From ea7a4b1955107f9ba056002e04821044e331572e Mon Sep 17 00:00:00 2001 From: Koen Kanters Date: Sat, 23 Feb 2019 16:22:01 +0100 Subject: [PATCH] Remove last_seen from state when last_seen is disabled. https://github.com/Koenkk/zigbee2mqtt/issues/1075 --- lib/state.js | 24 ++++++++++++++++++++++++ lib/util/settings.js | 5 +++++ 2 files changed, 29 insertions(+) diff --git a/lib/state.js b/lib/state.js index 4cb133dad..c0d3addf5 100644 --- a/lib/state.js +++ b/lib/state.js @@ -1,6 +1,7 @@ const logger = require('./util/logger'); const data = require('./util/data'); const fs = require('fs'); +const settings = require('./util/settings'); const saveInterval = 1000 * 60 * 5; // 5 minutes @@ -9,6 +10,8 @@ class State { this.state = {}; this.file = data.joinPath('state.json'); this.timer = null; + + this.handleSettingsChanged = this.handleSettingsChanged.bind(this); } start() { @@ -17,6 +20,27 @@ class State { // Save the state on every interval this.clearTimer(); this.timer = setInterval(() => this.save(), saveInterval); + + // Listen for on settings changed events. + settings.addOnChangeHandler(this.handleSettingsChanged); + + this.checkLastSeen(); + } + + handleSettingsChanged() { + this.checkLastSeen(); + } + + checkLastSeen() { + if (settings.get().advanced.last_seen === 'disable') { + Object.values(this.state).forEach((s) => { + if (s.hasOwnProperty('last_seen')) { + delete s.last_seen; + } + }); + + this.save(); + } } clearTimer() { diff --git a/lib/util/settings.js b/lib/util/settings.js index c21e7d0fa..37ca50931 100644 --- a/lib/util/settings.js +++ b/lib/util/settings.js @@ -5,6 +5,8 @@ const file = data.joinPath('configuration.yaml'); const objectAssignDeep = require(`object-assign-deep`); const path = require('path'); +const onChangeHandlers = []; + const defaults = { permit_join: false, mqtt: { @@ -65,6 +67,7 @@ let settings = read(); function writeRead() { write(); settings = read(); + onChangeHandlers.forEach((handler) => handler()); } function write() { @@ -173,4 +176,6 @@ module.exports = { getGroupIDByFriendlyName: (friendlyName) => getGroupIDByFriendlyName(friendlyName), changeFriendlyName: (old, new_) => changeFriendlyName(old, new_), changeDeviceOptions: (ieeeAddr, options) => changeDeviceOptions(ieeeAddr, options), + + addOnChangeHandler: (handler) => onChangeHandlers.push(handler), };