-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathswitchbot.ts
524 lines (495 loc) · 18.9 KB
/
switchbot.ts
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
/* Copyright(C) 2024, donavanbecker (https://github.com/donavanbecker). All rights reserved.
*
* switchbot.ts: Switchbot BLE API registration.
*/
import { ParameterChecker } from './parameter-checker.js';
import { Advertising } from './advertising.js';
import { SwitchbotDevice } from './device.js';
import { WoHand } from './device/wohand.js';
import { WoCurtain } from './device/wocurtain.js';
import { WoBlindTilt } from './device/woblindtilt.js';
import { WoPresence } from './device/wopresence.js';
import { WoContact } from './device/wocontact.js';
import { WoSensorTH } from './device/wosensorth.js';
import { WoIOSensorTH } from './device/woiosensorth.js';
import { WoHumi } from './device/wohumi.js';
import { WoPlugMini } from './device/woplugmini.js';
import { WoBulb } from './device/wobulb.js';
import { WoStrip } from './device/wostrip.js';
import { Ad } from './advertising.js';
import { Peripheral } from '@abandonware/noble';
type Params = {
duration?: number,
model?: string,
id?: string,
quick?: false,
noble?: any,
}
export class SwitchBot {
private ready: Promise<void>;
noble?: any;
ondiscover?: (device: SwitchbotDevice) => void;
onadvertisement?: (ad: Ad) => void;
onlog: ((message: string) => void) | undefined;
scanning = false;
DEFAULT_DISCOVERY_DURATION = 5000;
PRIMARY_SERVICE_UUID_LIST = [];
static onlog: any;
static noble: any;
/* ------------------------------------------------------------------
* Constructor
*
* [Arguments]
* - params | Object | Optional |
* - noble | Noble | Optional | The Noble object created by the noble module.
* | | | This parameter is optional.
* | | | If you don't specify this parameter, this
* | | | module automatically creates it.
* ---------------------------------------------------------------- */
constructor(params?: Params) {
this.ready = this.init(params);
}
// Check parameters
async init(params?: Params) {
let noble;
if (params && params.noble) {
noble = params.noble;
} else {
noble = (await import('@abandonware/noble')).default;
}
// Public properties
this.noble = noble;
// Private properties
this.scanning = false;
}
/* ------------------------------------------------------------------
* discover([params])
* - Discover switchbot devices
*
* [Arguments]
* - params | Object | Optional |
* - duration | Integer | Optional | Duration for discovery process (msec).
* | | | The value must be in the range of 1 to 60000.
* | | | The default value is 5000 (msec).
* - model | String | Optional | "H", "T", "e", "s", "d", "c", "{", "u", "g", "o", "i", or "r".
* | | | If "H" is specified, this method will discover only Bots.
* | | | If "T" is specified, this method will discover only Meters.
* | | | If "e" is specified, this method will discover only Humidifiers.
* | | | If "s" is specified, this method will discover only Motion Sensors.
* | | | If "d" is specified, this method will discover only Contact Sensors.
* | | | If "c" is specified, this method will discover only Curtains.
* | | | If "{" is specified, this method will discover only Curtain 3.
* | | | If "u" is specified, this method will discover only Color Bulbs.
* | | | If "g" is specified, this method will discover only Plugs.
* | | | If "o" is specified, this method will discover only Locks.
* | | | If "i" is specified, this method will discover only Meter Pluses.
* | | | If "r" is specified, this method will discover only Locks.
* - id | String | Optional | If this value is set, this method will discover
* | | | only a device whose ID is as same as this value.
* | | | The ID is identical to the MAC address.
* | | | This parameter is case-insensitive, and
* | | | colons are ignored.
* - quick | Boolean | Optional | If this value is true, this method finishes
* | | | the discovery process when the first device
* | | | is found, then calls the resolve() function
* | | | without waiting the specified duration.
* | | | The default value is false.
*
* [Return value]
* - Promise object
* An array will be passed to the `resolve()`, which includes
* `SwitchbotDevice` objects representing the found devices.
* ---------------------------------------------------------------- */
discover(params: Params = {}) {
const promise = new Promise((resolve, reject) => {
// Check the parameters
const valid = ParameterChecker.check(
params,
{
duration: { required: false, type: 'integer', min: 1, max: 60000 },
model: {
required: false,
type: 'string',
enum: [
'H',
'T',
'e',
's',
'd',
'c',
'{',
'u',
'g',
'j',
'o',
'i',
'r',
'x',
'w',
],
},
id: { required: false, type: 'string', min: 12, max: 17 },
quick: { required: false, type: 'boolean' },
},
false,
);
if (!valid) {
reject(new Error(ParameterChecker.error.message));
return;
}
if (!params) {
params = {};
}
// Determine the values of the parameters
const p = {
duration: params.duration || this.DEFAULT_DISCOVERY_DURATION,
model: params.model || '',
id: params.id || '',
quick: params.quick ? true : false,
};
// Initialize the noble object
this._init()
.then(() => {
const peripherals: Record<string, SwitchbotDevice> = {};
let timer: NodeJS.Timeout = setTimeout(() => { }, 0);
const finishDiscovery = () => {
if (timer) {
clearTimeout(timer);
}
this.noble?.removeAllListeners('discover');
this.noble?.stopScanning();
const device_list: SwitchbotDevice[] = [];
for (const addr in peripherals) {
device_list.push(peripherals[addr]);
}
if (device_list.length) {
resolve(device_list);
}
};
// Set a handler for the 'discover' event
this.noble?.on('discover', (peripheral: Peripheral) => {
const device = this.getDeviceObject(peripheral, p.id, p.model) as SwitchbotDevice;
if (!device) {
return;
}
const id = device.id as string;
peripherals[id] = device;
if (this.ondiscover && typeof this.ondiscover === 'function') {
this.ondiscover(device);
}
if (p.quick) {
finishDiscovery();
return;
}
});
// Start scanning
this.noble?.startScanning(
this.PRIMARY_SERVICE_UUID_LIST,
false,
(error: Error) => {
if (error) {
reject(error);
return;
}
timer = setTimeout(() => {
finishDiscovery();
}, p.duration);
},
);
})
.catch((error) => {
reject(error);
});
});
return promise;
}
async _init() {
await this.ready;
const promise = new Promise<void>((resolve, reject) => {
let err;
if (this.noble.state === 'poweredOn') {
resolve();
return;
}
this.noble?.once('stateChange', (state: any) => {
switch (state) {
case 'unsupported':
case 'unauthorized':
case 'poweredOff':
err = new Error(
'Failed to initialize the Noble object: ' + this.noble.state,
);
reject(err);
return;
case 'resetting':
case 'unknown':
err = new Error(
'Adapter is not ready: ' + this.noble.state,
);
reject(err);
return;
case 'poweredOn':
resolve();
return;
default:
err = new Error(
'Unknown state: ' + this.noble.state,
);
reject(err);
return;
}
});
});
return promise;
}
getDeviceObject(peripheral: Peripheral, id: string, model: string) {
const ad = Advertising.parse(peripheral, this.onlog);
if (this.filterAdvertising(ad, id, model)) {
let device;
if (ad && ad.serviceData && ad.serviceData.model) {
switch (ad.serviceData.model) {
case 'H':
device = new WoHand(peripheral, this.noble);
break;
case 'T':
device = new WoSensorTH(peripheral, this.noble);
break;
case 'e':
device = new WoHumi(peripheral, this.noble);
break;
case 's':
device = new WoPresence(peripheral, this.noble);
break;
case 'd':
device = new WoContact(peripheral, this.noble);
break;
case 'c':
case '{':
device = new WoCurtain(peripheral, this.noble);
break;
case 'x':
device = new WoBlindTilt(peripheral, this.noble);
break;
case 'u':
device = new WoBulb(peripheral, this.noble);
break;
case 'g':
case 'j':
device = new WoPlugMini(peripheral, this.noble);
break;
case 'o':
//device = new SwitchbotDeviceWoSmartLock(peripheral, this.noble);
break;
case 'i':
device = new WoSensorTH(peripheral, this.noble);
break;
case 'w':
device = new WoIOSensorTH(peripheral, this.noble);
break;
case 'r':
device = new WoStrip(peripheral, this.noble);
break;
default: // 'resetting', 'unknown'
device = new SwitchbotDevice(peripheral, this.noble);
}
}
return device;
} else {
return null;
}
}
filterAdvertising(ad: Ad, id: string, model: string) {
if (!ad) {
return false;
}
if (id) {
id = id.toLowerCase().replace(/:/g, '');
const ad_id = ad.address.toLowerCase().replace(/[^a-z0-9]/g, '');
if (ad_id !== id) {
return false;
}
}
if (model) {
if (ad.serviceData.model !== model) {
return false;
}
}
return true;
}
/* ------------------------------------------------------------------
* startScan([params])
* - Start to monitor advertising packets coming from switchbot devices
*
* [Arguments]
* - params | Object | Optional |
* - model | String | Optional | "H", "T", "e", "s", "d", "c", "{", "u", "g", "o", "i", "x", or "r".
* | | | If "H" is specified, the `onadvertisement`
* | | | event handler will be called only when advertising
* | | | packets comes from Bots.
* | | | If "T" is specified, the `onadvertisement`
* | | | event handler will be called only when advertising
* | | | packets comes from Meters.
* | | | If "e" is specified, the `onadvertisement`
* | | | event handler will be called only when advertising
* | | | packets comes from Humidifiers.
* | | | If "s" is specified, the `onadvertisement`
* | | | event handler will be called only when advertising
* | | | packets comes from Motion Sensor.
* | | | If "d" is specified, the `onadvertisement`
* | | | event handler will be called only when advertising
* | | | packets comes from Contact Sensor.
* | | | If "c" is specified, the `onadvertisement`
* | | | event handler will be called only when advertising
* | | | packets comes from Curtains.
* | | | If "{" is specified, the `onadvertisement`
* | | | event handler will be called only when advertising
* | | | packets comes from Curtain 3.
* | | | If "x" is specified, the `onadvertisement`
* | | | event handler will be called only when advertising
* | | | packets comes from BlindTilt.
* | | | If "u" is specified, the `onadvertisement`
* | | | event handler will be called only when advertising
* | | | packets comes from Color Bulb.
* | | | If "g" is specified, the `onadvertisement`
* | | | event handler will be called only when advertising
* | | | packets comes from Plug Mini.
* | | | If "o" is specified, the `onadvertisement`
* | | | event handler will be called only when advertising
* | | | packets comes from Smart Lock.
* | | | If "i" is specified, the `onadvertisement`
* | | | event handler will be called only when advertising
* | | | packets comes from Meter Plus.
* | | | If "r" is specified, the `onadvertisement`
* | | | event handler will be called only when advertising
* | | | packets comes from LED Strip Light.
* - id | String | Optional | If this value is set, the `onadvertisement`
* | | | event handler will be called only when advertising
* | | | packets comes from devices whose ID is as same as
* | | | this value.
* | | | The ID is identical to the MAC address.
* | | | This parameter is case-insensitive, and
* | | | colons are ignored.
*
* [Return value]
* - Promise object
* Nothing will be passed to the `resolve()`.
* ---------------------------------------------------------------- */
startScan(params: Params = {}) {
const promise = new Promise<void>((resolve, reject) => {
// Check the parameters
const valid = ParameterChecker.check(
params,
{
model: {
required: false,
type: 'string',
enum: [
'H',
'T',
'e',
's',
'd',
'c',
'{',
'u',
'g',
'j',
'o',
'i',
'r',
'x',
'w',
],
},
id: { required: false, type: 'string', min: 12, max: 17 },
},
false,
);
if (!valid) {
reject(new Error(ParameterChecker.error.message));
return;
}
// Initialize the noble object
this._init()
.then(() => {
// Determine the values of the parameters
const p = {
model: params.model || '',
id: params.id || '',
};
// Set a handler for the 'discover' event
this.noble?.on('discover', (peripheral: Peripheral) => {
const ad = Advertising.parse(peripheral, this.onlog);
if (this.filterAdvertising(ad, p.id, p.model)) {
if (
this.onadvertisement &&
typeof this.onadvertisement === 'function'
) {
this.onadvertisement(ad);
}
}
});
// Start scanning
this.noble?.startScanning(
this.PRIMARY_SERVICE_UUID_LIST,
true,
(error: Error) => {
if (error) {
reject(error);
} else {
resolve();
}
},
);
})
.catch((error) => {
reject(error);
});
});
return promise;
}
/* ------------------------------------------------------------------
* stopScan()
* - Stop to monitor advertising packets coming from switchbot devices
*
* [Arguments]
* - none
*
* [Return value]
* - none
* ---------------------------------------------------------------- */
stopScan() {
this.noble?.removeAllListeners('discover');
this.noble?.stopScanning();
}
/* ------------------------------------------------------------------
* wait(msec) {
* - Wait for the specified time (msec)
*
* [Arguments]
* - msec | Integer | Required | Msec.
*
* [Return value]
* - Promise object
* Nothing will be passed to the `resolve()`.
* ---------------------------------------------------------------- */
wait(msec: number) {
return new Promise((resolve, reject) => {
// Check the parameters
const valid = ParameterChecker.check(
{ msec: msec },
{
msec: { required: true, type: 'integer', min: 0 },
},
true, // Add the required argument
);
if (!valid) {
reject(new Error(ParameterChecker.error.message));
return;
}
// Set a timer
setTimeout(resolve, msec);
});
}
}
export { SwitchbotDevice };