Refactor message parsing.

This commit is contained in:
Koen Kanters 2018-04-09 17:09:52 +02:00
parent 366b5be765
commit 63a05fc443
2 changed files with 67 additions and 69 deletions

100
index.js
View File

@ -5,6 +5,7 @@ const ZShepherd = require('zigbee-shepherd');
const mqtt = require('mqtt')
const ArgumentParser = require('argparse').ArgumentParser;
const fs = require('fs');
const parsers = require('./parsers');
const configFile = `${__dirname}/data/config.json`
@ -85,7 +86,7 @@ function handleReady() {
console.log(`Currently ${devices.length} devices are joined:`);
devices.forEach((device) => {
console.log(device.ieeeAddr + ' ' + device.nwkAddr + ' ' + device.modelId);
console.log(`${device.ieeeAddr} ${device.nwkAddr} ${device.modelId}`);
});
// Set all Xiaomi devices to be online, so shepherd won't try
@ -114,77 +115,38 @@ function handleConnect() {
}
function handleMessage(msg) {
// debug('msg: ' + util.inspect(msg, false, null));
var pl = null;
var topic = 'xiaomiZb/';
switch (msg.type) {
case 'devIncoming':
console.log('Device: ' + msg.data + ' joining the network!');
break;
case 'attReport':
console.log('attreport: ' + msg.endpoints[0].device.ieeeAddr + ' ' + msg.endpoints[0].devId + ' ' + msg.endpoints[0].epId + ' ' + util.inspect(msg.data, false, null));
// defaults, will be extended or overridden based on device and message
topic += msg.endpoints[0].device.ieeeAddr.substr(2);
pl=1;
switch (msg.data.cid) {
case 'genOnOff': // various switches
topic += '/' + msg.endpoints[0].epId;
pl = msg.data.data['onOff'];
break;
case 'msTemperatureMeasurement': // Aqara Temperature/Humidity
topic += "/temperature";
pl = parseFloat(msg.data.data['measuredValue']) / 100.0;
break;
case 'msRelativeHumidity':
topic += "/humidity";
pl = parseFloat(msg.data.data['measuredValue']) / 100.0;
break;
case 'msPressureMeasurement':
topic += "/pressure";
pl = parseFloat(msg.data.data['16']) / 10.0;
break;
case 'msOccupancySensing': // motion sensor
topic += "/occupancy";
pl = msg.data.data['occupancy'];
break;
case 'msIlluminanceMeasurement':
topic += "/illuminance";
pl = msg.data.data['measuredValue'];
break;
}
switch (msg.endpoints[0].devId) {
case 260: // WXKG01LM switch
if (msg.data.data['onOff'] == 0) { // click down
perfy.start(msg.endpoints[0].device.ieeeAddr); // start timer
pl = null; // do not send mqtt message
} else if (msg.data.data['onOff'] == 1) { // click release
if (perfy.exists(msg.endpoints[0].device.ieeeAddr)) { // do we have timer running
var clicktime = perfy.end(msg.endpoints[0].device.ieeeAddr); // end timer
if (clicktime.seconds > 0 || clicktime.milliseconds > 240) { // seems like a long press so ..
topic = topic.slice(0,-1) + '2'; //change topic to 2
pl = clicktime.seconds + Math.floor(clicktime.milliseconds) + ''; // and payload to elapsed seconds
}
}
} else if (msg.data.data['32768']) { // multiple clicks
pl = msg.data.data['32768'];
}
}
break;
default:
// console.log(util.inspect(msg, false, null));
// Not deal with other msg.type in this example
break;
if (msg.type !== 'attReport') {
return;
}
if (pl != null) { // only publish message if we have not set payload to null
console.log("MQTT Reporting to ", topic, " value ", pl)
client.publish(topic, pl.toString());
const device = msg.endpoints[0].device;
// Check if new device, add to config if new.
if (!config.devices[device.ieeeAddr]) {
console.log(`Detected new device: ${device.ieeeAddr} ${device.nwkAddr} ${device.modelId}`);
config.devices[device.ieeeAddr] = device.ieeeAddr;
writeConfig(config);
}
// Check if we have a parser for this type of message.
const deviceID = msg.endpoints[0].devId;
const parser = parsers.find((p) => p.supportedDevices.includes(deviceID));
if (!parser) {
console.log(`
WARNING: No parser available for deviceID: ${deviceID}
Please report on https://github.com/Koenkk/xiaomi-zb2mqtt/issues
to add support for your device`);
return;
}
// Parse the message.
const friendlyName = config.devices[device.ieeeAddr];
const payload = parser.parse(msg).toString();
const topic = `xiaomi/${friendlyName}/${parser.topic}`;
// Send the message.
console.log(`MQTT publish, topic: '${topic}', payload: '${payload}'`);
client.publish(topic, payload);
}
function handleQuit() {

36
parsers.js Normal file
View File

@ -0,0 +1,36 @@
module.exports = [
{
supportedDevices: [260],
description: 'WXKG01LM switch (260)',
topic: 'switch',
parse: (msg) => {
return msg.data.data['onOff'] === 0 ? 'on' : 'off';
}
},
]
// // TODO
// 1001: {
// topic: 'temperature',
// payload: (msg) => parseFloat(msg.data.data['measuredValue']) / 100.0,
// },
// // TODO
// 1002: {
// topic: 'humidity',
// payload: (msg) => parseFloat(msg.data.data['measuredValue']) / 100.0,
// },
// // TODO
// 1003: {
// topic: 'pressure',
// payload: (msg) => parseFloat(msg.data.data['16']) / 10.0,
// },
// // TODO
// 1004: {
// topic: 'occupancy',
// payload: (msg) => msg.data.data['occupancy'],
// },
// // TODO
// 1005: {
// topic: 'illuminance',
// payload: (msg) => msg.data.data['measuredValue'],
// },