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