-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
181 lines (165 loc) · 5.18 KB
/
index.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
// Copyright (c) 2019 Martin Giger
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
const dgram = require('dgram');
const easyLink = require("./easylink");
const socket = dgram.createSocket({
type: 'udp4'
});
const PORT = 8888,
PROTOCOL_VERSION = 3,
TIMEOUT = 30000,
CMD = {
GET_WATT: 90,
CONTROL: 20,
BIND: 73
},
queue = [];
const makePacket = (sn, ip, cmd, data = {}) => {
return `V${PROTOCOL_VERSION}${JSON.stringify(Object.assign({
sn,
cmd
}, data))} ip=${ip}`;
};
exports.CMD = CMD;
exports.makeControlPacket = (state, port = 1) => {
return {
port,
state: state ? 1: 0
};
};
exports.makeBindServerPacket = (regId, url = 'www.maxsmart.ch', port = 5000) => {
const date = new Date();
return {
regid: regId,
zone: Math.round(date.getTimezoneOffset() / 1000) + 12,
url: url,
port: port,
time: Math.floor(Date.now() / 1000)
};
};
const formatDigit = (d) => d.toString().padStart(2, '0');
const makeDiscoveryPacket = () => {
const now = new Date();
return `00dv=all,${now.getFullYear()}-${formatDigit(now.getMonth() + 1)}-${formatDigit(now.getDate())},${formatDigit(now.getHours())}:${formatDigit(now.getMinutes())}:${formatDigit(now.getSeconds())},${Math.round(now.getTimezoneOffset() / 1000) + 12};`
};
exports.isMaxSmart2Plug = (device) => device.sn.startsWith("SWW1");
exports.discoverDevices = async (deviceListener, timeout = 10000) => {
const discoSocket = dgram.createSocket({
type: 'udp4'
});
const packet = makeDiscoveryPacket();
discoSocket.on('message', (msg, rinfo) => {
const { data } = JSON.parse(msg.toString('utf8'));
deviceListener({
sn: data.sn,
ip: rinfo.address,
sak: data.sak,
mac: data.mac,
regId: data.regid,
version: data.ver,
name: data.name
});
});
await new Promise((resolve) => discoSocket.bind(8890, resolve));
discoSocket.setBroadcast(true);
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
discoSocket.setBroadcast(false);
discoSocket.close();
resolve();
}, 10000);
discoSocket.send(Buffer.from(packet), 8888, "255.255.255.255", (err) => {
if(err) {
discoSocket.close();
clearTimeout(timeout);
reject(err);
}
});
});
};
exports.send = (sn, ip, command, data = {}, timeout = TIMEOUT) => new Promise((resolve, reject) => {
const existing = queue.findIndex((q) => q.ip === ip && command === command);
if(existing > 0) {
queue[existing].reject(new Error("Time out"));
queue.splice(existing, 1);
}
const packet = makePacket(sn, ip, command, data);
const buffer = Buffer.from(packet, 'utf8');
const item = {
resolve(arg) {
resolve(arg);
clearTimeout(this.timeout);
},
reject(err) {
reject(err);
const index = queue.findIndex((q) => q.resolve === resolve && q.reject === reject && q.command === command && q.ip === ip);
queue.splice(index, 1);
clearTimeout(this.timeout);
},
command,
ip,
timeout: setTimeout((t) => {
item.reject({
code: 0,
data: "Timeout"
});
}, timeout)
};
queue.push(item);
socket.send(buffer, PORT, ip, (err) => {
if(err) {
item.reject(err);
}
});
});
exports.pair = async (opts) => {
await easyLink.sendWifiInfo(opts.wifiSSID, opts.wifiPassword);
const deviceInfo = await new Promise((resolve, reject) => {
exports.discoverDevices((device) => {
if(exports.isMaxSmart2Plug(device)) {
resolve(device);
}
}).then(resolve).catch(reject);
});
await exports.send(deviceInfo.sn, deviceInfo.ip, CMD.BIND, exports.makeBindServerPacket(opts.uid, opts.server, opts.port));
return deviceInfo;
};
socket.on('message', (msg, rinfo) => {
const rawMsg = msg.toString('utf8');
if(!rawMsg.startsWith(`V${PROTOCOL_VERSION}`)) {
console.error("Unrecognized response", rawMsg);
return;
}
const resp = JSON.parse(rawMsg.substr(2));
const waitingIndex = queue.findIndex((q) => q.command === resp.response && q.ip === rinfo.address);
if(waitingIndex < 0) {
console.error("Unexpected response", resp);
return;
}
const waiting = queue[waitingIndex];
queue.splice(waitingIndex, 1);
if(resp.code !== 200) {
waiting.reject(resp);
}
else if(resp.response === CMD.GET_WATT) {
const watt = resp.data.watt[0] / 1000;
const amp = resp.data.amp[0] / 1000;
waiting.resolve({
sn: resp.sn,
watt,
amp
});
}
else if(resp.response === CMD.CONTROL) {
waiting.resolve({
sn: resp.sn
});
}
else {
waiting.resolve(resp);
}
});
socket.on('error', console.error);
socket.bind();