This repository has been archived by the owner on Jul 24, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathankuoo-rec.js
58 lines (48 loc) · 1.67 KB
/
ankuoo-rec.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// ankuoo-rec.js
// ========
module.exports = function AnkuooRecApi(ip,mac,onCode,offCode) {
const PORT = '18530';
const HOST = '0.0.0.0';
var switchStatus = false;
var headerString = "01"+"44"+mac.replace(/:/g, '')+"10";
var headerData = Buffer.from(headerString,'hex');
var onCodeData = Buffer.from(onCode,'hex');
var onMessageData = Buffer.concat([headerData, onCodeData]);
var offCodeData = Buffer.from(offCode,'hex');
var offMessageData = Buffer.concat([headerData, offCodeData]);
function sendPacket(message){
var client = dgram.createSocket('udp4');
client.send(message, 0, message.length, PORT, ip, function(err, bytes) {
// DEBUG: Commented out to avoid crashing homebridge
//if (err) throw err;
client.close();
});
}
var dgram = require('dgram');
var server = dgram.createSocket('udp4');
server.on('listening', function () {
var address = server.address();
//DEBUG: comment out, not useful while testing with homebridge.
//console.log('UDP Server listening on ' + address.address + ":" + address.port);
});
server.on('message', function (message, remote) {
// consider only the payload
var messageCode = message.slice(9);
// consider valid only packets sent by the switch and that are not identical to the ones we sent (avoids duplicates)
if(remote.address==ip && !messageCode.equals(onCodeData) && !messageCode.equals(offCodeData)){
switchStatus = !switchStatus;
}
});
server.bind(PORT, HOST);
return {
getStatus: function() {
return switchStatus;
},
setStatus: function(status) {
if(status)
sendPacket(onMessageData);
else
sendPacket(offMessageData);
}
};
};