@switchbot/homebridge-switchbot 2.2.3-beta.1 → 2.3.0-beta.0

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.
@@ -0,0 +1,874 @@
1
+ import https from 'https';
2
+ import crypto from 'crypto';
3
+ import { Context } from 'vm';
4
+ import { IncomingMessage } from 'http';
5
+ import { interval, Subject } from 'rxjs';
6
+ import superStringify from 'super-stringify';
7
+ import { SwitchBotPlatform } from '../platform';
8
+ import { debounceTime, skipWhile, take, tap } from 'rxjs/operators';
9
+ import { Service, PlatformAccessory, CharacteristicValue } from 'homebridge';
10
+ import { device, devicesConfig, deviceStatus, ad, serviceData, switchbot, HostDomain, DevicePath } from '../settings';
11
+
12
+ export class RobotVacuumCleaner {
13
+ // Services
14
+ robotVacuumCleanerService: Service;
15
+ batteryService?: Service;
16
+
17
+ // Characteristic Values
18
+ On!: CharacteristicValue;
19
+ Brightness!: CharacteristicValue;
20
+ BatteryLevel?: CharacteristicValue;
21
+ StatusLowBattery?: CharacteristicValue;
22
+
23
+ // OpenAPI Others
24
+ power: deviceStatus['power'];
25
+ deviceStatus!: any; //deviceStatusResponse;
26
+
27
+ // BLE Others
28
+ connected?: boolean;
29
+ switchbot!: switchbot;
30
+ address!: ad['address'];
31
+ serviceData!: serviceData;
32
+ state: serviceData['state'];
33
+
34
+ // Config
35
+ scanDuration!: number;
36
+ deviceLogging!: string;
37
+ deviceRefreshRate!: number;
38
+
39
+ // Updates
40
+ robotVacuumCleanerUpdateInProgress!: boolean;
41
+ doRobotVacuumCleanerUpdate!: Subject<void>;
42
+
43
+ // Connection
44
+ private readonly BLE = (this.device.connectionType === 'BLE' || this.device.connectionType === 'BLE/OpenAPI');
45
+ private readonly OpenAPI = (this.device.connectionType === 'OpenAPI' || this.device.connectionType === 'BLE/OpenAPI');
46
+
47
+ constructor(private readonly platform: SwitchBotPlatform, private accessory: PlatformAccessory, public device: device & devicesConfig) {
48
+ // default placeholders
49
+ this.logs(device);
50
+ this.scan(device);
51
+ this.refreshRate(device);
52
+ this.config(device);
53
+ this.context();
54
+
55
+ // this is subject we use to track when we need to POST changes to the SwitchBot API
56
+ this.doRobotVacuumCleanerUpdate = new Subject();
57
+ this.robotVacuumCleanerUpdateInProgress = false;
58
+
59
+ // Retrieve initial values and updateHomekit
60
+ this.refreshStatus();
61
+
62
+ // set accessory information
63
+ accessory
64
+ .getService(this.platform.Service.AccessoryInformation)!
65
+ .setCharacteristic(this.platform.Characteristic.Manufacturer, 'SwitchBot')
66
+ .setCharacteristic(this.platform.Characteristic.Model, this.model(device))
67
+ .setCharacteristic(this.platform.Characteristic.SerialNumber, device.deviceId!)
68
+ .setCharacteristic(this.platform.Characteristic.FirmwareRevision, this.FirmwareRevision(accessory, device))
69
+ .getCharacteristic(this.platform.Characteristic.FirmwareRevision)
70
+ .updateValue(this.FirmwareRevision(accessory, device));
71
+
72
+ // get the Lightbulb service if it exists, otherwise create a new Lightbulb service
73
+ // you can create multiple services for each accessory
74
+ (this.robotVacuumCleanerService = accessory.getService(this.platform.Service.Lightbulb) || accessory.addService(this.platform.Service.Lightbulb)),
75
+ `${device.deviceName} ${device.deviceType}`;
76
+
77
+ // To avoid "Cannot add a Service with the same UUID another Service without also defining a unique 'subtype' property." error,
78
+ // when creating multiple services of the same type, you need to use the following syntax to specify a name and subtype id:
79
+ // accessory.getService('NAME') ?? accessory.addService(this.platform.Service.Lightbulb, 'NAME', 'USER_DEFINED_SUBTYPE');
80
+
81
+ // set the service name, this is what is displayed as the default name on the Home app
82
+ // in this example we are using the name we stored in the `accessory.context` in the `discoverDevices` method.
83
+ this.robotVacuumCleanerService.setCharacteristic(this.platform.Characteristic.Name, accessory.displayName);
84
+
85
+ // each service must implement at-minimum the "required characteristics" for the given service type
86
+ // see https://developers.homebridge.io/#/service/Lightbulb
87
+
88
+ // create handlers for required characteristics
89
+ this.robotVacuumCleanerService.getCharacteristic(this.platform.Characteristic.On).onSet(this.OnSet.bind(this));
90
+
91
+ // handle Brightness events using the Brightness characteristic
92
+ this.robotVacuumCleanerService
93
+ .getCharacteristic(this.platform.Characteristic.Brightness)
94
+ .setProps({
95
+ minStep: 25,
96
+ minValue: 0,
97
+ maxValue: 100,
98
+ validValues: [0, 25, 50, 75, 100],
99
+ validValueRanges: [0, 100],
100
+ })
101
+ .onGet(() => {
102
+ return this.Brightness;
103
+ })
104
+ .onSet(this.BrightnessSet.bind(this));
105
+
106
+ // Update Homekit
107
+ this.updateHomeKitCharacteristics();
108
+
109
+ // Start an update interval
110
+ interval(this.deviceRefreshRate * 1000)
111
+ .pipe(skipWhile(() => this.robotVacuumCleanerUpdateInProgress))
112
+ .subscribe(async () => {
113
+ await this.refreshStatus();
114
+ });
115
+
116
+ // Watch for Plug change events
117
+ // We put in a debounce of 100ms so we don't make duplicate calls
118
+ this.doRobotVacuumCleanerUpdate
119
+ .pipe(
120
+ tap(() => {
121
+ this.robotVacuumCleanerUpdateInProgress = true;
122
+ }),
123
+ debounceTime(this.platform.config.options!.pushRate! * 1000),
124
+ )
125
+ .subscribe(async () => {
126
+ try {
127
+ if (this.On !== this.accessory.context.On) {
128
+ await this.pushChanges();
129
+ }
130
+ if (this.On && (this.Brightness !== this.accessory.context.Brightness) ) {
131
+ await this.openAPIpushBrightnessChanges();
132
+ }
133
+ } catch (e: any) {
134
+ this.apiError(e);
135
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} failed pushChanges with ${this.device.connectionType} Connection,`
136
+ + ` Error Message: ${superStringify(e.message)}`);
137
+ }
138
+ this.robotVacuumCleanerUpdateInProgress = false;
139
+ });
140
+ }
141
+
142
+ /**
143
+ * Parse the device status from the SwitchBot api
144
+ */
145
+ async parseStatus(): Promise<void> {
146
+ if (!this.device.enableCloudService && this.OpenAPI) {
147
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} parseStatus enableCloudService: ${this.device.enableCloudService}`);
148
+ } else/*if (this.BLE) {
149
+ await this.BLEparseStatus();
150
+ } else*/if (this.OpenAPI && this.platform.config.credentials?.token) {
151
+ await this.openAPIparseStatus();
152
+ } else {
153
+ await this.offlineOff();
154
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} Connection Type:`
155
+ + ` ${this.device.connectionType}, parseStatus will not happen.`);
156
+ }
157
+ }
158
+
159
+ async BLEparseStatus(): Promise<void> {
160
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLEparseStatus`);
161
+ // State
162
+ switch (this.state) {
163
+ case 'on':
164
+ this.On = true;
165
+ break;
166
+ default:
167
+ this.On = false;
168
+ }
169
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`);
170
+ }
171
+
172
+ async openAPIparseStatus() {
173
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIparseStatus`);
174
+ switch (this.power) {
175
+ case 'on':
176
+ this.On = true;
177
+ break;
178
+ default:
179
+ this.On = false;
180
+ }
181
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`);
182
+ }
183
+
184
+ /**
185
+ * Asks the SwitchBot API for the latest device information
186
+ */
187
+ async refreshStatus(): Promise<void> {
188
+ if (!this.device.enableCloudService && this.OpenAPI) {
189
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} refreshStatus enableCloudService: ${this.device.enableCloudService}`);
190
+ } else/*if (this.BLE) {
191
+ await this.BLERefreshStatus();
192
+ } else*/if (this.OpenAPI && this.platform.config.credentials?.token) {
193
+ await this.openAPIRefreshStatus();
194
+ } else {
195
+ await this.offlineOff();
196
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} Connection Type:`
197
+ + ` ${this.device.connectionType}, refreshStatus will not happen.`);
198
+ }
199
+ }
200
+
201
+ async BLERefreshStatus(): Promise<void> {
202
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLERefreshStatus`);
203
+ const switchbot = await this.platform.connectBLE();
204
+ // Convert to BLE Address
205
+ this.device.bleMac = this.device
206
+ .deviceId!.match(/.{1,2}/g)!
207
+ .join(':')
208
+ .toLowerCase();
209
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLE Address: ${this.device.bleMac}`);
210
+ this.getCustomBLEAddress(switchbot);
211
+ // Start to monitor advertisement packets
212
+ if (switchbot !== false) {
213
+ switchbot
214
+ .startScan({
215
+ model: this.BLEmodel(),
216
+ id: this.device.bleMac,
217
+ })
218
+ .then(async () => {
219
+ // Set an event hander
220
+ switchbot.onadvertisement = async (ad: any) => {
221
+ this.address = ad.address;
222
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Config BLE Address: ${this.device.bleMac},`
223
+ + ` BLE Address Found: ${this.address}`);
224
+ this.serviceData = ad.serviceData;
225
+ this.state = ad.serviceData.state;
226
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} serviceData: ${superStringify(ad.serviceData)}`);
227
+ this.debugLog(
228
+ `${this.device.deviceType}: ${this.accessory.displayName} state: ${ad.serviceData.state}, ` +
229
+ `delay: ${ad.serviceData.delay}, timer: ${ad.serviceData.timer}, syncUtcTime: ${ad.serviceData.syncUtcTime} ` +
230
+ `wifiRssi: ${ad.serviceData.wifiRssi}, overload: ${ad.serviceData.overload}, currentPower: ${ad.serviceData.currentPower}`,
231
+ );
232
+
233
+ if (this.serviceData) {
234
+ this.connected = true;
235
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} connected: ${this.connected}`);
236
+ await this.stopScanning(switchbot);
237
+ } else {
238
+ this.connected = false;
239
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} connected: ${this.connected}`);
240
+ }
241
+ };
242
+ // Wait
243
+ return await switchbot.wait(this.scanDuration * 1000);
244
+ })
245
+ .then(async () => {
246
+ // Stop to monitor
247
+ await this.stopScanning(switchbot);
248
+ })
249
+ .catch(async (e: any) => {
250
+ this.apiError(e);
251
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} failed BLERefreshStatus with ${this.device.connectionType}`
252
+ + ` Connection, Error Message: ${superStringify(e.message)}`);
253
+ await this.BLERefreshConnection(switchbot);
254
+ });
255
+ } else {
256
+ await this.BLERefreshConnection(switchbot);
257
+ }
258
+ }
259
+
260
+ async openAPIRefreshStatus() {
261
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIRefreshStatus`);
262
+ try {
263
+ const t = Date.now();
264
+ const nonce = 'requestID';
265
+ const data = this.platform.config.credentials?.token + t + nonce;
266
+ const signTerm = crypto.createHmac('sha256', this.platform.config.credentials?.secret).update(Buffer.from(data, 'utf-8')).digest();
267
+ const sign = signTerm.toString('base64');
268
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} sign: ${sign}`);
269
+ const options = {
270
+ hostname: HostDomain,
271
+ port: 443,
272
+ path: `${DevicePath}/${this.device.deviceId}/status`,
273
+ method: 'GET',
274
+ headers: {
275
+ Authorization: this.platform.config.credentials?.token,
276
+ sign: sign,
277
+ nonce: nonce,
278
+ t: t,
279
+ 'Content-Type': 'application/json',
280
+ },
281
+ };
282
+ const req = https.request(options, (res) => {
283
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIRefreshStatus statusCode: ${res.statusCode}`);
284
+ this.statusCode({ res });
285
+ let rawData = '';
286
+ res.on('data', (d) => {
287
+ rawData += d;
288
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} d: ${d}`);
289
+ });
290
+ res.on('end', () => {
291
+ try {
292
+ this.deviceStatus = JSON.parse(rawData);
293
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIRefreshStatus: ${superStringify(this.deviceStatus)}`);
294
+ this.power = this.deviceStatus.body.power;
295
+ this.openAPIparseStatus();
296
+ this.updateHomeKitCharacteristics();
297
+ } catch (e: any) {
298
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} error message: ${e.message}`);
299
+ }
300
+ });
301
+ });
302
+ req.on('error', (e: any) => {
303
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} error message: ${e.message}`);
304
+ });
305
+ req.end();
306
+ } catch (e: any) {
307
+ this.apiError(e);
308
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} failed openAPIRefreshStatus with ${this.device.connectionType}`
309
+ + ` Connection, Error Message: ${superStringify(e.message)}`);
310
+ }
311
+ }
312
+
313
+ /**
314
+ * Pushes the requested changes to the SwitchBot API
315
+ * deviceType commandType Command parameter Description
316
+ * Robot Vacuum Cleaner S1 "command" "start" "default" = start vacuuming
317
+ * Robot Vacuum Cleaner S1 "command" "stop" "default" = stop vacuuming
318
+ * Robot Vacuum Cleaner S1 "command" "dock" "default" = return to charging dock
319
+ * Robot Vacuum Cleaner S1 "command" "PowLevel" "{0-3}" = set suction power level: 0 (Quiet), 1 (Standard), 2 (Strong), 3 (MAX)
320
+ */
321
+
322
+ async pushChanges(): Promise<void> {
323
+ if (!this.device.enableCloudService && this.OpenAPI) {
324
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} pushChanges enableCloudService: ${this.device.enableCloudService}`);
325
+ } else/* if (this.BLE) {
326
+ await this.BLEpushChanges();
327
+ } else*/if (this.OpenAPI && this.platform.config.credentials?.token) {
328
+ await this.openAPIpushChanges();
329
+ } else {
330
+ await this.offlineOff();
331
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} Connection Type:`
332
+ + ` ${this.device.connectionType}, pushChanges will not happen.`);
333
+ }
334
+ // Refresh the status from the API
335
+ interval(15000)
336
+ .pipe(skipWhile(() => this.robotVacuumCleanerUpdateInProgress))
337
+ .pipe(take(1))
338
+ .subscribe(async () => {
339
+ await this.refreshStatus();
340
+ });
341
+ }
342
+
343
+ async BLEpushChanges(): Promise<void> {
344
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLEpushChanges`);
345
+ if (this.On !== this.accessory.context.On) {
346
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLEpushChanges On: ${this.On} OnCached: ${this.accessory.context.On}`);
347
+ const switchbot = await this.platform.connectBLE();
348
+ // Convert to BLE Address
349
+ this.device.bleMac = this.device
350
+ .deviceId!.match(/.{1,2}/g)!
351
+ .join(':')
352
+ .toLowerCase();
353
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLE Address: ${this.device.bleMac}`);
354
+ switchbot
355
+ .discover({
356
+ model: this.BLEmodel(),
357
+ id: this.device.bleMac,
358
+ })
359
+ .then((device_list: any) => {
360
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`);
361
+ return this.turnOnOff(device_list);
362
+ })
363
+ .then(() => {
364
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Done.`);
365
+ this.On = false;
366
+ })
367
+ .catch(async (e: any) => {
368
+ this.apiError(e);
369
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} failed BLEpushChanges with ${this.device.connectionType}`
370
+ + ` Connection, Error Message: ${superStringify(e.message)}`);
371
+ await this.BLEPushConnection();
372
+ });
373
+ } else {
374
+ this.debugLog(
375
+ `${this.device.deviceType}: ${this.accessory.displayName} No BLEpushChanges.` + `On: ${this.On}, `
376
+ +`OnCached: ${this.accessory.context.On}`,
377
+ );
378
+ }
379
+ }
380
+
381
+ async openAPIpushChanges() {
382
+ try {
383
+ // Make Push On request to the API
384
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIpushChanges`);
385
+ const t = Date.now();
386
+ const nonce = 'requestID';
387
+ const data = this.platform.config.credentials?.token + t + nonce;
388
+ const signTerm = crypto.createHmac('sha256', this.platform.config.credentials?.secret)
389
+ .update(Buffer.from(data, 'utf-8'))
390
+ .digest();
391
+ const sign = signTerm.toString('base64');
392
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} sign: ${sign}`);
393
+ const body = await this.commands();
394
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Sending request to SwitchBot API, body: ${body},`);
395
+ const options = {
396
+ hostname: HostDomain,
397
+ port: 443,
398
+ path: `${DevicePath}/${this.device.deviceId}/commands`,
399
+ method: 'POST',
400
+ headers: {
401
+ 'Authorization': this.platform.config.credentials?.token,
402
+ 'sign': sign,
403
+ 'nonce': nonce,
404
+ 't': t,
405
+ 'Content-Type': 'application/json',
406
+ 'Content-Length': body.length,
407
+ },
408
+ };
409
+ const req = https.request(options, res => {
410
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIpushChanges statusCode: ${res.statusCode}`);
411
+ this.statusCode({ res });
412
+ res.on('data', d => {
413
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} d: ${d}`);
414
+ });
415
+ });
416
+ req.on('error', (e: any) => {
417
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} error message: ${e.message}`);
418
+ });
419
+ req.write(body);
420
+ req.end();
421
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIpushChanges: ${superStringify(req)}`);
422
+ } catch (e: any) {
423
+ this.apiError(e);
424
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} failed openAPIpushChanges with ${this.device.connectionType}`
425
+ + ` Connection, Error Message: ${superStringify(e.message)}`,
426
+ );
427
+ }
428
+ }
429
+
430
+ async openAPIpushBrightnessChanges() {
431
+ try {
432
+ // Make Push On request to the API
433
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIpushChanges`);
434
+ const t = Date.now();
435
+ const nonce = 'requestID';
436
+ const data = this.platform.config.credentials?.token + t + nonce;
437
+ const signTerm = crypto.createHmac('sha256', this.platform.config.credentials?.secret)
438
+ .update(Buffer.from(data, 'utf-8'))
439
+ .digest();
440
+ const sign = signTerm.toString('base64');
441
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} sign: ${sign}`);
442
+ const body = await this.brightnessCommands();
443
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Sending request to SwitchBot API, body: ${body},`);
444
+ const options = {
445
+ hostname: HostDomain,
446
+ port: 443,
447
+ path: `${DevicePath}/${this.device.deviceId}/commands`,
448
+ method: 'POST',
449
+ headers: {
450
+ 'Authorization': this.platform.config.credentials?.token,
451
+ 'sign': sign,
452
+ 'nonce': nonce,
453
+ 't': t,
454
+ 'Content-Type': 'application/json',
455
+ 'Content-Length': body.length,
456
+ },
457
+ };
458
+ const req = https.request(options, res => {
459
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIpushChanges statusCode: ${res.statusCode}`);
460
+ this.statusCode({ res });
461
+ res.on('data', d => {
462
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} d: ${d}`);
463
+ });
464
+ });
465
+ req.on('error', (e: any) => {
466
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} error message: ${e.message}`);
467
+ });
468
+ req.write(body);
469
+ req.end();
470
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIpushChanges: ${superStringify(req)}`);
471
+ } catch (e: any) {
472
+ this.apiError(e);
473
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} failed openAPIpushChanges with ${this.device.connectionType}`
474
+ + ` Connection, Error Message: ${superStringify(e.message)}`,
475
+ );
476
+ }
477
+ }
478
+
479
+ private commands() {
480
+ let command: string;
481
+ let parameter: string;
482
+ if (this.On) {
483
+ command = 'start';
484
+ parameter = 'default';
485
+ } else {
486
+ command = 'dock';
487
+ parameter = 'default';
488
+ }
489
+ const body = superStringify({
490
+ 'command': `${command}`,
491
+ 'parameter': `${parameter}`,
492
+ 'commandType': 'command',
493
+ });
494
+ return body;
495
+ }
496
+
497
+ private brightnessCommands() {
498
+ let command: string;
499
+ let parameter: string;
500
+ if (this.Brightness === 25) {
501
+ command = 'PowLevel';
502
+ parameter = '0';
503
+ } else if (this.Brightness === 50) {
504
+ command = 'PowLevel';
505
+ parameter = '1';
506
+ } else if (this.Brightness === 75) {
507
+ command = 'PowLevel';
508
+ parameter = '2';
509
+ } else if (this.Brightness === 100) {
510
+ command = 'PowLevel';
511
+ parameter = '3';
512
+ } else {
513
+ command = 'dock';
514
+ parameter = 'default';
515
+ }
516
+ const body = superStringify({
517
+ 'command': `${command}`,
518
+ 'parameter': `${parameter}`,
519
+ 'commandType': 'command',
520
+ });
521
+ return body;
522
+ }
523
+
524
+ /**
525
+ * Handle requests to set the value of the "On" characteristic
526
+ */
527
+ async OnSet(value: CharacteristicValue): Promise<void> {
528
+ if (this.On === this.accessory.context.On) {
529
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} No Changes, Set On: ${value}`);
530
+ } else {
531
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Set On: ${value}`);
532
+ }
533
+
534
+ this.On = value;
535
+ this.doRobotVacuumCleanerUpdate.next();
536
+ }
537
+
538
+ /**
539
+ * Handle requests to set the value of the "Brightness" characteristic
540
+ */
541
+ async BrightnessSet(value: CharacteristicValue): Promise<void> {
542
+ if (this.Brightness === this.accessory.context.Brightness) {
543
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} No Changes, Set Brightness: ${value}`);
544
+ } else if (this.On) {
545
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Set Brightness: ${value}`);
546
+ } else {
547
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Set Brightness: ${value}`);
548
+ }
549
+
550
+ this.Brightness = value;
551
+ this.doRobotVacuumCleanerUpdate.next();
552
+ }
553
+
554
+ async updateHomeKitCharacteristics(): Promise<void> {
555
+ if (this.On === undefined) {
556
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`);
557
+ } else {
558
+ this.accessory.context.On = this.On;
559
+ this.robotVacuumCleanerService.updateCharacteristic(this.platform.Characteristic.On, this.On);
560
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic On: ${this.On}`);
561
+ }
562
+ if (this.Brightness === undefined) {
563
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Brightness: ${this.Brightness}`);
564
+ } else {
565
+ this.accessory.context.Brightness = this.Brightness;
566
+ this.robotVacuumCleanerService.updateCharacteristic(this.platform.Characteristic.Brightness, this.Brightness);
567
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic Brightness: ${this.Brightness}`);
568
+ }
569
+ if (this.BatteryLevel === undefined) {
570
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel}`);
571
+ } else {
572
+ this.accessory.context.BatteryLevel = this.BatteryLevel;
573
+ this.batteryService?.updateCharacteristic(this.platform.Characteristic.BatteryLevel, this.BatteryLevel);
574
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic BatteryLevel: ${this.BatteryLevel}`);
575
+ }
576
+ if (this.StatusLowBattery === undefined) {
577
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} StatusLowBattery: ${this.StatusLowBattery}`);
578
+ } else {
579
+ this.accessory.context.StatusLowBattery = this.StatusLowBattery;
580
+ this.batteryService?.updateCharacteristic(this.platform.Characteristic.StatusLowBattery, this.StatusLowBattery);
581
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic StatusLowBattery: ${this.StatusLowBattery}`);
582
+ }
583
+ }
584
+
585
+ async stopScanning(switchbot: any) {
586
+ await switchbot.stopScan();
587
+ if (this.connected) {
588
+ await this.BLEparseStatus();
589
+ await this.updateHomeKitCharacteristics();
590
+ } else {
591
+ await this.BLERefreshConnection(switchbot);
592
+ }
593
+ }
594
+
595
+ BLEmodel(): 'g' | 'j' {
596
+ if (this.device.deviceType === 'Plug Mini (US)') {
597
+ return 'g';
598
+ } else {
599
+ return 'j';
600
+ }
601
+ }
602
+
603
+ async getCustomBLEAddress(switchbot: any) {
604
+ if (this.device.customBLEaddress && this.deviceLogging.includes('debug')) {
605
+ (async () => {
606
+ // Start to monitor advertisement packets
607
+ await switchbot.startScan({
608
+ model: this.BLEmodel(),
609
+ });
610
+ // Set an event handler
611
+ switchbot.onadvertisement = (ad: any) => {
612
+ this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} ad: ${superStringify(ad, null, ' ')}`);
613
+ };
614
+ await switchbot.wait(10000);
615
+ // Stop to monitor
616
+ switchbot.stopScan();
617
+ })();
618
+ }
619
+ }
620
+
621
+ async BLEPushConnection() {
622
+ if (this.platform.config.credentials?.token && this.device.connectionType === 'BLE/OpenAPI') {
623
+ this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} Using OpenAPI Connection to Push Changes`);
624
+ await this.openAPIpushChanges();
625
+ }
626
+ }
627
+
628
+ async BLERefreshConnection(switchbot: any): Promise<void> {
629
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} wasn't able to establish BLE Connection, node-switchbot: ${switchbot}`);
630
+ if (this.platform.config.credentials?.token && this.device.connectionType === 'BLE/OpenAPI') {
631
+ this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} Using OpenAPI Connection to Refresh Status`);
632
+ await this.openAPIRefreshStatus();
633
+ }
634
+ }
635
+
636
+ async turnOnOff(device_list: any): Promise<any> {
637
+ return await this.retry({
638
+ max: await this.maxRetry(),
639
+ fn: () => {
640
+ if (this.On) {
641
+ return device_list[0].turnOn({ id: this.device.bleMac });
642
+ } else {
643
+ return device_list[0].turnOff({ id: this.device.bleMac });
644
+ }
645
+ },
646
+ });
647
+ }
648
+
649
+ async retry({ max, fn }: { max: number; fn: { (): any; (): Promise<any> } }): Promise<null> {
650
+ return fn().catch(async (err: any) => {
651
+ if (max === 0) {
652
+ throw err;
653
+ }
654
+ this.infoLog(err);
655
+ this.infoLog('Retrying');
656
+ await this.switchbot.wait(1000);
657
+ return this.retry({ max: max - 1, fn });
658
+ });
659
+ }
660
+
661
+ async maxRetry(): Promise<number> {
662
+ let maxRetry: number;
663
+ if (this.device.bot?.maxRetry) {
664
+ maxRetry = this.device.bot?.maxRetry;
665
+ } else {
666
+ maxRetry = 5;
667
+ }
668
+ return maxRetry;
669
+ }
670
+
671
+ model(device: device & devicesConfig): string {
672
+ let model: string;
673
+ if (device.deviceType === 'Robot Vacuum Cleaner S1 Plus') {
674
+ model = 'W3011010';
675
+ } else if (device.deviceType === 'Robot Vacuum Cleaner S1') {
676
+ model = 'W3011000';
677
+ } else {
678
+ model = 'N/A';
679
+ }
680
+ return model;
681
+ }
682
+
683
+ async scan(device: device & devicesConfig): Promise<void> {
684
+ if (device.scanDuration) {
685
+ this.scanDuration = this.accessory.context.scanDuration = device.scanDuration;
686
+ if (this.BLE) {
687
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config scanDuration: ${this.scanDuration}`);
688
+ }
689
+ } else {
690
+ this.scanDuration = this.accessory.context.scanDuration = 1;
691
+ if (this.BLE) {
692
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Default scanDuration: ${this.scanDuration}`);
693
+ }
694
+ }
695
+ }
696
+
697
+ async statusCode({ res }: { res: IncomingMessage }): Promise<void> {
698
+ switch (res.statusCode) {
699
+ case 151:
700
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Command not supported by this device type.`);
701
+ break;
702
+ case 152:
703
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Device not found.`);
704
+ break;
705
+ case 160:
706
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Command is not supported.`);
707
+ break;
708
+ case 161:
709
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Device is offline.`);
710
+ await this.offlineOff();
711
+ break;
712
+ case 171:
713
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Hub Device is offline. Hub: ${this.device.hubDeviceId}`);
714
+ await this.offlineOff();
715
+ break;
716
+ case 190:
717
+ this.errorLog(
718
+ `${this.device.deviceType}: ${this.accessory.displayName} Device internal error due to device states not synchronized with server,` +
719
+ ` Or command: ${superStringify(res)} format is invalid`,
720
+ );
721
+ break;
722
+ case 100:
723
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Command successfully sent.`);
724
+ break;
725
+ default:
726
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Unknown statusCode.`);
727
+ }
728
+ }
729
+
730
+ async offlineOff(): Promise<void> {
731
+ if (this.device.offline) {
732
+ await this.context();
733
+ await this.updateHomeKitCharacteristics();
734
+ }
735
+ }
736
+
737
+ async apiError(e: any): Promise<void> {
738
+ this.robotVacuumCleanerService.updateCharacteristic(this.platform.Characteristic.On, e);
739
+ }
740
+
741
+ FirmwareRevision(accessory: PlatformAccessory<Context>, device: device & devicesConfig): CharacteristicValue {
742
+ let FirmwareRevision: string;
743
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName}`
744
+ +` accessory.context.FirmwareRevision: ${accessory.context.FirmwareRevision}`);
745
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} device.firmware: ${device.firmware}`);
746
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} this.platform.version: ${this.platform.version}`);
747
+ if (accessory.context.FirmwareRevision) {
748
+ FirmwareRevision = accessory.context.FirmwareRevision;
749
+ } else if (device.firmware) {
750
+ FirmwareRevision = device.firmware;
751
+ } else {
752
+ FirmwareRevision = this.platform.version;
753
+ }
754
+ return FirmwareRevision;
755
+ }
756
+
757
+ async context() {
758
+ if (this.On === undefined) {
759
+ this.On = false;
760
+ } else {
761
+ this.On = this.accessory.context.On;
762
+ }
763
+ if (this.Brightness === undefined) {
764
+ this.Brightness = 0;
765
+ } else {
766
+ this.Brightness = this.accessory.context.Brightness;
767
+ }
768
+ }
769
+
770
+ async refreshRate(device: device & devicesConfig): Promise<void> {
771
+ if (device.refreshRate) {
772
+ this.deviceRefreshRate = this.accessory.context.refreshRate = device.refreshRate;
773
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config refreshRate: ${this.deviceRefreshRate}`);
774
+ } else if (this.platform.config.options!.refreshRate) {
775
+ this.deviceRefreshRate = this.accessory.context.refreshRate = this.platform.config.options!.refreshRate;
776
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Platform Config refreshRate: ${this.deviceRefreshRate}`);
777
+ }
778
+ }
779
+
780
+ async config(device: device & devicesConfig): Promise<void> {
781
+ let config = {};
782
+ if (device.plug) {
783
+ config = device.plug;
784
+ }
785
+ if (device.connectionType !== undefined) {
786
+ config['connectionType'] = device.connectionType;
787
+ }
788
+ if (device.external !== undefined) {
789
+ config['external'] = device.external;
790
+ }
791
+ if (device.logging !== undefined) {
792
+ config['logging'] = device.logging;
793
+ }
794
+ if (device.refreshRate !== undefined) {
795
+ config['refreshRate'] = device.refreshRate;
796
+ }
797
+ if (device.scanDuration !== undefined) {
798
+ config['scanDuration'] = device.scanDuration;
799
+ }
800
+ if (device.offline !== undefined) {
801
+ config['offline'] = device.offline;
802
+ }
803
+ if (Object.entries(config).length !== 0) {
804
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Config: ${superStringify(config)}`);
805
+ }
806
+ }
807
+
808
+ async logs(device: device & devicesConfig): Promise<void> {
809
+ if (this.platform.debugMode) {
810
+ this.deviceLogging = this.accessory.context.logging = 'debugMode';
811
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Debug Mode Logging: ${this.deviceLogging}`);
812
+ } else if (device.logging) {
813
+ this.deviceLogging = this.accessory.context.logging = device.logging;
814
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config Logging: ${this.deviceLogging}`);
815
+ } else if (this.platform.config.options?.logging) {
816
+ this.deviceLogging = this.accessory.context.logging = this.platform.config.options?.logging;
817
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Platform Config Logging: ${this.deviceLogging}`);
818
+ } else {
819
+ this.deviceLogging = this.accessory.context.logging = 'standard';
820
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Logging Not Set, Using: ${this.deviceLogging}`);
821
+ }
822
+ }
823
+
824
+ /**
825
+ * Logging for Device
826
+ */
827
+ infoLog(...log: any[]): void {
828
+ if (this.enablingDeviceLogging()) {
829
+ this.platform.log.info(String(...log));
830
+ }
831
+ }
832
+
833
+ warnLog(...log: any[]): void {
834
+ if (this.enablingDeviceLogging()) {
835
+ this.platform.log.warn(String(...log));
836
+ }
837
+ }
838
+
839
+ debugWarnLog(...log: any[]): void {
840
+ if (this.enablingDeviceLogging()) {
841
+ if (this.deviceLogging?.includes('debug')) {
842
+ this.platform.log.warn('[DEBUG]', String(...log));
843
+ }
844
+ }
845
+ }
846
+
847
+ errorLog(...log: any[]): void {
848
+ if (this.enablingDeviceLogging()) {
849
+ this.platform.log.error(String(...log));
850
+ }
851
+ }
852
+
853
+ debugErrorLog(...log: any[]): void {
854
+ if (this.enablingDeviceLogging()) {
855
+ if (this.deviceLogging?.includes('debug')) {
856
+ this.platform.log.error('[DEBUG]', String(...log));
857
+ }
858
+ }
859
+ }
860
+
861
+ debugLog(...log: any[]): void {
862
+ if (this.enablingDeviceLogging()) {
863
+ if (this.deviceLogging === 'debug') {
864
+ this.platform.log.info('[DEBUG]', String(...log));
865
+ } else {
866
+ this.platform.log.debug(String(...log));
867
+ }
868
+ }
869
+ }
870
+
871
+ enablingDeviceLogging(): boolean {
872
+ return this.deviceLogging.includes('debug') || this.deviceLogging === 'standard';
873
+ }
874
+ }