zigbee2mqtt/lib/state.js

97 lines
2.3 KiB
JavaScript
Raw Normal View History

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
class State {
constructor() {
this.state = {};
this.file = data.joinPath('state.json');
2018-11-28 11:34:37 -07:00
this.timer = null;
this.handleSettingsChanged = this.handleSettingsChanged.bind(this);
2018-11-28 11:34:37 -07:00
}
start() {
this._load();
// Save the state on every interval
2018-11-28 11:34:37 -07:00
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();
}
}
2018-11-28 11:34:37 -07:00
clearTimer() {
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
}
stop() {
this.clearTimer();
this.save();
}
_load() {
if (fs.existsSync(this.file)) {
try {
this.state = JSON.parse(fs.readFileSync(this.file, 'utf8'));
logger.debug(`Loaded state from file ${this.file}`);
} catch (e) {
logger.debug(`Failed to load state from file ${this.file} (corrupt file?)`);
}
} else {
2019-02-19 11:16:18 -07:00
logger.debug(`Can't load state from file ${this.file} (doesn't exist)`);
}
}
save() {
logger.debug(`Saving state to file ${this.file}`);
const json = JSON.stringify(this.state, null, 4);
fs.writeFileSync(this.file, json, 'utf8');
}
2018-11-16 12:23:11 -07:00
exists(ieeeAddr) {
return this.state.hasOwnProperty(ieeeAddr);
}
2018-11-16 12:23:11 -07:00
get(ieeeAddr) {
return this.state[ieeeAddr];
}
2018-11-16 12:23:11 -07:00
set(ieeeAddr, state) {
this.state[ieeeAddr] = state;
}
2018-11-16 12:23:11 -07:00
remove(ieeeAddr) {
if (this.exists(ieeeAddr)) {
delete this.state[ieeeAddr];
}
}
}
module.exports = State;