2
0
Files
node-red-contrib-mi-devices/node-red-contrib-xiaomi-socket/xiaomi-socket.js

79 lines
3.0 KiB
JavaScript
Raw Normal View History

2018-01-03 12:12:45 +01:00
const crypto = require("crypto");
2018-01-03 12:12:45 +01:00
module.exports = (RED) => {
function XiaomiPlugNode(config) {
RED.nodes.createNode(this, config);
this.gateway = RED.nodes.getNode(config.gateway);
this.sid = config.sid;
2017-06-30 22:02:50 +02:00
this.key = this.gateway.key;
var currentToken = "";
var state = "";
2018-01-03 12:12:45 +01:00
this.status({fill:"yellow", shape:"ring", text:"waiting for key"});
2017-07-03 22:41:43 +02:00
if (this.gateway && this.key != "") {
2018-01-03 12:12:45 +01:00
this.on('input', (msg) => {
var payload = msg.payload;
if (payload.cmd == "heartbeat" && payload.model == "gateway") {
var token = payload.token;
if (token) {
2017-06-30 22:02:50 +02:00
var cipher = crypto.createCipheriv('aes128', node.key, (new Buffer("17996d093d28ddb3ba695a2e6f58562e", "hex")));
var encoded_string = cipher.update(token, 'utf8', 'hex');
encoded_string += cipher.final('hex');
currentToken = encoded_string.substring(0,32);
if (state == "") {
node.status({fill:"yellow", shape:"dot", text:"unknown state"});
}
}
}
if (payload == 'on') {
var cmd =
{ "cmd":"write",
"sid": node.sid,
"model": "plug",
"data": JSON.stringify({"status":"on", "key": currentToken })
}
msg.payload = JSON.stringify(cmd);
node.send([[],[msg]]);
} else if (payload == "off") {
var cmd =
{ "cmd":"write",
"sid": node.sid,
"model": "plug",
"data": JSON.stringify({"status":"off", "key": currentToken })
}
msg.payload = JSON.stringify(cmd);
node.send([[],[msg]]);
} else if (payload.sid == node.sid && payload.model == "plug") {
var data = JSON.parse(payload.data)
if (currentToken == "") {
2017-07-02 18:11:19 +02:00
node.status({fill:"yellow", shape:"ring", text:"waiting for key"});
} else if (data.status && data.status == "on") {
node.status({fill:"green", shape:"dot", text:"on"});
state = "on";
} else if (data.status && data.status == "off") {
node.status({fill:"red", shape:"dot", text:"off"});
state = "off";
}
2018-01-03 12:12:45 +01:00
msg.payload = payload;
node.send([msg]);
}
});
2018-01-03 12:12:45 +01:00
} else if (this.key == "") {
node.status({fill:"red", shape:"dot", text:"no key configured"});
}
}
RED.nodes.registerType("xiaomi-plug", XiaomiPlugNode);
}