node-miio 0.0.0-dev-20250810-f1674d0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.editorconfig +21 -0
- package/.eslintrc +32 -0
- package/.github/workflows/build.yml +50 -0
- package/.github/workflows/codecov.yml +35 -0
- package/.github/workflows/codeql.yml +24 -0
- package/.github/workflows/publish-dev-from-main.yml +92 -0
- package/.github/workflows/publish-release-to-npm.yml +48 -0
- package/CONTRIBUTING.md +104 -0
- package/LICENSE.md +20 -0
- package/README.md +216 -0
- package/cli/commands/configure.js +69 -0
- package/cli/commands/control.js +54 -0
- package/cli/commands/discover.js +36 -0
- package/cli/commands/inspect.js +197 -0
- package/cli/commands/protocol/call.js +66 -0
- package/cli/commands/protocol/json-dump.js +52 -0
- package/cli/commands/protocol/packet.js +29 -0
- package/cli/commands/protocol.js +8 -0
- package/cli/commands/tokens/update.js +58 -0
- package/cli/commands/tokens.js +8 -0
- package/cli/device-finder.js +66 -0
- package/cli/index.js +9 -0
- package/cli/log.js +89 -0
- package/docs/advanced-api.md +103 -0
- package/docs/devices/README.md +111 -0
- package/docs/devices/air-purifier.md +142 -0
- package/docs/devices/controller.md +89 -0
- package/docs/devices/gateway.md +41 -0
- package/docs/devices/humidifier.md +136 -0
- package/docs/devices/light.md +141 -0
- package/docs/devices/power-outlet.md +56 -0
- package/docs/devices/power-plug.md +69 -0
- package/docs/devices/power-strip.md +73 -0
- package/docs/devices/sensor.md +74 -0
- package/docs/devices/vacuum.md +80 -0
- package/docs/devices/wall-switch.md +62 -0
- package/docs/management.md +109 -0
- package/docs/missing-devices.md +48 -0
- package/docs/protocol.md +77 -0
- package/docs/reporting-issues.md +47 -0
- package/example.js +11 -0
- package/lib/checkResult.js +13 -0
- package/lib/connectToDevice.js +62 -0
- package/lib/device.js +290 -0
- package/lib/device_info.js +329 -0
- package/lib/device_info.test.js +337 -0
- package/lib/devices/air-monitor.js +53 -0
- package/lib/devices/air-purifier.js +162 -0
- package/lib/devices/capabilities/battery-level.js +16 -0
- package/lib/devices/capabilities/buzzer.js +78 -0
- package/lib/devices/capabilities/changeable-led-brightness.js +48 -0
- package/lib/devices/capabilities/colorable.js +14 -0
- package/lib/devices/capabilities/dimmable.js +14 -0
- package/lib/devices/capabilities/mode.js +13 -0
- package/lib/devices/capabilities/power.js +14 -0
- package/lib/devices/capabilities/sensor.js +50 -0
- package/lib/devices/capabilities/switchable-led.js +49 -0
- package/lib/devices/chuangmi.plug.v1.js +61 -0
- package/lib/devices/eyecare-lamp2.js +179 -0
- package/lib/devices/gateway/86sw1.js +28 -0
- package/lib/devices/gateway/86sw2.js +44 -0
- package/lib/devices/gateway/ctrl_ln1.js +44 -0
- package/lib/devices/gateway/ctrl_ln2.js +53 -0
- package/lib/devices/gateway/ctrl_neutral1.js +44 -0
- package/lib/devices/gateway/ctrl_neutral2.js +53 -0
- package/lib/devices/gateway/cube.js +55 -0
- package/lib/devices/gateway/developer-api.js +120 -0
- package/lib/devices/gateway/light-channel.js +32 -0
- package/lib/devices/gateway/light-mixin.js +71 -0
- package/lib/devices/gateway/magnet.js +29 -0
- package/lib/devices/gateway/magnet2.js +13 -0
- package/lib/devices/gateway/motion.js +27 -0
- package/lib/devices/gateway/motion2.js +31 -0
- package/lib/devices/gateway/plug.js +45 -0
- package/lib/devices/gateway/sensor_ht.js +17 -0
- package/lib/devices/gateway/subdevice.js +227 -0
- package/lib/devices/gateway/subdevices.js +37 -0
- package/lib/devices/gateway/switch.js +29 -0
- package/lib/devices/gateway/switch2.js +27 -0
- package/lib/devices/gateway/voltage.js +28 -0
- package/lib/devices/gateway/weather.js +22 -0
- package/lib/devices/gateway.js +244 -0
- package/lib/devices/humidifier.js +162 -0
- package/lib/devices/mijiavacuum.js +22 -0
- package/lib/devices/philips-light-bulb.js +73 -0
- package/lib/devices/power-plug.js +26 -0
- package/lib/devices/power-strip.js +38 -0
- package/lib/devices/vacuum.js +412 -0
- package/lib/devices/viomivacuum.js +250 -0
- package/lib/devices/yeelight.color.js +6 -0
- package/lib/devices/yeelight.js +286 -0
- package/lib/devices/yeelight.mono.js +9 -0
- package/lib/discovery.js +192 -0
- package/lib/index.js +40 -0
- package/lib/infoFromHostname.js +24 -0
- package/lib/management.js +102 -0
- package/lib/models.js +77 -0
- package/lib/network.js +234 -0
- package/lib/packet.js +191 -0
- package/lib/placeholder.js +12 -0
- package/lib/safeishJSON.js +14 -0
- package/lib/tokens.js +129 -0
- package/npm-shrinkwrap.json +853 -0
- package/package.json +40 -0
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const debug = require('debug');
|
|
4
|
+
const Packet = require('./packet');
|
|
5
|
+
const safeishJSON = require('./safeishJSON');
|
|
6
|
+
|
|
7
|
+
const ERRORS = {
|
|
8
|
+
'-5001': (method, args, err) =>
|
|
9
|
+
err.message === 'invalid_arg' ? 'Invalid argument' : err.message,
|
|
10
|
+
'-5005': (method, args, err) =>
|
|
11
|
+
err.message === 'params error' ? 'Invalid argument' : err.message,
|
|
12
|
+
'-10000': (method) => 'Method `' + method + '` is not supported',
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
class DeviceInfo {
|
|
16
|
+
constructor(parent, id, address, port) {
|
|
17
|
+
this.parent = parent;
|
|
18
|
+
this.packet = new Packet();
|
|
19
|
+
|
|
20
|
+
this.address = address;
|
|
21
|
+
this.port = port;
|
|
22
|
+
|
|
23
|
+
// Tracker for all promises associated with this device
|
|
24
|
+
this.promises = new Map();
|
|
25
|
+
this.lastId = 0;
|
|
26
|
+
|
|
27
|
+
this.id = id;
|
|
28
|
+
this.debug = id ? debug('thing:miio:' + id) : debug('thing:miio:pending');
|
|
29
|
+
|
|
30
|
+
// Get if the token has been manually changed
|
|
31
|
+
this.tokenChanged = false;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
get token() {
|
|
35
|
+
return this.packet.token;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
set token(t) {
|
|
39
|
+
this.debug('Using manual token:', t.toString('hex'));
|
|
40
|
+
this.packet.token = t;
|
|
41
|
+
this.tokenChanged = true;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Enrich this device with detailed information about the model. This will
|
|
46
|
+
* simply call miIO.info.
|
|
47
|
+
*/
|
|
48
|
+
async enrich() {
|
|
49
|
+
if (!this.id) {
|
|
50
|
+
throw new Error('Device has no identifier yet, handshake needed');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (this.model && !this.tokenChanged && this.packet.token) {
|
|
54
|
+
// This device has model info and a valid token
|
|
55
|
+
return Promise.resolve();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (this.packet.token) {
|
|
59
|
+
if (this.tokenChanged) {
|
|
60
|
+
this.autoToken = false;
|
|
61
|
+
} else {
|
|
62
|
+
this.autoToken = true;
|
|
63
|
+
this.debug('Using automatic token:', this.packet.token.toString('hex'));
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
if (!this.enrichPromise) {
|
|
68
|
+
this.enrichPromise = this.call('miIO.info');
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
try {
|
|
72
|
+
const { model } = await this.enrichPromise;
|
|
73
|
+
this.model = model;
|
|
74
|
+
this.tokenChanged = false;
|
|
75
|
+
} catch (err) {
|
|
76
|
+
if (err.code === 'missing-token') {
|
|
77
|
+
err.device = this;
|
|
78
|
+
throw err;
|
|
79
|
+
} else if (this.packet.token) {
|
|
80
|
+
// Could not call the info method, this might be either a timeout or a token problem
|
|
81
|
+
const e = new Error(
|
|
82
|
+
'Could not connect to device, token might be wrong'
|
|
83
|
+
);
|
|
84
|
+
e.code = 'connection-failure';
|
|
85
|
+
e.device = this;
|
|
86
|
+
throw e;
|
|
87
|
+
} else {
|
|
88
|
+
const e = new Error(
|
|
89
|
+
'Could not connect to device, token needs to be specified'
|
|
90
|
+
);
|
|
91
|
+
e.code = 'missing-token';
|
|
92
|
+
e.device = this;
|
|
93
|
+
throw e;
|
|
94
|
+
}
|
|
95
|
+
} finally {
|
|
96
|
+
this.enriched = true;
|
|
97
|
+
this.enrichPromise = null;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
onMessage(msg) {
|
|
102
|
+
try {
|
|
103
|
+
this.packet.raw = msg;
|
|
104
|
+
} catch (ex) {
|
|
105
|
+
this.debug('<- Unable to parse packet', ex);
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
let data = this.packet.data;
|
|
110
|
+
if (data === null) {
|
|
111
|
+
this.debug('<-', 'Handshake reply:', this.packet.checksum);
|
|
112
|
+
this.packet.handleHandshakeReply();
|
|
113
|
+
|
|
114
|
+
if (this.handshakeResolve) {
|
|
115
|
+
this.handshakeResolve();
|
|
116
|
+
}
|
|
117
|
+
} else {
|
|
118
|
+
// Handle null-terminated strings
|
|
119
|
+
if (data[data.length - 1] === 0) {
|
|
120
|
+
data = data.slice(0, data.length - 1);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Parse and handle the JSON message
|
|
124
|
+
let str = data.toString('utf8');
|
|
125
|
+
|
|
126
|
+
// Remove non-printable characters to help with invalid JSON from devices
|
|
127
|
+
// eslint-disable-next-line no-control-regex
|
|
128
|
+
str = str.replace(/[\x00-\x09\x0B-\x0C\x0E-\x1F\x7F-\x9F]/g, '');
|
|
129
|
+
|
|
130
|
+
this.debug('<- Message: `' + str + '`');
|
|
131
|
+
try {
|
|
132
|
+
let object = safeishJSON(str);
|
|
133
|
+
|
|
134
|
+
const p = this.promises.get(object.id);
|
|
135
|
+
if (!p) return;
|
|
136
|
+
if (typeof object.result !== 'undefined') {
|
|
137
|
+
p.resolve(object.result);
|
|
138
|
+
} else {
|
|
139
|
+
p.reject(object.error);
|
|
140
|
+
}
|
|
141
|
+
} catch (ex) {
|
|
142
|
+
this.debug('<- Invalid JSON', ex);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async handshake() {
|
|
148
|
+
if (!this.packet.needsHandshake) {
|
|
149
|
+
return Promise.resolve(this.token);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// If a handshake is already in progress use it
|
|
153
|
+
if (!this.handshakePromise) {
|
|
154
|
+
this.handshakePromise = this._sendHandshakePackage();
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
try {
|
|
158
|
+
return await Promise.race([this.handshakePromise, this._setTimeout()]);
|
|
159
|
+
} catch (err) {
|
|
160
|
+
if (err.code === 'timeout') {
|
|
161
|
+
this.debug('<- Handshake timed out');
|
|
162
|
+
}
|
|
163
|
+
throw err;
|
|
164
|
+
} finally {
|
|
165
|
+
this.handshakeResolve = null;
|
|
166
|
+
this.handshakePromise = null;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
async _sendHandshakePackage() {
|
|
171
|
+
const waitForResponse = this._waitForHandshakeResponse();
|
|
172
|
+
// Create and send the handshake data
|
|
173
|
+
this.packet.handshake();
|
|
174
|
+
await this._sendPacket();
|
|
175
|
+
return await waitForResponse;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
async _sendPacket() {
|
|
179
|
+
return await new Promise((resolve, reject) => {
|
|
180
|
+
const data = this.packet.raw;
|
|
181
|
+
this.parent.socket.send(
|
|
182
|
+
data,
|
|
183
|
+
0,
|
|
184
|
+
data.length,
|
|
185
|
+
this.port,
|
|
186
|
+
this.address,
|
|
187
|
+
(err) => (err ? reject(err) : resolve())
|
|
188
|
+
);
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
async _waitForHandshakeResponse() {
|
|
193
|
+
return await new Promise((resolve, reject) => {
|
|
194
|
+
// Handler called when a reply to the handshake is received
|
|
195
|
+
this.handshakeResolve = () => {
|
|
196
|
+
if (this.id !== this.packet.deviceId) {
|
|
197
|
+
// Update the identifier if needed
|
|
198
|
+
this.id = this.packet.deviceId;
|
|
199
|
+
this.debug = debug('thing:miio:' + this.id);
|
|
200
|
+
this.debug('Identifier of device updated');
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
if (this.packet.token) {
|
|
204
|
+
resolve(this.token);
|
|
205
|
+
} else {
|
|
206
|
+
const err = new Error(
|
|
207
|
+
'Could not connect to device, token needs to be specified'
|
|
208
|
+
);
|
|
209
|
+
err.code = 'missing-token';
|
|
210
|
+
reject(err);
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async _setTimeout() {
|
|
217
|
+
await new Promise((resolve, reject) =>
|
|
218
|
+
setTimeout(() => {
|
|
219
|
+
const err = new Error('Could not connect to device, handshake timeout');
|
|
220
|
+
err.code = 'timeout';
|
|
221
|
+
reject(err);
|
|
222
|
+
}, 2000)
|
|
223
|
+
);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async call(method, params = [], options = {}) {
|
|
227
|
+
const { retries = 5 } = options;
|
|
228
|
+
return await this._retryOnTimeout(retries, async (retriesLeft) => {
|
|
229
|
+
await this.handshake(); // Ensure the handshake is done
|
|
230
|
+
|
|
231
|
+
const request = {
|
|
232
|
+
id: this._nextId(retries === retriesLeft), // Assign the identifier
|
|
233
|
+
method,
|
|
234
|
+
params,
|
|
235
|
+
sid: options.sid, // If we have a sub-device set it (used by Lumi Smart Home Gateway)
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
try {
|
|
239
|
+
// Enqueue promise listener to this request ID
|
|
240
|
+
const waitForResponse = this._waitForResponse(request.id);
|
|
241
|
+
|
|
242
|
+
// Create the JSON and send it
|
|
243
|
+
const json = JSON.stringify(request);
|
|
244
|
+
this.debug('-> (' + retriesLeft + ')', json);
|
|
245
|
+
this.packet.data = Buffer.from(json, 'utf8');
|
|
246
|
+
await this._sendPacket();
|
|
247
|
+
return await waitForResponse;
|
|
248
|
+
} catch (err) {
|
|
249
|
+
if (!(err instanceof Error) && typeof err.code !== 'undefined') {
|
|
250
|
+
const code = err.code;
|
|
251
|
+
const handler = ERRORS[code];
|
|
252
|
+
const msg = handler
|
|
253
|
+
? handler(method, params, err)
|
|
254
|
+
: err.message || err.toString();
|
|
255
|
+
|
|
256
|
+
const newErr = new Error(msg);
|
|
257
|
+
newErr.code = code;
|
|
258
|
+
throw newErr;
|
|
259
|
+
}
|
|
260
|
+
throw err;
|
|
261
|
+
} finally {
|
|
262
|
+
this.promises.delete(request.id);
|
|
263
|
+
}
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
async _waitForResponse(requestId) {
|
|
268
|
+
return new Promise((resolve, reject) => {
|
|
269
|
+
// Store reference to the promise so reply can be received
|
|
270
|
+
this.promises.set(requestId, { resolve, reject });
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* Retries the action defined in `actionPromiseFn` as many times as `retries`,
|
|
276
|
+
* only if the action fails due to a timeout.
|
|
277
|
+
* @param retries Max number of attempts
|
|
278
|
+
* @param actionPromiseFn Method that returns a promise to repeat
|
|
279
|
+
* @private
|
|
280
|
+
*/
|
|
281
|
+
async _retryOnTimeout(retries = 5, actionPromiseFn) {
|
|
282
|
+
while (retries > 0) {
|
|
283
|
+
try {
|
|
284
|
+
const result = await Promise.race([
|
|
285
|
+
actionPromiseFn(retries),
|
|
286
|
+
this._setTimeout(),
|
|
287
|
+
]);
|
|
288
|
+
return result;
|
|
289
|
+
} catch (err) {
|
|
290
|
+
if (err.code !== 'timeout') {
|
|
291
|
+
throw err;
|
|
292
|
+
}
|
|
293
|
+
retries--;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
this.debug('Reached maximum number of retries, giving up');
|
|
297
|
+
const maxRetriesError = new Error('Call to device timed out');
|
|
298
|
+
maxRetriesError.code = 'timeout';
|
|
299
|
+
throw maxRetriesError;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
_nextId(isFirstAttempt) {
|
|
303
|
+
let id;
|
|
304
|
+
|
|
305
|
+
if (isFirstAttempt) {
|
|
306
|
+
id = this.lastId + 1;
|
|
307
|
+
} else {
|
|
308
|
+
/*
|
|
309
|
+
* This is a failure, increase the last id. Should
|
|
310
|
+
* increase the chances of the new request to
|
|
311
|
+
* succeed. Related to issues with the vacuum
|
|
312
|
+
* not responding such as described in issue
|
|
313
|
+
* https://github.com/aholstenson/miio/issues/94.
|
|
314
|
+
*/
|
|
315
|
+
id = this.lastId + 100;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// Check that the id hasn't rolled over
|
|
319
|
+
if (id >= 10000) {
|
|
320
|
+
this.lastId = id = 1;
|
|
321
|
+
} else {
|
|
322
|
+
this.lastId = id;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
return id;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
module.exports = DeviceInfo;
|
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const TOKEN = 'e381c97af00985577e8e6a3d94732bbe';
|
|
4
|
+
|
|
5
|
+
const loggerMock = jest.fn().mockImplementation((a, b) => {
|
|
6
|
+
// Uncomment when debugging tests
|
|
7
|
+
// console.debug(a, b);
|
|
8
|
+
});
|
|
9
|
+
const debugMock = jest.fn().mockImplementation((label) => {
|
|
10
|
+
return loggerMock;
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
jest.doMock('debug', () => debugMock);
|
|
14
|
+
|
|
15
|
+
function createParentMock() {
|
|
16
|
+
return {
|
|
17
|
+
socket: {
|
|
18
|
+
send: jest
|
|
19
|
+
.fn()
|
|
20
|
+
.mockImplementation((data, size, length, port, address, cb) => {
|
|
21
|
+
cb();
|
|
22
|
+
}),
|
|
23
|
+
},
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const DeviceInfo = require('./device_info');
|
|
28
|
+
const Packet = require('./packet');
|
|
29
|
+
|
|
30
|
+
describe('DeviceInfo', () => {
|
|
31
|
+
jest.useFakeTimers();
|
|
32
|
+
|
|
33
|
+
describe('constructor', () => {
|
|
34
|
+
test('creates a new DeviceInfo without id', () => {
|
|
35
|
+
new DeviceInfo({}, null, 'localhost', 1234);
|
|
36
|
+
expect(debugMock).toHaveBeenCalledWith('thing:miio:pending');
|
|
37
|
+
});
|
|
38
|
+
test('creates a new DeviceInfo with id', () => {
|
|
39
|
+
new DeviceInfo({}, 'MY-ID', 'localhost', 1234);
|
|
40
|
+
expect(debugMock).toHaveBeenCalledWith('thing:miio:MY-ID');
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
describe('token', () => {
|
|
45
|
+
const device = new DeviceInfo({}, 'MY-ID', 'localhost', 1234);
|
|
46
|
+
test('initial token does not exist', () => {
|
|
47
|
+
expect(device.token).toBeNull();
|
|
48
|
+
});
|
|
49
|
+
test('token stored', () => {
|
|
50
|
+
expect(device.tokenChanged).toBe(false);
|
|
51
|
+
device.token = Buffer.from('my-token');
|
|
52
|
+
expect(device.tokenChanged).toBe(true);
|
|
53
|
+
expect(device.token.toString('utf8')).toBe('my-token');
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
describe('enrich', () => {
|
|
58
|
+
test('fails if the id is not populated yet', async () => {
|
|
59
|
+
const device = new DeviceInfo({}, null, 'localhost', 1234);
|
|
60
|
+
await expect(device.enrich()).rejects.toThrow(
|
|
61
|
+
'Device has no identifier yet, handshake needed'
|
|
62
|
+
);
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test('returns undefined because everything is properly initialised already', async () => {
|
|
66
|
+
const device = new DeviceInfo({}, 'MY-ID', 'localhost', 1234);
|
|
67
|
+
device.token = TOKEN;
|
|
68
|
+
device.tokenChanged = false;
|
|
69
|
+
device.model = {};
|
|
70
|
+
await expect(device.enrich()).resolves.toBeUndefined();
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
test('happy path', async () => {
|
|
74
|
+
const model = { test: 1 };
|
|
75
|
+
const device = new DeviceInfo({}, 'MY-ID', 'localhost', 1234);
|
|
76
|
+
device.token = TOKEN;
|
|
77
|
+
device.call = jest.fn().mockImplementation(async () => ({ model }));
|
|
78
|
+
await expect(device.enrich()).resolves.toBeUndefined();
|
|
79
|
+
expect(device.tokenChanged).toBe(false);
|
|
80
|
+
expect(device.model).toBe(model);
|
|
81
|
+
expect(device.enriched).toBe(true);
|
|
82
|
+
expect(device.enrichPromise).toBeNull();
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test('errors with \'missing-token\'', async () => {
|
|
86
|
+
const device = new DeviceInfo({}, 'MY-ID', 'localhost', 1234);
|
|
87
|
+
device.token = TOKEN;
|
|
88
|
+
device.enrichPromise = Promise.reject({ code: 'missing-token' });
|
|
89
|
+
await expect(device.enrich()).rejects.toStrictEqual({
|
|
90
|
+
code: 'missing-token',
|
|
91
|
+
device,
|
|
92
|
+
});
|
|
93
|
+
expect(device.tokenChanged).toBe(true);
|
|
94
|
+
expect(device.enriched).toBe(true);
|
|
95
|
+
expect(device.enrichPromise).toBeNull();
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
test('errors with \'connection-failure\'', async () => {
|
|
99
|
+
const device = new DeviceInfo({}, 'MY-ID', 'localhost', 1234);
|
|
100
|
+
device.token = TOKEN;
|
|
101
|
+
device.tokenChanged = false;
|
|
102
|
+
device.enrichPromise = Promise.reject('Something went terribly wrong');
|
|
103
|
+
await expect(device.enrich()).rejects.toThrow(
|
|
104
|
+
'Could not connect to device, token might be wrong'
|
|
105
|
+
);
|
|
106
|
+
expect(device.tokenChanged).toBe(false);
|
|
107
|
+
expect(device.enriched).toBe(true);
|
|
108
|
+
expect(device.enrichPromise).toBeNull();
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
test('errors with \'missing-token\' custom', async () => {
|
|
112
|
+
const device = new DeviceInfo({}, 'MY-ID', 'localhost', 1234);
|
|
113
|
+
device.enrichPromise = Promise.reject('Something went terribly wrong');
|
|
114
|
+
await expect(device.enrich()).rejects.toThrow(
|
|
115
|
+
'Could not connect to device, token needs to be specified'
|
|
116
|
+
);
|
|
117
|
+
expect(device.tokenChanged).toBe(false);
|
|
118
|
+
expect(device.enriched).toBe(true);
|
|
119
|
+
expect(device.enrichPromise).toBeNull();
|
|
120
|
+
});
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
describe('handshake', () => {
|
|
124
|
+
test('happy-path: runs the handshake', async () => {
|
|
125
|
+
const packet = new Packet(false);
|
|
126
|
+
const parent = createParentMock();
|
|
127
|
+
const device = new DeviceInfo(parent, 'MY-ID', 'localhost', 1234);
|
|
128
|
+
device.token = TOKEN;
|
|
129
|
+
packet.token = TOKEN;
|
|
130
|
+
parent.socket.send.mockImplementation(
|
|
131
|
+
(data, size, length, port, address, cb) => {
|
|
132
|
+
cb();
|
|
133
|
+
packet.data = null;
|
|
134
|
+
device.onMessage(packet.raw);
|
|
135
|
+
}
|
|
136
|
+
);
|
|
137
|
+
const token = await device.handshake();
|
|
138
|
+
expect(token.toString()).toBe(TOKEN);
|
|
139
|
+
// Second call is not triggered
|
|
140
|
+
const token2 = await device.handshake();
|
|
141
|
+
expect(token2.toString()).toBe(TOKEN);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
test('fails because \'missing-token\'', async () => {
|
|
145
|
+
const packet = new Packet(false);
|
|
146
|
+
const parent = createParentMock();
|
|
147
|
+
const device = new DeviceInfo(parent, 'MY-ID', 'localhost', 1234);
|
|
148
|
+
packet.token = TOKEN;
|
|
149
|
+
parent.socket.send.mockImplementation(
|
|
150
|
+
(data, size, length, port, address, cb) => {
|
|
151
|
+
cb();
|
|
152
|
+
packet.data = null;
|
|
153
|
+
device.onMessage(packet.raw);
|
|
154
|
+
}
|
|
155
|
+
);
|
|
156
|
+
await expect(device.handshake()).rejects.toThrow(
|
|
157
|
+
'Could not connect to device, token needs to be specified'
|
|
158
|
+
);
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
test('fails because to send the handshake request', async () => {
|
|
162
|
+
const packet = new Packet(false);
|
|
163
|
+
const parent = createParentMock();
|
|
164
|
+
const device = new DeviceInfo(parent, 'MY-ID', 'localhost', 1234);
|
|
165
|
+
packet.token = TOKEN;
|
|
166
|
+
parent.socket.send.mockImplementation(
|
|
167
|
+
(data, size, length, port, address, cb) => {
|
|
168
|
+
cb(new Error('Something went terribly wrong'));
|
|
169
|
+
}
|
|
170
|
+
);
|
|
171
|
+
await expect(device.handshake()).rejects.toThrow(
|
|
172
|
+
'Something went terribly wrong'
|
|
173
|
+
);
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
test('timesout after 2 secs', async () => {
|
|
177
|
+
const parent = createParentMock();
|
|
178
|
+
const device = new DeviceInfo(parent, 'MY-ID', 'localhost', 1234);
|
|
179
|
+
device.token = TOKEN;
|
|
180
|
+
const promise = device.handshake();
|
|
181
|
+
jest.advanceTimersByTime(2 * 1000);
|
|
182
|
+
await expect(promise).rejects.toThrow(
|
|
183
|
+
'Could not connect to device, handshake timeout'
|
|
184
|
+
);
|
|
185
|
+
});
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
describe('onMessage', () => {
|
|
189
|
+
test('swallows error to parse the message', async () => {
|
|
190
|
+
const device = new DeviceInfo({}, 'MY-ID', 'localhost', 1234);
|
|
191
|
+
expect(device.onMessage('test')).toBeUndefined();
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
test('handshake message but no handler', async () => {
|
|
195
|
+
const device = new DeviceInfo({}, 'MY-ID', 'localhost', 1234);
|
|
196
|
+
const packet = new Packet();
|
|
197
|
+
device.token = TOKEN;
|
|
198
|
+
packet.token = TOKEN;
|
|
199
|
+
packet.data = null;
|
|
200
|
+
expect(device.onMessage(packet.raw)).toBeUndefined();
|
|
201
|
+
});
|
|
202
|
+
|
|
203
|
+
test('swallows error because data is not a valid JSON', async () => {
|
|
204
|
+
const device = new DeviceInfo({}, 'MY-ID', 'localhost', 1234);
|
|
205
|
+
const packet = new Packet();
|
|
206
|
+
device.token = TOKEN;
|
|
207
|
+
packet.token = TOKEN;
|
|
208
|
+
packet.data = Buffer.from('test').fill(0);
|
|
209
|
+
expect(device.onMessage(packet.raw)).toBeUndefined();
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
test('does not call the promise resolvers because there\'s none', async () => {
|
|
213
|
+
const device = new DeviceInfo({}, 'MY-ID', 'localhost', 1234);
|
|
214
|
+
const packet = new Packet();
|
|
215
|
+
device.token = TOKEN;
|
|
216
|
+
packet.token = TOKEN;
|
|
217
|
+
const response = { id: '1', result: 'something' };
|
|
218
|
+
packet.data = Buffer.from(JSON.stringify(response));
|
|
219
|
+
expect(device.onMessage(packet.raw)).toBeUndefined();
|
|
220
|
+
});
|
|
221
|
+
|
|
222
|
+
test('calls the promise resolver when there\'s a result', async () => {
|
|
223
|
+
const device = new DeviceInfo({}, 'MY-ID', 'localhost', 1234);
|
|
224
|
+
const packet = new Packet();
|
|
225
|
+
device.token = TOKEN;
|
|
226
|
+
packet.token = TOKEN;
|
|
227
|
+
const response = { id: '1', result: 'something' };
|
|
228
|
+
const promiseResolvers = { resolve: jest.fn(), reject: jest.fn() };
|
|
229
|
+
device.promises.set('1', promiseResolvers);
|
|
230
|
+
packet.data = Buffer.from(JSON.stringify(response));
|
|
231
|
+
expect(device.onMessage(packet.raw)).toBeUndefined();
|
|
232
|
+
expect(promiseResolvers.resolve).toHaveBeenCalledWith('something');
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
test('calls the promise resolver\'s reject when there\'s an error', async () => {
|
|
236
|
+
const device = new DeviceInfo({}, 'MY-ID', 'localhost', 1234);
|
|
237
|
+
const packet = new Packet();
|
|
238
|
+
device.token = TOKEN;
|
|
239
|
+
packet.token = TOKEN;
|
|
240
|
+
const response = { id: '1', error: 'something' };
|
|
241
|
+
const promiseResolvers = { resolve: jest.fn(), reject: jest.fn() };
|
|
242
|
+
device.promises.set('1', promiseResolvers);
|
|
243
|
+
packet.data = Buffer.from(JSON.stringify(response));
|
|
244
|
+
expect(device.onMessage(packet.raw)).toBeUndefined();
|
|
245
|
+
expect(promiseResolvers.reject).toHaveBeenCalledWith('something');
|
|
246
|
+
});
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
describe('call', () => {
|
|
250
|
+
test('happy-path: sends a method \'miIO.info\'', async () => {
|
|
251
|
+
const packet = new Packet(false);
|
|
252
|
+
const parent = createParentMock();
|
|
253
|
+
const device = new DeviceInfo(parent, 'MY-ID', 'localhost', 1234);
|
|
254
|
+
device.token = TOKEN;
|
|
255
|
+
packet.token = TOKEN;
|
|
256
|
+
parent.socket.send.mockImplementation(
|
|
257
|
+
(data, size, length, port, address, cb) => {
|
|
258
|
+
cb();
|
|
259
|
+
// Return what you get embedded in `result`
|
|
260
|
+
packet.raw = Buffer.from(data);
|
|
261
|
+
const str = packet.data;
|
|
262
|
+
if (str !== null) {
|
|
263
|
+
const json = JSON.parse(str);
|
|
264
|
+
packet.data = JSON.stringify(Object.assign({}, json, {result: json}));
|
|
265
|
+
}
|
|
266
|
+
device.onMessage(packet.raw);
|
|
267
|
+
}
|
|
268
|
+
);
|
|
269
|
+
const response = await device.call('miIO.info');
|
|
270
|
+
expect(response).toStrictEqual({
|
|
271
|
+
id: device.lastId,
|
|
272
|
+
method: 'miIO.info',
|
|
273
|
+
params: [],
|
|
274
|
+
});
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
test('timeout error', async () => {
|
|
278
|
+
const packet = new Packet(false);
|
|
279
|
+
const parent = createParentMock();
|
|
280
|
+
const device = new DeviceInfo(parent, 'MY-ID', 'localhost', 1234);
|
|
281
|
+
packet.token = TOKEN;
|
|
282
|
+
device.token = TOKEN;
|
|
283
|
+
device.lastId = 10000;
|
|
284
|
+
|
|
285
|
+
parent.socket.send.mockImplementation(
|
|
286
|
+
(data, size, length, port, address, cb) => {
|
|
287
|
+
cb();
|
|
288
|
+
// Reply to handshakes only
|
|
289
|
+
packet.raw = data;
|
|
290
|
+
const str = packet.data;
|
|
291
|
+
if (str === null) {
|
|
292
|
+
device.onMessage(packet.raw);
|
|
293
|
+
} else {
|
|
294
|
+
jest.advanceTimersByTime(2 * 1000);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
);
|
|
298
|
+
const promise = device.call('miIO.info', [], { retries: 2 });
|
|
299
|
+
await expect(promise).rejects.toThrow('Call to device timed out');
|
|
300
|
+
expect(device.lastId).toBe(101);
|
|
301
|
+
});
|
|
302
|
+
|
|
303
|
+
describe('known errors', () => {
|
|
304
|
+
const packet = new Packet(false);
|
|
305
|
+
packet.token = TOKEN;
|
|
306
|
+
|
|
307
|
+
test.each`
|
|
308
|
+
code | message | expected
|
|
309
|
+
${'-5001'} | ${'invalid_arg'} | ${'Invalid argument'}
|
|
310
|
+
${'-5001'} | ${'Test msg'} | ${'Test msg'}
|
|
311
|
+
${'-5005'} | ${'params error'} | ${'Invalid argument'}
|
|
312
|
+
${'-5005'} | ${'Test msg'} | ${'Test msg'}
|
|
313
|
+
${'-10000'} | ${'Test msg'} | ${'Method `miIO.info` is not supported'}
|
|
314
|
+
${'OTHER'} | ${'Test msg'} | ${'Test msg'}
|
|
315
|
+
`('$code | $message', async ({ code, message, expected }) => {
|
|
316
|
+
const parent = createParentMock();
|
|
317
|
+
const device = new DeviceInfo(parent, 'MY-ID', 'localhost', 1234);
|
|
318
|
+
device.token = TOKEN;
|
|
319
|
+
|
|
320
|
+
parent.socket.send.mockImplementation(
|
|
321
|
+
(data, size, length, port, address, cb) => {
|
|
322
|
+
cb();
|
|
323
|
+
// Return what you get embedded in `result`
|
|
324
|
+
packet.raw = data;
|
|
325
|
+
const str = packet.data;
|
|
326
|
+
if (str !== null) {
|
|
327
|
+
const json = JSON.parse(str);
|
|
328
|
+
packet.data = JSON.stringify(Object.assign({}, json, { error: { code, message } }));
|
|
329
|
+
}
|
|
330
|
+
device.onMessage(packet.raw);
|
|
331
|
+
}
|
|
332
|
+
);
|
|
333
|
+
await expect(device.call('miIO.info')).rejects.toThrow(expected);
|
|
334
|
+
});
|
|
335
|
+
});
|
|
336
|
+
});
|
|
337
|
+
});
|