zigbee2mqtt/lib/extension/bridgeConfig.js

234 lines
7.3 KiB
JavaScript
Raw Normal View History

2018-11-16 12:23:11 -07:00
const settings = require('../util/settings');
const logger = require('../util/logger');
const zigbeeShepherdConverters = require('zigbee-shepherd-converters');
const configRegex = new RegExp(`${settings.get().mqtt.base_topic}/bridge/config/\\w+`, 'g');
const allowedLogLevels = ['error', 'warn', 'info', 'debug'];
class BridgeConfig {
constructor(zigbee, mqtt, state, publishEntityState) {
2018-11-16 12:23:11 -07:00
this.zigbee = zigbee;
this.mqtt = mqtt;
this.state = state;
this.publishEntityState = publishEntityState;
2018-11-16 12:23:11 -07:00
// Bind functions
this.permitJoin = this.permitJoin.bind(this);
this.lastSeen = this.lastSeen.bind(this);
this.elapsed = this.elapsed.bind(this);
this.reset = this.reset.bind(this);
2018-11-16 12:23:11 -07:00
this.logLevel = this.logLevel.bind(this);
this.devices = this.devices.bind(this);
this.rename = this.rename.bind(this);
this.remove = this.remove.bind(this);
2019-01-08 11:00:02 -07:00
this.ban = this.ban.bind(this);
this.deviceOptions = this.deviceOptions.bind(this);
2018-11-16 12:23:11 -07:00
// Set supported options
this.supportedOptions = {
'permit_join': this.permitJoin,
'last_seen': this.lastSeen,
'elapsed': this.elapsed,
'reset': this.reset,
2018-11-16 12:23:11 -07:00
'log_level': this.logLevel,
'devices': this.devices,
'rename': this.rename,
'remove': this.remove,
2019-01-08 11:00:02 -07:00
'ban': this.ban,
'device_options': this.deviceOptions,
2018-11-16 12:23:11 -07:00
};
}
deviceOptions(topic, message) {
let json = null;
try {
json = JSON.parse(message.toString());
} catch (e) {
logger.error('Failed to parse message as JSON');
return;
}
if (!json.hasOwnProperty('friendly_name') || !json.hasOwnProperty('options')) {
logger.error('Invalid JSON message, should contain "friendly_name" and "options"');
return;
}
const ieeeAddr = settings.getIeeeAddrByFriendlyName(json.friendly_name);
if (!ieeeAddr) {
logger.error(`Failed to find device '${json.friendly_name}'`);
return;
}
settings.changeDeviceOptions(ieeeAddr, json.options);
logger.info(`Changed device specific options of '${json.friendly_name}' (${JSON.stringify(json.options)})`);
}
2018-11-16 12:23:11 -07:00
permitJoin(topic, message) {
this.zigbee.permitJoin(message.toString().toLowerCase() === 'true', () => this.publish());
2018-11-16 12:23:11 -07:00
}
reset(topic, message) {
this.zigbee.softReset((error) => {
if (error) {
logger.error('Soft reset failed');
} else {
logger.info('Soft resetted ZNP');
}
});
}
lastSeen(topic, message) {
const allowed = ['disable', 'ISO_8601', 'epoch', 'ISO_8601_local'];
message = message.toString();
if (!allowed.includes(message)) {
logger.error(`${message} is not an allowed value, possible: ${allowed}`);
return;
}
settings.set(['advanced', 'last_seen'], message);
logger.info(`Set last_seen to ${message}`);
}
elapsed(topic, message) {
const allowed = ['true', 'false'];
message = message.toString();
if (!allowed.includes(message)) {
logger.error(`${message} is not an allowed value, possible: ${allowed}`);
return;
}
settings.set(['advanced', 'elapsed'], message === 'true');
logger.info(`Set elapsed to ${message}`);
}
2018-11-16 12:23:11 -07:00
logLevel(topic, message) {
const level = message.toString().toLowerCase();
if (allowedLogLevels.includes(level)) {
logger.info(`Switching log level to '${level}'`);
logger.transports.console.level = level;
logger.transports.file.level = level;
} else {
logger.error(`Could not set log level to '${level}'. Allowed level: '${allowedLogLevels.join(',')}'`);
}
this.publish();
2018-11-16 12:23:11 -07:00
}
devices(topic, message) {
const devices = this.zigbee.getAllClients().map((device) => {
const mappedDevice = zigbeeShepherdConverters.findByZigbeeModel(device.modelId);
const friendlyDevice = settings.getDevice(device.ieeeAddr);
return {
ieeeAddr: device.ieeeAddr,
type: device.type,
model: mappedDevice ? mappedDevice.model : device.modelId,
friendly_name: friendlyDevice ? friendlyDevice.friendly_name : device.ieeeAddr,
};
});
this.mqtt.log('devices', devices);
}
rename(topic, message) {
const invalid = `Invalid rename message format expected {old: 'friendly_name', new: 'new_name} ` +
`got ${message.toString()}`;
let json = null;
try {
json = JSON.parse(message.toString());
} catch (e) {
logger.error(invalid);
return;
}
// Validate message
if (!json.new || !json.old) {
logger.error(invalid);
return;
}
if (settings.changeFriendlyName(json.old, json.new)) {
logger.info(`Successfully renamed - ${json.old} to ${json.new} `);
2019-02-13 11:49:06 -07:00
this.mqtt.log('device_renamed', {from: json.old, to: json.new});
2018-11-16 12:23:11 -07:00
} else {
logger.error(`Failed to renamed - ${json.old} to ${json.new}`);
return;
}
}
remove(topic, message) {
2019-01-08 11:00:02 -07:00
this.removeOrBan(false, message);
}
ban(topic, message) {
this.removeOrBan(true, message);
}
removeOrBan(ban, message) {
2018-11-16 12:23:11 -07:00
message = message.toString();
const IDByFriendlyName = settings.getIeeeAddrByFriendlyName(message);
const deviceID = IDByFriendlyName ? IDByFriendlyName : message;
const device = this.zigbee.getDevice(deviceID);
const cleanup = () => {
// Remove from configuration.yaml
settings.removeDevice(deviceID);
// Remove from state
this.state.remove(deviceID);
2019-01-08 11:00:02 -07:00
logger.info(`Successfully ${ban ? 'banned' : 'removed'} ${deviceID}`);
this.mqtt.log(ban ? 'device_banned' : 'device_removed', message);
2018-11-16 12:23:11 -07:00
};
// Remove from zigbee network.
if (device) {
2019-01-08 11:00:02 -07:00
this.zigbee.removeDevice(deviceID, ban, (error) => {
2018-11-16 12:23:11 -07:00
if (!error) {
cleanup();
} else {
2019-01-08 11:00:02 -07:00
logger.error(`Failed to ${ban ? 'ban' : 'remove'} ${deviceID}`);
2018-11-16 12:23:11 -07:00
}
});
} else {
cleanup();
}
}
onMQTTConnected() {
this.mqtt.subscribe(`${settings.get().mqtt.base_topic}/bridge/config/+`);
2019-02-13 11:49:06 -07:00
this.publish();
2018-11-16 12:23:11 -07:00
}
onMQTTMessage(topic, message) {
if (!topic.match(configRegex)) {
return false;
}
const option = topic.split('/').slice(-1)[0];
if (!this.supportedOptions.hasOwnProperty(option)) {
return false;
}
this.supportedOptions[option](topic, message);
return true;
}
publish() {
const topic = `bridge/config`;
const payload = {
log_level: logger.transports.console.level,
permit_join: this.zigbee.getPermitJoin(),
};
this.mqtt.publish(topic, JSON.stringify(payload), {retain: true, qos: 0}, null);
}
2018-11-16 12:23:11 -07:00
}
module.exports = BridgeConfig;