zigbee2mqtt/lib/zigbee.js

331 lines
10 KiB
JavaScript
Raw Normal View History

2018-04-18 09:25:40 -07:00
const ZShepherd = require('zigbee-shepherd');
const logger = require('./util/logger');
const settings = require('./util/settings');
2018-05-11 20:04:15 -07:00
const data = require('./util/data');
const utils = require('./util/utils');
const cieApp = require('./zapp/cie');
2019-02-01 11:04:49 -07:00
const Queue = require('queue');
const zclId = require('zcl-id');
2018-04-18 09:25:40 -07:00
const advancedSettings = settings.get().advanced;
2018-04-18 09:25:40 -07:00
const shepherdSettings = {
net: {
2018-11-16 12:23:11 -07:00
panId: advancedSettings.pan_id,
extPanId: advancedSettings.ext_pan_id,
2018-11-16 12:23:11 -07:00
channelList: [advancedSettings.channel],
precfgkey: settings.get().advanced.network_key,
},
2018-05-17 08:48:41 -07:00
dbPath: data.joinPath('database.db'),
2018-06-14 12:37:19 -07:00
sp: {
2018-11-16 12:23:11 -07:00
baudRate: advancedSettings.baudrate,
rtscts: advancedSettings.rtscts,
2018-06-14 12:37:19 -07:00
},
2018-04-18 09:25:40 -07:00
};
const defaultCfg = {
manufSpec: 0,
disDefaultRsp: 0,
};
2019-02-01 11:04:49 -07:00
const delay = 170;
2018-06-14 12:37:19 -07:00
logger.debug(`Using zigbee-shepherd with settings: '${JSON.stringify(shepherdSettings)}'`);
2018-04-18 09:25:40 -07:00
class Zigbee {
2018-11-16 12:23:11 -07:00
constructor() {
this.onReady = this.onReady.bind(this);
this.onMessage = this.onMessage.bind(this);
this.onError = this.onError.bind(this);
this.messageHandler = null;
2019-02-01 11:04:49 -07:00
this.queue = new Queue();
this.queue.concurrency = 1;
2018-04-18 09:25:40 -07:00
}
2018-11-16 12:23:11 -07:00
start(messageHandler, callback) {
2018-04-18 09:25:40 -07:00
logger.info(`Starting zigbee-shepherd`);
2018-11-16 12:23:11 -07:00
this.messageHandler = messageHandler;
2018-04-18 09:25:40 -07:00
this.shepherd = new ZShepherd(settings.get().serial.port, shepherdSettings);
this.shepherd.start((error) => {
if (error) {
logger.info('Error while starting zigbee-shepherd, attemping to fix... (takes 60 seconds)');
this.shepherd.controller._znp.close((() => null));
setTimeout(() => {
2018-06-04 08:36:46 -07:00
logger.info(`Starting zigbee-shepherd`);
this.shepherd.start((error) => {
if (error) {
logger.error('Error while starting zigbee-shepherd!');
logger.error(
'Press the reset button on the stick (the one closest to the USB) and start again'
);
callback(error);
} else {
2018-11-16 12:23:11 -07:00
this.logStartupInfo();
callback(null);
}
});
2018-11-16 12:23:11 -07:00
}, utils.secondsToMilliseconds(60));
2018-04-18 09:25:40 -07:00
} else {
2018-11-16 12:23:11 -07:00
this.logStartupInfo();
callback(null);
2018-04-18 09:25:40 -07:00
}
});
// Register callbacks.
2018-11-16 12:23:11 -07:00
this.shepherd.on('ready', this.onReady);
this.shepherd.on('ind', this.onMessage);
this.shepherd.on('error', this.onError);
2018-04-18 09:25:40 -07:00
}
2018-11-16 12:23:11 -07:00
logStartupInfo() {
logger.info('zigbee-shepherd started');
logger.info(`Coordinator firmware version: '${this.shepherd.info().firmware.revision}'`);
logger.debug(`zigbee-shepherd info: ${JSON.stringify(this.shepherd.info())}`);
}
2018-05-21 02:49:02 -07:00
softReset(callback) {
this.shepherd.reset('soft', callback);
}
2018-04-18 09:25:40 -07:00
stop(callback) {
2019-02-01 16:57:51 -07:00
this.queue.stop();
2018-04-18 09:25:40 -07:00
this.shepherd.stop((error) => {
2018-05-17 08:20:46 -07:00
logger.info('zigbee-shepherd stopped');
2018-04-18 09:25:40 -07:00
callback(error);
});
}
2018-11-16 12:23:11 -07:00
onReady() {
// Mount cieApp
this.shepherd.mount(cieApp, (err, epId) => {
if (!err) {
2019-01-07 10:18:14 -07:00
logger.debug(`Mounted the cieApp (epId ${epId})`);
} else {
logger.error(`Failed to mount the cieApp`);
}
});
// Check if we have to turn off the led
2018-07-21 12:13:28 -07:00
if (settings.get().serial.disable_led) {
this.shepherd.controller.request('UTIL', 'ledControl', {ledid: 3, mode: 0});
}
2019-02-01 11:43:22 -07:00
// Wait some time before we start the queue, many calls skip this queue which hangs the stick
setTimeout(() => {
this.queue.autostart = true;
this.queue.start();
}, 2000);
logger.info('zigbee-shepherd ready');
}
2018-04-18 09:25:40 -07:00
2018-11-16 12:23:11 -07:00
onError(message) {
2018-05-17 08:48:41 -07:00
// This event may appear if zigbee-shepherd cannot decode bad packets (invalid checksum).
logger.error(message);
}
permitJoin(permit, callback) {
if (permit) {
logger.info('Zigbee: allowing new devices to join.');
} else {
logger.info('Zigbee: disabling joining new devices.');
2018-04-18 09:25:40 -07:00
}
this.shepherd.permitJoin(permit ? 255 : 0, (error) => {
2018-04-18 09:25:40 -07:00
if (error) {
logger.info(error);
}
if (callback) {
callback();
}
2018-04-18 09:25:40 -07:00
});
}
getPermitJoin() {
return this.shepherd.controller._permitJoinTime === 255;
}
getAllClients() {
return this.getDevices().filter((device) => device.type !== 'Coordinator');
}
2019-01-08 11:00:02 -07:00
removeDevice(deviceID, ban, callback) {
this.shepherd.remove(deviceID, {reJoin: !ban}, (error) => {
if (error) {
logger.warn(`Failed to remove '${deviceID}', trying force remove...`);
2018-11-16 12:23:11 -07:00
this.forceRemove(deviceID, callback);
2018-06-06 12:13:32 -07:00
} else {
callback(null);
2018-06-06 12:13:32 -07:00
}
});
}
2018-11-16 12:23:11 -07:00
forceRemove(deviceID, callback) {
2018-06-06 12:13:32 -07:00
const device = this.shepherd._findDevByAddr(deviceID);
2018-06-07 10:41:11 -07:00
if (device) {
return this.shepherd._unregisterDev(device, (error) => callback(error));
2018-06-07 10:41:11 -07:00
} else {
logger.warn(`Could not find ${deviceID} for force removal`);
callback(true);
2018-06-07 10:41:11 -07:00
}
}
2018-06-06 12:19:50 -07:00
2018-11-16 12:23:11 -07:00
onMessage(message) {
if (this.messageHandler) {
this.messageHandler(message);
2018-04-18 09:25:40 -07:00
}
}
getDevices() {
return this.shepherd.list();
}
getDevice(ieeeAddr) {
return this.getDevices().find((d) => d.ieeeAddr === ieeeAddr);
2018-04-27 14:58:46 -07:00
}
getCoordinator() {
const device = this.getDevices().find((d) => d.type === 'Coordinator');
return this.shepherd.find(device.ieeeAddr, 1);
}
getGroup(ID) {
return this.shepherd.getGroup(ID);
}
networkScan(callback) {
logger.info('Starting network scan...');
this.shepherd.lqiScan().then((result) => {
logger.info('Network scan completed');
callback(result);
});
}
2019-02-01 11:04:49 -07:00
getEndpoint(ieeeAddr, ep) {
// If no ep is given, the first endpoint will be returned
2018-05-30 13:28:08 -07:00
// Find device in zigbee-shepherd
2019-02-01 11:04:49 -07:00
const device = this.getDevice(ieeeAddr);
2018-05-30 13:28:08 -07:00
if (!device || !device.epList || !device.epList.length) {
2019-02-01 11:04:49 -07:00
logger.error(`Zigbee cannot determine endpoint for '${ieeeAddr}'`);
2018-05-30 13:28:08 -07:00
return null;
}
ep = ep ? ep : device.epList[0];
2019-02-01 11:04:49 -07:00
const endpoint = this.shepherd.find(ieeeAddr, ep);
return endpoint;
}
publish(entityID, entityType, cid, cmd, cmdType, zclData, cfg=defaultCfg, ep, callback) {
let entity = null;
if (entityType === 'device') {
entity = this.getEndpoint(entityID, ep);
} else if (entityType === 'group') {
entity = this.getGroup(entityID);
}
if (!entity) {
logger.error(
`Cannot publish message to ${entityType} because '${entityID}' is not known by zigbee-shepherd`
);
return;
}
this.queue.push((queueCallback) => {
logger.info(
`Zigbee publish to ${entityType} '${entityID}', ${cid} - ${cmd} - ` +
`${JSON.stringify(zclData)} - ${JSON.stringify(cfg)} - ${ep}`
);
const callback_ = (error, rsp) => {
if (error) {
logger.error(
`Zigbee publish to ${entityType} '${entityID}', ${cid} - ${cmd} - ${JSON.stringify(zclData)} ` +
`- ${JSON.stringify(cfg)} - ${ep} ` +
`failed with error ${error}`);
}
2019-02-01 18:14:31 -07:00
if (callback) {
callback(error, rsp);
}
};
if (cmdType === 'functional' && entity.functional) {
entity.functional(cid, cmd, zclData, cfg, callback_);
} else if (cmdType === 'foundation' && entity.foundation) {
entity.foundation(cid, cmd, zclData, cfg, callback_);
} else {
logger.error(`Unknown zigbee publish cmdType ${cmdType}`);
}
setTimeout(() => queueCallback(), delay);
});
}
2019-02-01 16:57:51 -07:00
ping(ieeeAddr, cb) {
const device = this.shepherd._findDevByAddr(ieeeAddr);
if (device) {
this.queue.push((queueCallback) => {
logger.debug(`Ping ${ieeeAddr}`);
this.shepherd.controller.checkOnline(device, (error) => {
if (error) {
logger.error(`Failed to ping ${ieeeAddr}`);
} else {
logger.debug(`Successfully pinged ${ieeeAddr}`);
}
2019-02-01 18:14:31 -07:00
if (cb) {
cb(error);
}
2019-02-01 16:57:51 -07:00
});
setTimeout(() => queueCallback(), delay);
});
}
}
bind(ep, cluster, target=this.getCoordinator()) {
2019-02-01 11:43:22 -07:00
const log = `for ${ep.device.ieeeAddr} - ${cluster}`;
this.queue.push((queueCallback) => {
logger.debug(`Setup binding ${log}`);
ep.bind(cluster, target, (error) => {
2019-02-01 11:43:22 -07:00
if (error) {
logger.error(`Failed to setup binding ${log} - (${error})`);
} else {
logger.debug(`Successfully setup binding ${log}`);
}
});
setTimeout(() => queueCallback(), delay);
});
}
report(ep, cluster, attribute, min, max, change) {
2019-02-01 11:04:49 -07:00
const attrId = zclId.attr(cluster, attribute).value;
const dataType = zclId.attrType(cluster, attribute).value;
const cfg = {direction: 0, attrId, dataType, minRepIntval: min, maxRepIntval: max, repChange: change};
const log = `for ${ep.device.ieeeAddr} - ${cluster} - ${attribute}`;
this.queue.push((queueCallback) => {
logger.debug(`Setup reporting ${log}`);
2019-02-01 18:00:20 -07:00
ep.foundation(cluster, 'configReport', [cfg], defaultCfg, (error) => {
2019-02-01 11:04:49 -07:00
if (error) {
logger.error(`Failed to setup reporting ${log} - (${error})`);
} else {
logger.debug(`Successfully setup reporting ${log}`);
}
});
setTimeout(() => queueCallback(), delay);
});
2018-04-18 09:25:40 -07:00
}
}
module.exports = Zigbee;