@switchbot/homebridge-switchbot 3.7.1-beta.17 → 3.7.1-beta.19

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,1514 @@
1
+ import { interval, Subject } from 'rxjs';
2
+ import { debounceTime, skipWhile, take, tap } from 'rxjs/operators';
3
+ import { request } from 'undici';
4
+ import { Devices } from '../settings.js';
5
+ import { sleep } from '../utils.js';
6
+ /**
7
+ * Platform Accessory
8
+ * An instance of this class is created for each accessory your platform registers
9
+ * Each accessory may expose multiple services of different service types.
10
+ */
11
+ export class Bot {
12
+ platform;
13
+ accessory;
14
+ device;
15
+ api;
16
+ log;
17
+ config;
18
+ hap;
19
+ // Services
20
+ fanService;
21
+ doorService;
22
+ lockService;
23
+ faucetService;
24
+ windowService;
25
+ switchService;
26
+ outletService;
27
+ batteryService;
28
+ garageDoorService;
29
+ windowCoveringService;
30
+ statefulProgrammableSwitchService;
31
+ // Characteristic Values
32
+ On;
33
+ BatteryLevel;
34
+ FirmwareRevision;
35
+ StatusLowBattery;
36
+ // OpenAPI Status
37
+ OpenAPI_On;
38
+ OpenAPI_BatteryLevel;
39
+ OpenAPI_FirmwareRevision;
40
+ // BLE Status
41
+ BLE_On;
42
+ BLE_Mode;
43
+ BLE_BatteryLevel;
44
+ // BLE Others
45
+ BLE_IsConnected;
46
+ // Config
47
+ botMode;
48
+ allowPush;
49
+ doublePress;
50
+ scanDuration;
51
+ botDeviceType;
52
+ pushRatePress;
53
+ deviceLogging;
54
+ multiPressCount;
55
+ deviceRefreshRate;
56
+ // Updates
57
+ botUpdateInProgress;
58
+ doBotUpdate;
59
+ // Connection
60
+ OpenAPI;
61
+ BLE;
62
+ constructor(platform, accessory, device) {
63
+ this.platform = platform;
64
+ this.accessory = accessory;
65
+ this.device = device;
66
+ this.api = this.platform.api;
67
+ this.log = this.platform.log;
68
+ this.config = this.platform.config;
69
+ this.hap = this.api.hap;
70
+ // Connection
71
+ this.BLE = this.device.connectionType === 'BLE' || this.device.connectionType === 'BLE/OpenAPI';
72
+ this.OpenAPI = this.device.connectionType === 'OpenAPI' || this.device.connectionType === 'BLE/OpenAPI';
73
+ // default placeholders
74
+ this.deviceLogs(device);
75
+ this.deviceType(device);
76
+ this.scan(device);
77
+ this.refreshRate(device);
78
+ this.PressOrSwitch(device);
79
+ this.allowPushChanges(device);
80
+ this.deviceContext();
81
+ this.DoublePress(device);
82
+ this.deviceConfig(device);
83
+ this.multiPressCount = 0;
84
+ // this is subject we use to track when we need to POST changes to the SwitchBot API
85
+ this.doBotUpdate = new Subject();
86
+ this.botUpdateInProgress = false;
87
+ // Retrieve initial values and updateHomekit
88
+ this.refreshStatus();
89
+ // set accessory information
90
+ accessory
91
+ .getService(this.hap.Service.AccessoryInformation)
92
+ .setCharacteristic(this.hap.Characteristic.Manufacturer, 'SwitchBot')
93
+ .setCharacteristic(this.hap.Characteristic.Model, 'SWITCHBOT-BOT-S1')
94
+ .setCharacteristic(this.hap.Characteristic.SerialNumber, device.deviceId)
95
+ .setCharacteristic(this.hap.Characteristic.FirmwareRevision, accessory.context.FirmwareRevision);
96
+ // deviceType
97
+ if (this.botDeviceType === 'switch') {
98
+ this.removeFanService(accessory);
99
+ this.removeLockService(accessory);
100
+ this.removeDoorService(accessory);
101
+ this.removeFaucetService(accessory);
102
+ this.removeOutletService(accessory);
103
+ this.removeWindowService(accessory);
104
+ this.removeGarageDoorService(accessory);
105
+ this.removeWindowCoveringService(accessory);
106
+ this.removeStatefulProgrammableSwitchService(accessory);
107
+ // Add switchService
108
+ this.switchService = (accessory.getService(this.hap.Service.Switch)
109
+ || accessory.addService(this.hap.Service.Switch));
110
+ this.debugWarnLog(`${this.device.deviceType}: ${accessory.displayName} Displaying as Switch`);
111
+ this.switchService.setCharacteristic(this.hap.Characteristic.Name, accessory.displayName);
112
+ if (!this.switchService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
113
+ this.switchService.addCharacteristic(this.hap.Characteristic.ConfiguredName, accessory.displayName);
114
+ }
115
+ this.switchService.getCharacteristic(this.hap.Characteristic.On).onSet(this.OnSet.bind(this));
116
+ }
117
+ else if (this.botDeviceType === 'garagedoor') {
118
+ this.removeFanService(accessory);
119
+ this.removeLockService(accessory);
120
+ this.removeDoorService(accessory);
121
+ this.removeFaucetService(accessory);
122
+ this.removeOutletService(accessory);
123
+ this.removeSwitchService(accessory);
124
+ this.removeWindowService(accessory);
125
+ this.removeWindowCoveringService(accessory);
126
+ this.removeStatefulProgrammableSwitchService(accessory);
127
+ // Add garageDoorService
128
+ this.garageDoorService = (accessory.getService(this.hap.Service.GarageDoorOpener)
129
+ || accessory.addService(this.hap.Service.GarageDoorOpener));
130
+ this.debugWarnLog(`${this.device.deviceType}: ${accessory.displayName} Displaying as Garage Door Opener`);
131
+ this.garageDoorService.setCharacteristic(this.hap.Characteristic.Name, accessory.displayName);
132
+ if (!this.garageDoorService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
133
+ this.garageDoorService.addCharacteristic(this.hap.Characteristic.ConfiguredName, accessory.displayName);
134
+ }
135
+ this.garageDoorService.getCharacteristic(this.hap.Characteristic.TargetDoorState).onSet(this.OnSet.bind(this));
136
+ this.garageDoorService.setCharacteristic(this.hap.Characteristic.ObstructionDetected, false);
137
+ }
138
+ else if (this.botDeviceType === 'door') {
139
+ this.removeFanService(accessory);
140
+ this.removeLockService(accessory);
141
+ this.removeOutletService(accessory);
142
+ this.removeFaucetService(accessory);
143
+ this.removeSwitchService(accessory);
144
+ this.removeWindowService(accessory);
145
+ this.removeGarageDoorService(accessory);
146
+ this.removeWindowCoveringService(accessory);
147
+ this.removeStatefulProgrammableSwitchService(accessory);
148
+ // Add doorService
149
+ this.doorService = accessory.getService(this.hap.Service.Door)
150
+ || accessory.addService(this.hap.Service.Door);
151
+ this.debugWarnLog(`${this.device.deviceType}: ${accessory.displayName} Displaying as Door`);
152
+ this.doorService.setCharacteristic(this.hap.Characteristic.Name, accessory.displayName);
153
+ if (!this.doorService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
154
+ this.doorService.addCharacteristic(this.hap.Characteristic.ConfiguredName, accessory.displayName);
155
+ }
156
+ this.doorService
157
+ .getCharacteristic(this.hap.Characteristic.TargetPosition)
158
+ .setProps({
159
+ validValues: [0, 100],
160
+ minValue: 0,
161
+ maxValue: 100,
162
+ minStep: 100,
163
+ })
164
+ .onSet(this.OnSet.bind(this));
165
+ this.doorService.setCharacteristic(this.hap.Characteristic.PositionState, this.hap.Characteristic.PositionState.STOPPED);
166
+ }
167
+ else if (this.botDeviceType === 'window') {
168
+ this.removeFanService(accessory);
169
+ this.removeLockService(accessory);
170
+ this.removeDoorService(accessory);
171
+ this.removeOutletService(accessory);
172
+ this.removeFaucetService(accessory);
173
+ this.removeSwitchService(accessory);
174
+ this.removeGarageDoorService(accessory);
175
+ this.removeWindowCoveringService(accessory);
176
+ this.removeStatefulProgrammableSwitchService(accessory);
177
+ // Add windowService
178
+ this.windowService = accessory.getService(this.hap.Service.Window)
179
+ || accessory.addService(this.hap.Service.Window);
180
+ this.debugWarnLog(`${this.device.deviceType}: ${accessory.displayName} Displaying as Window`);
181
+ this.windowService.setCharacteristic(this.hap.Characteristic.Name, accessory.displayName);
182
+ if (!this.windowService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
183
+ this.windowService.addCharacteristic(this.hap.Characteristic.ConfiguredName, accessory.displayName);
184
+ }
185
+ this.windowService
186
+ .getCharacteristic(this.hap.Characteristic.TargetPosition)
187
+ .setProps({
188
+ validValues: [0, 100],
189
+ minValue: 0,
190
+ maxValue: 100,
191
+ minStep: 100,
192
+ })
193
+ .onSet(this.OnSet.bind(this));
194
+ this.windowService.setCharacteristic(this.hap.Characteristic.PositionState, this.hap.Characteristic.PositionState.STOPPED);
195
+ }
196
+ else if (this.botDeviceType === 'windowcovering') {
197
+ this.removeFanService(accessory);
198
+ this.removeLockService(accessory);
199
+ this.removeDoorService(accessory);
200
+ this.removeOutletService(accessory);
201
+ this.removeFaucetService(accessory);
202
+ this.removeSwitchService(accessory);
203
+ this.removeWindowService(accessory);
204
+ this.removeGarageDoorService(accessory);
205
+ this.removeStatefulProgrammableSwitchService(accessory);
206
+ // Add windowCoveringService
207
+ this.windowCoveringService = accessory.getService(this.hap.Service.WindowCovering)
208
+ || accessory.addService(this.hap.Service.WindowCovering);
209
+ this.debugWarnLog(`${this.device.deviceType}: ${accessory.displayName} Displaying as Window Covering`);
210
+ this.windowCoveringService.setCharacteristic(this.hap.Characteristic.Name, accessory.displayName);
211
+ if (!this.windowCoveringService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
212
+ this.windowCoveringService.addCharacteristic(this.hap.Characteristic.ConfiguredName, accessory.displayName);
213
+ }
214
+ this.windowCoveringService
215
+ .getCharacteristic(this.hap.Characteristic.TargetPosition)
216
+ .setProps({
217
+ validValues: [0, 100],
218
+ minValue: 0,
219
+ maxValue: 100,
220
+ minStep: 100,
221
+ })
222
+ .onSet(this.OnSet.bind(this));
223
+ this.windowCoveringService.setCharacteristic(this.hap.Characteristic.PositionState, this.hap.Characteristic.PositionState.STOPPED);
224
+ }
225
+ else if (this.botDeviceType === 'lock') {
226
+ this.removeFanService(accessory);
227
+ this.removeDoorService(accessory);
228
+ this.removeOutletService(accessory);
229
+ this.removeSwitchService(accessory);
230
+ this.removeFaucetService(accessory);
231
+ this.removeWindowService(accessory);
232
+ this.removeGarageDoorService(accessory);
233
+ this.removeWindowCoveringService(accessory);
234
+ this.removeStatefulProgrammableSwitchService(accessory);
235
+ // Add lockService
236
+ this.lockService = accessory.getService(this.hap.Service.LockMechanism)
237
+ || accessory.addService(this.hap.Service.LockMechanism);
238
+ this.debugWarnLog(`${this.device.deviceType}: ${accessory.displayName} Displaying as Lock`);
239
+ this.lockService.setCharacteristic(this.hap.Characteristic.Name, accessory.displayName);
240
+ if (!this.lockService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
241
+ this.lockService.addCharacteristic(this.hap.Characteristic.ConfiguredName, accessory.displayName);
242
+ }
243
+ this.lockService.getCharacteristic(this.hap.Characteristic.LockTargetState).onSet(this.OnSet.bind(this));
244
+ }
245
+ else if (this.botDeviceType === 'faucet') {
246
+ this.removeFanService(accessory);
247
+ this.removeLockService(accessory);
248
+ this.removeDoorService(accessory);
249
+ this.removeOutletService(accessory);
250
+ this.removeSwitchService(accessory);
251
+ this.removeWindowService(accessory);
252
+ this.removeGarageDoorService(accessory);
253
+ this.removeWindowCoveringService(accessory);
254
+ this.removeStatefulProgrammableSwitchService(accessory);
255
+ // Add faucetService
256
+ this.faucetService = accessory.getService(this.hap.Service.Faucet)
257
+ || accessory.addService(this.hap.Service.Faucet);
258
+ this.debugWarnLog(`${this.device.deviceType}: ${accessory.displayName} Displaying as Faucet`);
259
+ this.faucetService.setCharacteristic(this.hap.Characteristic.Name, accessory.displayName);
260
+ if (!this.faucetService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
261
+ this.faucetService.addCharacteristic(this.hap.Characteristic.ConfiguredName, accessory.displayName);
262
+ }
263
+ this.faucetService.getCharacteristic(this.hap.Characteristic.Active).onSet(this.OnSet.bind(this));
264
+ }
265
+ else if (this.botDeviceType === 'fan') {
266
+ this.removeLockService(accessory);
267
+ this.removeDoorService(accessory);
268
+ this.removeFaucetService(accessory);
269
+ this.removeOutletService(accessory);
270
+ this.removeSwitchService(accessory);
271
+ this.removeWindowService(accessory);
272
+ this.removeGarageDoorService(accessory);
273
+ this.removeWindowCoveringService(accessory);
274
+ this.removeStatefulProgrammableSwitchService(accessory);
275
+ // Add fanService
276
+ this.fanService = accessory.getService(this.hap.Service.Fan)
277
+ || accessory.addService(this.hap.Service.Fan);
278
+ this.debugWarnLog(`${this.device.deviceType}: ${accessory.displayName} Displaying as Fan`);
279
+ this.fanService.setCharacteristic(this.hap.Characteristic.Name, accessory.displayName);
280
+ if (!this.fanService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
281
+ this.fanService.addCharacteristic(this.hap.Characteristic.ConfiguredName, accessory.displayName);
282
+ }
283
+ this.fanService.getCharacteristic(this.hap.Characteristic.On).onSet(this.OnSet.bind(this));
284
+ }
285
+ else if (this.botDeviceType === 'stateful') {
286
+ this.removeFanService(accessory);
287
+ this.removeLockService(accessory);
288
+ this.removeDoorService(accessory);
289
+ this.removeFaucetService(accessory);
290
+ this.removeOutletService(accessory);
291
+ this.removeSwitchService(accessory);
292
+ this.removeWindowService(accessory);
293
+ this.removeGarageDoorService(accessory);
294
+ this.removeWindowCoveringService(accessory);
295
+ // Add statefulProgrammableSwitchService
296
+ this.statefulProgrammableSwitchService = (accessory.getService(this.hap.Service.StatefulProgrammableSwitch)
297
+ || accessory.addService(this.hap.Service.StatefulProgrammableSwitch));
298
+ this.debugWarnLog(`${this.device.deviceType}: ${accessory.displayName} Displaying as Stateful Programmable Switch`);
299
+ this.statefulProgrammableSwitchService.setCharacteristic(this.hap.Characteristic.Name, accessory.displayName);
300
+ if (!this.statefulProgrammableSwitchService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
301
+ this.statefulProgrammableSwitchService.addCharacteristic(this.hap.Characteristic.ConfiguredName, accessory.displayName);
302
+ }
303
+ this.statefulProgrammableSwitchService
304
+ .getCharacteristic(this.hap.Characteristic.ProgrammableSwitchOutputState)
305
+ .onSet(this.OnSet.bind(this));
306
+ }
307
+ else {
308
+ this.removeFanService(accessory);
309
+ this.removeLockService(accessory);
310
+ this.removeDoorService(accessory);
311
+ this.removeFaucetService(accessory);
312
+ this.removeSwitchService(accessory);
313
+ this.removeWindowService(accessory);
314
+ this.removeGarageDoorService(accessory);
315
+ this.removeWindowCoveringService(accessory);
316
+ this.removeStatefulProgrammableSwitchService(accessory);
317
+ // Add outletService
318
+ this.outletService = (accessory.getService(this.hap.Service.Outlet)
319
+ || accessory.addService(this.hap.Service.Outlet));
320
+ this.debugWarnLog(`${this.device.deviceType}: ${accessory.displayName} Displaying as Outlet`);
321
+ this.outletService.setCharacteristic(this.hap.Characteristic.Name, accessory.displayName);
322
+ if (!this.outletService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
323
+ this.outletService.addCharacteristic(this.hap.Characteristic.ConfiguredName, accessory.displayName);
324
+ }
325
+ this.outletService.getCharacteristic(this.hap.Characteristic.On).onSet(this.OnSet.bind(this));
326
+ }
327
+ // batteryService
328
+ this.batteryService = (this.accessory.getService(this.hap.Service.Battery)
329
+ || accessory.addService(this.hap.Service.Battery));
330
+ this.batteryService.setCharacteristic(this.hap.Characteristic.Name, `${accessory.displayName} Battery`);
331
+ if (!this.batteryService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
332
+ this.batteryService.addCharacteristic(this.hap.Characteristic.ConfiguredName, `${accessory.displayName} Battery`);
333
+ }
334
+ this.batteryService.setCharacteristic(this.hap.Characteristic.ChargingState, this.hap.Characteristic.ChargingState.NOT_CHARGEABLE);
335
+ // Retrieve initial values and updateHomekit
336
+ this.updateHomeKitCharacteristics();
337
+ // Start an update interval
338
+ interval(this.deviceRefreshRate * 1000)
339
+ .pipe(skipWhile(() => this.botUpdateInProgress))
340
+ .subscribe(async () => {
341
+ await this.refreshStatus();
342
+ });
343
+ // regisiter webhook event handler
344
+ if (this.device.webhook) {
345
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} is listening webhook.`);
346
+ this.platform.webhookEventHandler[this.device.deviceId] = async (context) => {
347
+ try {
348
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} received Webhook: ${JSON.stringify(context)}`);
349
+ const { power, battery, deviceMode } = context;
350
+ const { On, BatteryLevel, botMode } = this;
351
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} `
352
+ + '(power, battery, deviceMode) = '
353
+ + `Webhook:(${power}, ${battery}, ${deviceMode}), `
354
+ + `current:(${On}, ${BatteryLevel}, ${botMode})`);
355
+ this.On = power;
356
+ this.BatteryLevel = battery;
357
+ this.botMode = deviceMode;
358
+ this.updateHomeKitCharacteristics();
359
+ }
360
+ catch (e) {
361
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} `
362
+ + `failed to handle webhook. Received: ${JSON.stringify(context)} Error: ${e}`);
363
+ }
364
+ };
365
+ }
366
+ // Watch for Bot change events
367
+ // We put in a debounce of 1000ms so we don't make duplicate calls
368
+ this.doBotUpdate
369
+ .pipe(tap(() => {
370
+ this.botUpdateInProgress = true;
371
+ }), debounceTime(this.platform.config.options.pushRate * 1000))
372
+ .subscribe(async () => {
373
+ try {
374
+ if (this.doublePress > 1) {
375
+ interval(this.pushRatePress * 1000)
376
+ .pipe(take(this.doublePress))
377
+ .subscribe(async () => {
378
+ await this.pushChanges();
379
+ });
380
+ }
381
+ else {
382
+ await this.pushChanges();
383
+ }
384
+ }
385
+ catch (e) {
386
+ this.apiError(e);
387
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} failed pushChanges with ${this.device.connectionType} Connection,`
388
+ + ` Error Message: ${JSON.stringify(e.message)}`);
389
+ }
390
+ this.botUpdateInProgress = false;
391
+ });
392
+ }
393
+ /**
394
+ * Parse the device status from the SwitchBot api
395
+ */
396
+ async parseStatus() {
397
+ if (!this.device.enableCloudService && this.OpenAPI) {
398
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} parseStatus enableCloudService: ${this.device.enableCloudService}`);
399
+ }
400
+ else if (this.BLE) {
401
+ await this.BLEparseStatus();
402
+ }
403
+ else if (this.OpenAPI && this.platform.config.credentials?.token) {
404
+ await this.openAPIparseStatus();
405
+ }
406
+ else {
407
+ await this.offlineOff();
408
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} Connection Type:` + ` ${this.device.connectionType}, parseStatus will not happen.`);
409
+ }
410
+ }
411
+ async BLEparseStatus() {
412
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLEparseStatus`);
413
+ // BLEmode (true if Switch Mode) | (false if Press Mode)
414
+ if (this.BLE_Mode) {
415
+ this.accessory.context.On = this.On;
416
+ if (this.On === undefined) {
417
+ this.On = Boolean(this.BLE_On);
418
+ }
419
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Switch Mode, mode: ${this.BLE_Mode}, On: ${this.On}`);
420
+ }
421
+ else {
422
+ this.On = false;
423
+ this.accessory.context.On = this.On;
424
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Press Mode, mode: ${this.BLE_Mode}, On: ${this.On}`);
425
+ }
426
+ this.BatteryLevel = Number(this.BLE_BatteryLevel);
427
+ if (this.BatteryLevel < 10) {
428
+ this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
429
+ }
430
+ else {
431
+ this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
432
+ }
433
+ if (Number.isNaN(this.BatteryLevel)) {
434
+ this.BatteryLevel = 100;
435
+ }
436
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel},`
437
+ + ` StatusLowBattery: ${this.StatusLowBattery}`);
438
+ }
439
+ async openAPIparseStatus() {
440
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIparseStatus`);
441
+ if (this.botMode === 'press') {
442
+ this.On = false;
443
+ this.accessory.context.On = this.On;
444
+ }
445
+ else {
446
+ this.accessory.context.On = this.On;
447
+ if (this.On === undefined) {
448
+ this.On = false;
449
+ }
450
+ }
451
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`);
452
+ // Battery
453
+ this.BatteryLevel = Number(this.OpenAPI_BatteryLevel);
454
+ if (this.BatteryLevel < 10) {
455
+ this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
456
+ }
457
+ else {
458
+ this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
459
+ }
460
+ if (Number.isNaN(this.BatteryLevel)) {
461
+ this.BatteryLevel = 100;
462
+ }
463
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel},`
464
+ + ` StatusLowBattery: ${this.StatusLowBattery}`);
465
+ // FirmwareRevision
466
+ this.FirmwareRevision = this.OpenAPI_FirmwareRevision;
467
+ this.accessory.context.FirmwareRevision = this.FirmwareRevision;
468
+ }
469
+ /**
470
+ * Asks the SwitchBot API for the latest device information
471
+ */
472
+ async refreshStatus() {
473
+ if (!this.device.enableCloudService && this.OpenAPI) {
474
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} refreshStatus enableCloudService: ${this.device.enableCloudService}`);
475
+ }
476
+ else if (this.BLE) {
477
+ await this.BLERefreshStatus();
478
+ }
479
+ else if (this.OpenAPI && this.platform.config.credentials?.token) {
480
+ await this.openAPIRefreshStatus();
481
+ }
482
+ else {
483
+ await this.offlineOff();
484
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} Connection Type:`
485
+ + ` ${this.device.connectionType}, refreshStatus will not happen.`);
486
+ }
487
+ }
488
+ async BLERefreshStatus() {
489
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLERefreshStatus`);
490
+ const switchbot = await this.platform.connectBLE(this.accessory, this.device);
491
+ // Convert to BLE Address
492
+ this.device.bleMac = this.device
493
+ .deviceId.match(/.{1,2}/g)
494
+ .join(':')
495
+ .toLowerCase();
496
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLE Address: ${this.device.bleMac}`);
497
+ this.getCustomBLEAddress(switchbot);
498
+ // Start to monitor advertisement packets
499
+ (async () => {
500
+ // Start to monitor advertisement packets
501
+ await switchbot.startScan({
502
+ model: 'H',
503
+ id: this.device.bleMac,
504
+ });
505
+ // Set an event handler
506
+ switchbot.onadvertisement = (ad) => {
507
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ${JSON.stringify(ad, null, ' ')}`);
508
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} address: ${ad.address}, model: ${ad.model}`);
509
+ if (this.device.bleMac === ad.address && ad.model === 'H') {
510
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} serviceData: ${JSON.stringify(ad.serviceData)}`);
511
+ this.BLE_Mode = ad.serviceData.mode;
512
+ this.BLE_On = ad.serviceData.state;
513
+ this.BLE_BatteryLevel = ad.serviceData.battery;
514
+ }
515
+ else {
516
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} serviceData: ${JSON.stringify(ad.serviceData)}`);
517
+ }
518
+ };
519
+ // Wait 1 seconds
520
+ await switchbot.wait(this.scanDuration * 1000);
521
+ // Stop to monitor
522
+ await switchbot.stopScan();
523
+ // Update HomeKit
524
+ await this.BLEparseStatus();
525
+ await this.updateHomeKitCharacteristics();
526
+ })();
527
+ /* if (switchbot !== false) {
528
+ switchbot
529
+ .startScan({
530
+ model: 'H',
531
+ id: this.device.bleMac,
532
+ })
533
+ .then(async () => {
534
+ // Set an event handler
535
+ switchbot.onadvertisement = async (ad: ad) => {
536
+ this.debugLog(
537
+ `${this.device.deviceType}: ${this.accessory.displayName} Config BLE Address: ${this.device.bleMac},` +
538
+ ` BLE Address Found: ${ad.address}`,
539
+ );
540
+ this.BLE_Mode = ad.serviceData.mode;
541
+ this.BLE_On = ad.serviceData.state;
542
+ this.BLE_BatteryLevel = ad.serviceData.battery;
543
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} serviceData: ${JSON.stringify(ad.serviceData)}`);
544
+ this.debugLog(
545
+ `${this.device.deviceType}: ${this.accessory.displayName}, model: ${ad.serviceData.model}, modelName: ` +
546
+ `${ad.serviceData.modelName}, mode: ${ad.serviceData.mode}, state: ${ad.serviceData.state}, battery: ${ad.serviceData.battery}`,
547
+ );
548
+
549
+ if (ad.serviceData) {
550
+ this.BLE_IsConnected = true;
551
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} connected: ${this.BLE_IsConnected}`);
552
+ await this.stopScanning(switchbot);
553
+ } else {
554
+ this.BLE_IsConnected = false;
555
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} connected: ${this.BLE_IsConnected}`);
556
+ }
557
+ };
558
+ // Wait
559
+ return await sleep(this.scanDuration * 1000);
560
+ })
561
+ .then(async () => {
562
+ // Stop to monitor
563
+ await this.stopScanning(switchbot);
564
+ })
565
+ .catch(async (e: any) => {
566
+ this.apiError(e);
567
+ this.errorLog(
568
+ `${this.device.deviceType}: ${this.accessory.displayName} failed BLERefreshStatus with ${this.device.connectionType}` +
569
+ ` Connection, Error Message: ${JSON.stringify(e.message)}`,
570
+ );
571
+ await this.BLERefreshConnection(switchbot);
572
+ });
573
+ } else {
574
+ await this.BLERefreshConnection(switchbot);
575
+ } */
576
+ }
577
+ async openAPIRefreshStatus() {
578
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIRefreshStatus`);
579
+ try {
580
+ const { body, statusCode } = await request(`${Devices}/${this.device.deviceId}/status`, {
581
+ headers: this.platform.generateHeaders(),
582
+ });
583
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} statusCode: ${statusCode}`);
584
+ const deviceStatus = await body.json();
585
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} deviceStatus: ${JSON.stringify(deviceStatus)}`);
586
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} deviceStatus statusCode: ${deviceStatus.statusCode}`);
587
+ if ((statusCode === 200 || statusCode === 100) && (deviceStatus.statusCode === 200 || deviceStatus.statusCode === 100)) {
588
+ this.debugErrorLog(`${this.device.deviceType}: ${this.accessory.displayName} `
589
+ + `statusCode: ${statusCode} & deviceStatus StatusCode: ${deviceStatus.statusCode}`);
590
+ this.OpenAPI_On = deviceStatus.body.power;
591
+ this.OpenAPI_BatteryLevel = deviceStatus.body.battery;
592
+ this.OpenAPI_FirmwareRevision = deviceStatus.body.version;
593
+ this.openAPIparseStatus();
594
+ this.updateHomeKitCharacteristics();
595
+ }
596
+ else {
597
+ this.statusCode(statusCode);
598
+ this.statusCode(deviceStatus.statusCode);
599
+ }
600
+ }
601
+ catch (e) {
602
+ this.apiError(e);
603
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} failed openAPIRefreshStatus with ${this.device.connectionType}`
604
+ + ` Connection, Error Message: ${JSON.stringify(e.message)}`);
605
+ }
606
+ }
607
+ /**
608
+ * Pushes the requested changes to the SwitchBot API
609
+ * deviceType commandType Command command parameter Description
610
+ * Bot - "command" "turnOff" "default" = set to OFF state
611
+ * Bot - "command" "turnOn" "default" = set to ON state
612
+ * Bot - "command" "press" "default" = trigger press
613
+ */
614
+ async pushChanges() {
615
+ if (!this.device.enableCloudService && this.OpenAPI) {
616
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} pushChanges enableCloudService: ${this.device.enableCloudService}`);
617
+ }
618
+ else if (this.BLE) {
619
+ await this.BLEpushChanges();
620
+ }
621
+ else if (this.OpenAPI) {
622
+ await this.openAPIpushChanges();
623
+ }
624
+ else {
625
+ await this.offlineOff();
626
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} Connection Type:` + ` ${this.device.connectionType}, pushChanges will not happen.`);
627
+ }
628
+ // Refresh the status from the API
629
+ interval(15000)
630
+ .pipe(skipWhile(() => this.botUpdateInProgress))
631
+ .pipe(take(1))
632
+ .subscribe(async () => {
633
+ await this.refreshStatus();
634
+ });
635
+ }
636
+ async BLEpushChanges() {
637
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLEpushChanges`);
638
+ if (this.On !== this.accessory.context.On || this.allowPush) {
639
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLEpushChanges On: ${this.On} OnCached: ${this.accessory.context.On}`);
640
+ const switchbot = await this.platform.connectBLE(this.accessory, this.device);
641
+ // Convert to BLE Address
642
+ this.device.bleMac = this.device
643
+ .deviceId.match(/.{1,2}/g)
644
+ .join(':')
645
+ .toLowerCase();
646
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLE Address: ${this.device.bleMac}`);
647
+ // if (switchbot !== false) {
648
+ if (this.botMode === 'press') {
649
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Bot Mode: ${this.botMode}`);
650
+ switchbot
651
+ .discover({ model: 'H', quick: true, id: this.device.bleMac })
652
+ .then(async (device_list) => {
653
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`);
654
+ return await device_list[0].press({ id: this.device.bleMac });
655
+ })
656
+ .then(() => {
657
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Done.`);
658
+ this.accessory.context.On = this.On;
659
+ setTimeout(() => {
660
+ if (this.botDeviceType === 'switch') {
661
+ this.switchService?.getCharacteristic(this.hap.Characteristic.On).updateValue(this.On);
662
+ }
663
+ else {
664
+ this.outletService?.getCharacteristic(this.hap.Characteristic.On).updateValue(this.On);
665
+ }
666
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}, Switch Timeout`);
667
+ }, 500);
668
+ })
669
+ .catch(async (e) => {
670
+ this.apiError(e);
671
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} failed BLEpushChanges with ${this.device.connectionType}`
672
+ + ` Connection & botMode: ${this.botMode}, Error Message: ${JSON.stringify(e.message)}`);
673
+ await this.BLEPushConnection();
674
+ });
675
+ }
676
+ else if (this.botMode === 'switch') {
677
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Press Mode: ${this.botMode}`);
678
+ switchbot
679
+ .discover({ model: 'H', quick: true, id: this.device.bleMac })
680
+ .then(async (device_list) => {
681
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`);
682
+ return await this.retry({
683
+ max: this.maxRetry(),
684
+ fn: async () => {
685
+ if (this.On) {
686
+ return await device_list[0].turnOn({ id: this.device.bleMac });
687
+ }
688
+ else {
689
+ return await device_list[0].turnOff({ id: this.device.bleMac });
690
+ }
691
+ },
692
+ });
693
+ })
694
+ .then(() => {
695
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Done.`);
696
+ this.accessory.context.On = this.On;
697
+ })
698
+ .catch(async (e) => {
699
+ this.apiError(e);
700
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} failed BLEpushChanges with ${this.device.connectionType}`
701
+ + ` Connection & botMode: ${this.botMode}, Error Message: ${JSON.stringify(e.message)}`);
702
+ await this.BLEPushConnection();
703
+ });
704
+ }
705
+ else {
706
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Bot Mode: ${this.botMode}`);
707
+ }
708
+ }
709
+ else {
710
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} No BLEpushChanges.` + `On: ${this.On}, ` + `OnCached: ${this.accessory.context.On}`);
711
+ }
712
+ }
713
+ async openAPIpushChanges() {
714
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIpushChanges`);
715
+ if (this.multiPressCount > 0) {
716
+ this.debugLog(`${this.device.deviceType}: ${this.multiPressCount} request(s) queued.`);
717
+ this.On = true;
718
+ }
719
+ if (this.On !== this.accessory.context.On || this.allowPush || this.multiPressCount > 0) {
720
+ let command = '';
721
+ if (this.botMode === 'switch' && this.On) {
722
+ command = 'turnOn';
723
+ this.On = true;
724
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Switch Mode, Turning ${this.On}`);
725
+ }
726
+ else if (this.botMode === 'switch' && !this.On) {
727
+ command = 'turnOff';
728
+ this.On = false;
729
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Switch Mode, Turning ${this.On}`);
730
+ }
731
+ else if (this.botMode === 'press' || this.botMode === 'multipress') {
732
+ command = 'press';
733
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Press Mode`);
734
+ this.On = false;
735
+ }
736
+ else {
737
+ throw new Error(`${this.device.deviceType}: ${this.accessory.displayName} Device Parameters not set for this Bot.`);
738
+ }
739
+ const bodyChange = JSON.stringify({
740
+ command: `${command}`,
741
+ parameter: 'default',
742
+ commandType: 'command',
743
+ });
744
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Sending request to SwitchBot API, body: ${bodyChange},`);
745
+ try {
746
+ const { body, statusCode } = await request(`${Devices}/${this.device.deviceId}/commands`, {
747
+ body: bodyChange,
748
+ method: 'POST',
749
+ headers: this.platform.generateHeaders(),
750
+ });
751
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} statusCode: ${statusCode}`);
752
+ const deviceStatus = await body.json();
753
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} deviceStatus: ${JSON.stringify(deviceStatus)}`);
754
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} deviceStatus body: ${JSON.stringify(deviceStatus.body)}`);
755
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} deviceStatus statusCode: ${deviceStatus.statusCode}`);
756
+ if ((statusCode === 200 || statusCode === 100) && (deviceStatus.statusCode === 200 || deviceStatus.statusCode === 100)) {
757
+ this.debugErrorLog(`${this.device.deviceType}: ${this.accessory.displayName} `
758
+ + `statusCode: ${statusCode} & deviceStatus StatusCode: ${deviceStatus.statusCode}`);
759
+ }
760
+ else {
761
+ this.statusCode(statusCode);
762
+ this.statusCode(deviceStatus.statusCode);
763
+ }
764
+ if (this.device.bot?.mode === 'multipress') {
765
+ this.multiPressCount--;
766
+ if (this.multiPressCount > 0) {
767
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Multi Press Count: ${this.multiPressCount}`);
768
+ this.On = true;
769
+ this.openAPIpushChanges();
770
+ }
771
+ }
772
+ }
773
+ catch (e) {
774
+ this.apiError(e);
775
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} failed openAPIpushChanges with ${this.device.connectionType}`
776
+ + ` Connection, Error Message: ${JSON.stringify(e.message)}`);
777
+ }
778
+ }
779
+ else {
780
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} No openAPIpushChanges.`
781
+ + `On: ${this.On}, `
782
+ + `OnCached: ${this.accessory.context.On}`);
783
+ }
784
+ }
785
+ /**
786
+ * Handle requests to set the "On" characteristic
787
+ */
788
+ async OnSet(value) {
789
+ if (this.botDeviceType === 'garagedoor') {
790
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Set TargetDoorState: ${value}`);
791
+ if (value === this.hap.Characteristic.TargetDoorState.CLOSED) {
792
+ this.On = false;
793
+ }
794
+ else {
795
+ this.On = true;
796
+ }
797
+ }
798
+ else if (this.botDeviceType === 'door'
799
+ || this.botDeviceType === 'window'
800
+ || this.botDeviceType === 'windowcovering') {
801
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Set TargetPosition: ${value}`);
802
+ if (value === 0) {
803
+ this.On = false;
804
+ }
805
+ else {
806
+ this.On = true;
807
+ }
808
+ }
809
+ else if (this.botDeviceType === 'lock') {
810
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Set LockTargetState: ${value}`);
811
+ if (value === this.hap.Characteristic.LockTargetState.SECURED) {
812
+ this.On = false;
813
+ }
814
+ else {
815
+ this.On = true;
816
+ }
817
+ }
818
+ else if (this.botDeviceType === 'faucet') {
819
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Set Active: ${value}`);
820
+ if (value === this.hap.Characteristic.Active.INACTIVE) {
821
+ this.On = false;
822
+ }
823
+ else {
824
+ this.On = true;
825
+ }
826
+ }
827
+ else if (this.botDeviceType === 'stateful') {
828
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Set ProgrammableSwitchOutputState: ${value}`);
829
+ if (value === 0) {
830
+ this.On = false;
831
+ }
832
+ else {
833
+ this.On = true;
834
+ }
835
+ }
836
+ else {
837
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Set On: ${value}`);
838
+ if (this.device.bot?.mode === 'multipress') {
839
+ if (value === true) {
840
+ this.multiPressCount++;
841
+ this.debugLog(`${this.device.deviceType} set to Multi-Press. Multi-Press count: ${this.multiPressCount}`);
842
+ }
843
+ }
844
+ this.On = value;
845
+ }
846
+ this.doBotUpdate.next();
847
+ }
848
+ /**
849
+ * Updates the status for each of the HomeKit Characteristics
850
+ */
851
+ async updateHomeKitCharacteristics() {
852
+ // State
853
+ if (this.botDeviceType === 'garagedoor') {
854
+ if (this.On === undefined) {
855
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`);
856
+ }
857
+ else {
858
+ if (this.On) {
859
+ this.garageDoorService?.updateCharacteristic(this.hap.Characteristic.TargetDoorState, this.hap.Characteristic.TargetDoorState.OPEN);
860
+ this.garageDoorService?.updateCharacteristic(this.hap.Characteristic.CurrentDoorState, this.hap.Characteristic.CurrentDoorState.OPEN);
861
+ this.debugLog(`${this.device.deviceType}: ` + `${this.accessory.displayName} updateCharacteristic TargetDoorState: Open, CurrentDoorState: Open`);
862
+ }
863
+ else {
864
+ this.garageDoorService?.updateCharacteristic(this.hap.Characteristic.TargetDoorState, this.hap.Characteristic.TargetDoorState.CLOSED);
865
+ this.garageDoorService?.updateCharacteristic(this.hap.Characteristic.CurrentDoorState, this.hap.Characteristic.CurrentDoorState.CLOSED);
866
+ this.debugLog(`${this.device.deviceType}: ` + `${this.accessory.displayName} updateCharacteristic TargetDoorState: Open, CurrentDoorState: Open`);
867
+ }
868
+ }
869
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Garage Door On: ${this.On}`);
870
+ }
871
+ else if (this.botDeviceType === 'door') {
872
+ if (this.On === undefined) {
873
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`);
874
+ }
875
+ else {
876
+ if (this.On) {
877
+ this.doorService?.updateCharacteristic(this.hap.Characteristic.TargetPosition, 100);
878
+ this.doorService?.updateCharacteristic(this.hap.Characteristic.CurrentPosition, 100);
879
+ this.doorService?.updateCharacteristic(this.hap.Characteristic.PositionState, this.hap.Characteristic.PositionState.STOPPED);
880
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic TargetPosition: 100, CurrentPosition: 100`);
881
+ }
882
+ else {
883
+ this.doorService?.updateCharacteristic(this.hap.Characteristic.TargetPosition, 0);
884
+ this.doorService?.updateCharacteristic(this.hap.Characteristic.CurrentPosition, 0);
885
+ this.doorService?.updateCharacteristic(this.hap.Characteristic.PositionState, this.hap.Characteristic.PositionState.STOPPED);
886
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic TargetPosition: 0, CurrentPosition: 0`);
887
+ }
888
+ }
889
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Door On: ${this.On}`);
890
+ }
891
+ else if (this.botDeviceType === 'window') {
892
+ if (this.On === undefined) {
893
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`);
894
+ }
895
+ else {
896
+ if (this.On) {
897
+ this.windowService?.updateCharacteristic(this.hap.Characteristic.TargetPosition, 100);
898
+ this.windowService?.updateCharacteristic(this.hap.Characteristic.CurrentPosition, 100);
899
+ this.windowService?.updateCharacteristic(this.hap.Characteristic.PositionState, this.hap.Characteristic.PositionState.STOPPED);
900
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic TargetPosition: 100, CurrentPosition: 100`);
901
+ }
902
+ else {
903
+ this.windowService?.updateCharacteristic(this.hap.Characteristic.TargetPosition, 0);
904
+ this.windowService?.updateCharacteristic(this.hap.Characteristic.CurrentPosition, 0);
905
+ this.windowService?.updateCharacteristic(this.hap.Characteristic.PositionState, this.hap.Characteristic.PositionState.STOPPED);
906
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic TargetPosition: 0, CurrentPosition: 0`);
907
+ }
908
+ }
909
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Window On: ${this.On}`);
910
+ }
911
+ else if (this.botDeviceType === 'windowcovering') {
912
+ if (this.On === undefined) {
913
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`);
914
+ }
915
+ else {
916
+ if (this.On) {
917
+ this.windowCoveringService?.updateCharacteristic(this.hap.Characteristic.TargetPosition, 100);
918
+ this.windowCoveringService?.updateCharacteristic(this.hap.Characteristic.CurrentPosition, 100);
919
+ this.windowCoveringService?.updateCharacteristic(this.hap.Characteristic.PositionState, this.hap.Characteristic.PositionState.STOPPED);
920
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic TargetPosition: 100, CurrentPosition: 100`);
921
+ }
922
+ else {
923
+ this.windowCoveringService?.updateCharacteristic(this.hap.Characteristic.TargetPosition, 0);
924
+ this.windowCoveringService?.updateCharacteristic(this.hap.Characteristic.CurrentPosition, 0);
925
+ this.windowCoveringService?.updateCharacteristic(this.hap.Characteristic.PositionState, this.hap.Characteristic.PositionState.STOPPED);
926
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic TargetPosition: 0, CurrentPosition: 0`);
927
+ }
928
+ }
929
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Window Covering On: ${this.On}`);
930
+ }
931
+ else if (this.botDeviceType === 'lock') {
932
+ if (this.On === undefined) {
933
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`);
934
+ }
935
+ else {
936
+ if (this.On) {
937
+ this.lockService?.updateCharacteristic(this.hap.Characteristic.LockTargetState, this.hap.Characteristic.LockTargetState.UNSECURED);
938
+ this.lockService?.updateCharacteristic(this.hap.Characteristic.LockCurrentState, this.hap.Characteristic.LockCurrentState.UNSECURED);
939
+ this.debugLog(`${this.device.deviceType}: `
940
+ + `${this.accessory.displayName} updateCharacteristic LockTargetState: UNSECURED, LockCurrentState: UNSECURED`);
941
+ }
942
+ else {
943
+ this.lockService?.updateCharacteristic(this.hap.Characteristic.LockTargetState, this.hap.Characteristic.LockTargetState.SECURED);
944
+ this.lockService?.updateCharacteristic(this.hap.Characteristic.LockCurrentState, this.hap.Characteristic.LockCurrentState.SECURED);
945
+ this.debugLog(`${this.device.deviceType}: ` + `${this.accessory.displayName} updateCharacteristic LockTargetState: SECURED, LockCurrentState: SECURED`);
946
+ }
947
+ }
948
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Lock On: ${this.On}`);
949
+ }
950
+ else if (this.botDeviceType === 'faucet') {
951
+ if (this.On === undefined) {
952
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`);
953
+ }
954
+ else {
955
+ if (this.On) {
956
+ this.faucetService?.updateCharacteristic(this.hap.Characteristic.Active, this.hap.Characteristic.Active.ACTIVE);
957
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic Active: ${this.On}`);
958
+ }
959
+ else {
960
+ this.faucetService?.updateCharacteristic(this.hap.Characteristic.Active, this.hap.Characteristic.Active.INACTIVE);
961
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic Active: ${this.On}`);
962
+ }
963
+ }
964
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Faucet On: ${this.On}`);
965
+ }
966
+ else if (this.botDeviceType === 'fan') {
967
+ if (this.On === undefined) {
968
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`);
969
+ }
970
+ else {
971
+ if (this.On) {
972
+ this.fanService?.updateCharacteristic(this.hap.Characteristic.On, this.On);
973
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic On: ${this.On}`);
974
+ }
975
+ else {
976
+ this.fanService?.updateCharacteristic(this.hap.Characteristic.On, this.On);
977
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic On: ${this.On}`);
978
+ }
979
+ }
980
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Fan On: ${this.On}`);
981
+ }
982
+ else if (this.botDeviceType === 'stateful') {
983
+ if (this.On === undefined) {
984
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`);
985
+ }
986
+ else {
987
+ if (this.On) {
988
+ this.statefulProgrammableSwitchService?.updateCharacteristic(this.hap.Characteristic.ProgrammableSwitchEvent, this.hap.Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS);
989
+ this.statefulProgrammableSwitchService?.updateCharacteristic(this.hap.Characteristic.ProgrammableSwitchOutputState, 1);
990
+ this.debugLog(`${this.device.deviceType}: `
991
+ + `${this.accessory.displayName} updateCharacteristic ProgrammableSwitchEvent: SINGLE, ProgrammableSwitchOutputState: 1`);
992
+ }
993
+ else {
994
+ this.statefulProgrammableSwitchService?.updateCharacteristic(this.hap.Characteristic.ProgrammableSwitchEvent, this.hap.Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS);
995
+ this.statefulProgrammableSwitchService?.updateCharacteristic(this.hap.Characteristic.ProgrammableSwitchOutputState, 0);
996
+ this.debugLog(`${this.device.deviceType}: `
997
+ + `${this.accessory.displayName} updateCharacteristic ProgrammableSwitchEvent: SINGLE, ProgrammableSwitchOutputState: 0`);
998
+ }
999
+ }
1000
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} StatefulProgrammableSwitch On: ${this.On}`);
1001
+ }
1002
+ else if (this.botDeviceType === 'switch') {
1003
+ if (this.On === undefined) {
1004
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`);
1005
+ }
1006
+ else {
1007
+ this.switchService?.updateCharacteristic(this.hap.Characteristic.On, this.On);
1008
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic On: ${this.On}`);
1009
+ }
1010
+ }
1011
+ else {
1012
+ if (this.On === undefined) {
1013
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} On: ${this.On}`);
1014
+ }
1015
+ else {
1016
+ this.outletService?.updateCharacteristic(this.hap.Characteristic.On, this.On);
1017
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic On: ${this.On}`);
1018
+ }
1019
+ }
1020
+ this.accessory.context.On = this.On;
1021
+ // BatteryLevel
1022
+ if (this.BatteryLevel === undefined) {
1023
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel}`);
1024
+ }
1025
+ else {
1026
+ this.accessory.context.BatteryLevel = this.BatteryLevel;
1027
+ this.batteryService?.updateCharacteristic(this.hap.Characteristic.BatteryLevel, this.BatteryLevel);
1028
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic BatteryLevel: ${this.BatteryLevel}`);
1029
+ }
1030
+ // StatusLowBattery
1031
+ if (this.StatusLowBattery === undefined) {
1032
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} StatusLowBattery: ${this.StatusLowBattery}`);
1033
+ }
1034
+ else {
1035
+ this.accessory.context.StatusLowBattery = this.StatusLowBattery;
1036
+ this.batteryService?.updateCharacteristic(this.hap.Characteristic.StatusLowBattery, this.StatusLowBattery);
1037
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic StatusLowBattery: ${this.StatusLowBattery}`);
1038
+ }
1039
+ }
1040
+ async removeOutletService(accessory) {
1041
+ // If outletService still present, then remove first
1042
+ this.outletService = this.accessory.getService(this.hap.Service.Outlet);
1043
+ if (this.outletService) {
1044
+ this.warnLog(`${this.device.deviceType}: ${accessory.displayName} Removing Leftover Outlet Service`);
1045
+ }
1046
+ accessory.removeService(this.outletService);
1047
+ }
1048
+ async removeGarageDoorService(accessory) {
1049
+ // If garageDoorService still present, then remove first
1050
+ this.garageDoorService = this.accessory.getService(this.hap.Service.GarageDoorOpener);
1051
+ if (this.garageDoorService) {
1052
+ this.warnLog(`${this.device.deviceType}: ${accessory.displayName} Removing Leftover Garage Door Service`);
1053
+ }
1054
+ accessory.removeService(this.garageDoorService);
1055
+ }
1056
+ async removeDoorService(accessory) {
1057
+ // If doorService still present, then remove first
1058
+ this.doorService = this.accessory.getService(this.hap.Service.Door);
1059
+ if (this.doorService) {
1060
+ this.warnLog(`${this.device.deviceType}: ${accessory.displayName} Removing Leftover Door Service`);
1061
+ }
1062
+ accessory.removeService(this.doorService);
1063
+ }
1064
+ async removeLockService(accessory) {
1065
+ // If lockService still present, then remove first
1066
+ this.lockService = this.accessory.getService(this.hap.Service.LockMechanism);
1067
+ if (this.lockService) {
1068
+ this.warnLog(`${this.device.deviceType}: ${accessory.displayName} Removing Leftover Lock Service`);
1069
+ }
1070
+ accessory.removeService(this.lockService);
1071
+ }
1072
+ async removeFaucetService(accessory) {
1073
+ // If faucetService still present, then remove first
1074
+ this.faucetService = this.accessory.getService(this.hap.Service.Faucet);
1075
+ if (this.faucetService) {
1076
+ this.warnLog(`${this.device.deviceType}: ${accessory.displayName} Removing Leftover Faucet Service`);
1077
+ }
1078
+ accessory.removeService(this.faucetService);
1079
+ }
1080
+ async removeFanService(accessory) {
1081
+ // If fanService still present, then remove first
1082
+ this.fanService = this.accessory.getService(this.hap.Service.Fan);
1083
+ if (this.fanService) {
1084
+ this.warnLog(`${this.device.deviceType}: ${accessory.displayName} Removing Leftover Fan Service`);
1085
+ }
1086
+ accessory.removeService(this.fanService);
1087
+ }
1088
+ async removeWindowService(accessory) {
1089
+ // If windowService still present, then remove first
1090
+ this.windowService = this.accessory.getService(this.hap.Service.Window);
1091
+ if (this.windowService) {
1092
+ this.warnLog(`${this.device.deviceType}: ${accessory.displayName} Removing Leftover Window Service`);
1093
+ }
1094
+ accessory.removeService(this.windowService);
1095
+ }
1096
+ async removeWindowCoveringService(accessory) {
1097
+ // If windowCoveringService still present, then remove first
1098
+ this.windowCoveringService = this.accessory.getService(this.hap.Service.WindowCovering);
1099
+ if (this.windowCoveringService) {
1100
+ this.warnLog(`${this.device.deviceType}: ${accessory.displayName} Removing Leftover Window Covering Service`);
1101
+ }
1102
+ accessory.removeService(this.windowCoveringService);
1103
+ }
1104
+ async removeStatefulProgrammableSwitchService(accessory) {
1105
+ // If statefulProgrammableSwitchService still present, then remove first
1106
+ this.statefulProgrammableSwitchService = this.accessory.getService(this.hap.Service.StatefulProgrammableSwitch);
1107
+ if (this.statefulProgrammableSwitchService) {
1108
+ this.warnLog(`${this.device.deviceType}: ${accessory.displayName} Removing Leftover Stateful Programmable Switch Service`);
1109
+ }
1110
+ accessory.removeService(this.statefulProgrammableSwitchService);
1111
+ }
1112
+ async removeSwitchService(accessory) {
1113
+ // If switchService still present, then remove first
1114
+ this.switchService = this.accessory.getService(this.hap.Service.Switch);
1115
+ if (this.switchService) {
1116
+ this.warnLog(`${this.device.deviceType}: ${accessory.displayName} Removing Leftover Switch Service`);
1117
+ }
1118
+ accessory.removeService(this.switchService);
1119
+ }
1120
+ DoublePress(device) {
1121
+ if (device.bot?.doublePress) {
1122
+ this.doublePress = device.bot?.doublePress;
1123
+ this.accessory.context.doublePress = this.doublePress;
1124
+ }
1125
+ else {
1126
+ this.doublePress = 1;
1127
+ }
1128
+ }
1129
+ async stopScanning(switchbot) {
1130
+ switchbot.stopScan();
1131
+ if (this.BLE_IsConnected) {
1132
+ await this.BLEparseStatus();
1133
+ await this.updateHomeKitCharacteristics();
1134
+ }
1135
+ else {
1136
+ await this.BLERefreshConnection(switchbot);
1137
+ }
1138
+ }
1139
+ async getCustomBLEAddress(switchbot) {
1140
+ if (this.device.customBLEaddress && this.deviceLogging.includes('debug')) {
1141
+ (async () => {
1142
+ // Start to monitor advertisement packets
1143
+ await switchbot.startScan({
1144
+ model: 'H',
1145
+ });
1146
+ // Set an event handler
1147
+ switchbot.onadvertisement = (ad) => {
1148
+ this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} ad: ${JSON.stringify(ad, null, ' ')}`);
1149
+ };
1150
+ await sleep(10000);
1151
+ // Stop to monitor
1152
+ switchbot.stopScan();
1153
+ })();
1154
+ }
1155
+ }
1156
+ async BLEPushConnection() {
1157
+ if (this.platform.config.credentials?.token && this.device.connectionType === 'BLE/OpenAPI') {
1158
+ this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} Using OpenAPI Connection to Push Changes`);
1159
+ await this.openAPIpushChanges();
1160
+ }
1161
+ }
1162
+ async BLERefreshConnection(switchbot) {
1163
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} wasn't able to establish BLE Connection, node-switchbot:`
1164
+ + ` ${JSON.stringify(switchbot)}`);
1165
+ if (this.platform.config.credentials?.token && this.device.connectionType === 'BLE/OpenAPI') {
1166
+ this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} Using OpenAPI Connection to Refresh Status`);
1167
+ await this.openAPIRefreshStatus();
1168
+ }
1169
+ }
1170
+ async retry({ max, fn }) {
1171
+ return fn().catch(async (e) => {
1172
+ if (max === 0) {
1173
+ throw e;
1174
+ }
1175
+ this.infoLog(e);
1176
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Retrying`);
1177
+ await sleep(1000);
1178
+ return this.retry({ max: max - 1, fn });
1179
+ });
1180
+ }
1181
+ maxRetry() {
1182
+ if (this.device.maxRetry) {
1183
+ return this.device.maxRetry;
1184
+ }
1185
+ else {
1186
+ return 5;
1187
+ }
1188
+ }
1189
+ async PressOrSwitch(device) {
1190
+ if (!device.bot?.mode) {
1191
+ this.botMode = 'switch';
1192
+ this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} does not have bot mode set in the Plugin's SwitchBot Device Settings,`);
1193
+ this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} is defaulting to "${this.botMode}" mode, you may experience issues.`);
1194
+ }
1195
+ else if (device.bot?.mode === 'switch') {
1196
+ this.botMode = 'switch';
1197
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Bot Mode: ${this.botMode}`);
1198
+ }
1199
+ else if (device.bot?.mode === 'press') {
1200
+ this.botMode = 'press';
1201
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Bot Mode: ${this.botMode}`);
1202
+ }
1203
+ else if (device.bot?.mode === 'multipress') {
1204
+ this.botMode = 'multipress';
1205
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Bot Mode: ${this.botMode}`);
1206
+ }
1207
+ else {
1208
+ throw new Error(`${this.device.deviceType}: ${this.accessory.displayName} Bot Mode: ${this.botMode}`);
1209
+ }
1210
+ }
1211
+ async allowPushChanges(device) {
1212
+ if (device.bot?.allowPush) {
1213
+ this.allowPush = true;
1214
+ }
1215
+ else {
1216
+ this.allowPush = false;
1217
+ }
1218
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Allowing Push Changes: ${this.allowPush}`);
1219
+ }
1220
+ async scan(device) {
1221
+ if (device.scanDuration) {
1222
+ this.scanDuration = this.accessory.context.scanDuration = device.scanDuration;
1223
+ if (this.BLE) {
1224
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config scanDuration: ${this.scanDuration}`);
1225
+ }
1226
+ }
1227
+ else {
1228
+ this.scanDuration = this.accessory.context.scanDuration = 1;
1229
+ if (this.BLE) {
1230
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Default scanDuration: ${this.scanDuration}`);
1231
+ }
1232
+ }
1233
+ }
1234
+ async statusCode(statusCode) {
1235
+ switch (statusCode) {
1236
+ case 151:
1237
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Command not supported by this deviceType, statusCode: ${statusCode}`);
1238
+ break;
1239
+ case 152:
1240
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Device not found, statusCode: ${statusCode}`);
1241
+ break;
1242
+ case 160:
1243
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Command is not supported, statusCode: ${statusCode}`);
1244
+ break;
1245
+ case 161:
1246
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Device is offline, statusCode: ${statusCode}`);
1247
+ this.offlineOff();
1248
+ break;
1249
+ case 171:
1250
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Hub Device is offline, statusCode: ${statusCode}. `
1251
+ + `Hub: ${this.device.hubDeviceId}`);
1252
+ this.offlineOff();
1253
+ break;
1254
+ case 190:
1255
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Device internal error due to device states not synchronized with server,`
1256
+ + ` Or command format is invalid, statusCode: ${statusCode}`);
1257
+ break;
1258
+ case 100:
1259
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Command successfully sent, statusCode: ${statusCode}`);
1260
+ break;
1261
+ case 200:
1262
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Request successful, statusCode: ${statusCode}`);
1263
+ break;
1264
+ case 400:
1265
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Bad Request, The client has issued an invalid request. `
1266
+ + `This is commonly used to specify validation errors in a request payload, statusCode: ${statusCode}`);
1267
+ break;
1268
+ case 401:
1269
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Unauthorized, Authorization for the API is required, `
1270
+ + `but the request has not been authenticated, statusCode: ${statusCode}`);
1271
+ break;
1272
+ case 403:
1273
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Forbidden, The request has been authenticated but does not `
1274
+ + `have appropriate permissions, or a requested resource is not found, statusCode: ${statusCode}`);
1275
+ break;
1276
+ case 404:
1277
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Not Found, Specifies the requested path does not exist, `
1278
+ + `statusCode: ${statusCode}`);
1279
+ break;
1280
+ case 406:
1281
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Not Acceptable, The client has requested a MIME type via `
1282
+ + `the Accept header for a value not supported by the server, statusCode: ${statusCode}`);
1283
+ break;
1284
+ case 415:
1285
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Unsupported Media Type, The client has defined a contentType `
1286
+ + `header that is not supported by the server, statusCode: ${statusCode}`);
1287
+ break;
1288
+ case 422:
1289
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Unprocessable Entity, The client has made a valid request, `
1290
+ + `but the server cannot process it. This is often used for APIs for which certain limits have been exceeded, statusCode: ${statusCode}`);
1291
+ break;
1292
+ case 429:
1293
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Too Many Requests, The client has exceeded the number of `
1294
+ + `requests allowed for a given time window, statusCode: ${statusCode}`);
1295
+ break;
1296
+ case 500:
1297
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Internal Server Error, An unexpected error on the SmartThings `
1298
+ + `servers has occurred. These errors should be rare, statusCode: ${statusCode}`);
1299
+ break;
1300
+ default:
1301
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Unknown statusCode: `
1302
+ + `${statusCode}, Submit Bugs Here: ' + 'https://tinyurl.com/SwitchBotBug`);
1303
+ }
1304
+ }
1305
+ async offlineOff() {
1306
+ if (this.device.offline) {
1307
+ await this.deviceContext();
1308
+ await this.updateHomeKitCharacteristics();
1309
+ }
1310
+ }
1311
+ async apiError(e) {
1312
+ if (this.botDeviceType === 'garagedoor') {
1313
+ this.garageDoorService?.updateCharacteristic(this.hap.Characteristic.TargetDoorState, e);
1314
+ this.garageDoorService?.updateCharacteristic(this.hap.Characteristic.CurrentDoorState, e);
1315
+ this.garageDoorService?.updateCharacteristic(this.hap.Characteristic.ObstructionDetected, e);
1316
+ }
1317
+ else if (this.botDeviceType === 'door') {
1318
+ this.doorService?.updateCharacteristic(this.hap.Characteristic.TargetPosition, e);
1319
+ this.doorService?.updateCharacteristic(this.hap.Characteristic.CurrentPosition, e);
1320
+ this.doorService?.updateCharacteristic(this.hap.Characteristic.PositionState, e);
1321
+ }
1322
+ else if (this.botDeviceType === 'window') {
1323
+ this.windowService?.updateCharacteristic(this.hap.Characteristic.TargetPosition, e);
1324
+ this.windowService?.updateCharacteristic(this.hap.Characteristic.CurrentPosition, e);
1325
+ this.windowService?.updateCharacteristic(this.hap.Characteristic.PositionState, e);
1326
+ }
1327
+ else if (this.botDeviceType === 'windowcovering') {
1328
+ this.windowCoveringService?.updateCharacteristic(this.hap.Characteristic.TargetPosition, e);
1329
+ this.windowCoveringService?.updateCharacteristic(this.hap.Characteristic.CurrentPosition, e);
1330
+ this.windowCoveringService?.updateCharacteristic(this.hap.Characteristic.PositionState, e);
1331
+ }
1332
+ else if (this.botDeviceType === 'lock') {
1333
+ this.doorService?.updateCharacteristic(this.hap.Characteristic.LockTargetState, e);
1334
+ this.doorService?.updateCharacteristic(this.hap.Characteristic.LockCurrentState, e);
1335
+ }
1336
+ else if (this.botDeviceType === 'faucet') {
1337
+ this.faucetService?.updateCharacteristic(this.hap.Characteristic.Active, e);
1338
+ }
1339
+ else if (this.botDeviceType === 'fan') {
1340
+ this.fanService?.updateCharacteristic(this.hap.Characteristic.On, e);
1341
+ }
1342
+ else if (this.botDeviceType === 'stateful') {
1343
+ this.statefulProgrammableSwitchService?.updateCharacteristic(this.hap.Characteristic.ProgrammableSwitchEvent, e);
1344
+ this.statefulProgrammableSwitchService?.updateCharacteristic(this.hap.Characteristic.ProgrammableSwitchOutputState, e);
1345
+ }
1346
+ else if (this.botDeviceType === 'switch') {
1347
+ this.switchService?.updateCharacteristic(this.hap.Characteristic.On, e);
1348
+ }
1349
+ else {
1350
+ this.outletService?.updateCharacteristic(this.hap.Characteristic.On, e);
1351
+ }
1352
+ this.batteryService?.updateCharacteristic(this.hap.Characteristic.BatteryLevel, e);
1353
+ this.batteryService?.updateCharacteristic(this.hap.Characteristic.StatusLowBattery, e);
1354
+ }
1355
+ async deviceType(device) {
1356
+ if (!device.bot?.deviceType && this.accessory.context.deviceType) {
1357
+ this.botDeviceType = this.accessory.context.deviceType;
1358
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Type: ${this.botDeviceType}, from Accessory Cache.`);
1359
+ }
1360
+ else if (device.bot?.deviceType) {
1361
+ this.accessory.context.deviceType = device.bot.deviceType;
1362
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} Accessory Cache: ${this.accessory.context.deviceType}`);
1363
+ this.botDeviceType = this.accessory.context.deviceType;
1364
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Type: ${this.botDeviceType}`);
1365
+ }
1366
+ else {
1367
+ this.botDeviceType = 'outlet';
1368
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} No Device Type Set, deviceType: ${this.device.bot?.deviceType}`);
1369
+ this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} Using default deviceType: ${this.botDeviceType}`);
1370
+ }
1371
+ }
1372
+ async deviceContext() {
1373
+ if (this.On === undefined) {
1374
+ this.On = false;
1375
+ this.accessory.context.On = this.On;
1376
+ }
1377
+ else {
1378
+ this.On = this.accessory.context.On;
1379
+ }
1380
+ if (this.BatteryLevel === undefined) {
1381
+ this.BatteryLevel = 100;
1382
+ }
1383
+ else {
1384
+ this.BatteryLevel = this.accessory.context.BatteryLevel;
1385
+ }
1386
+ if (this.StatusLowBattery === undefined) {
1387
+ this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
1388
+ this.accessory.context.StatusLowBattery = this.StatusLowBattery;
1389
+ }
1390
+ else {
1391
+ this.StatusLowBattery = this.accessory.context.StatusLowBattery;
1392
+ }
1393
+ if (this.FirmwareRevision === undefined) {
1394
+ this.FirmwareRevision = this.platform.version;
1395
+ this.accessory.context.FirmwareRevision = this.FirmwareRevision;
1396
+ }
1397
+ }
1398
+ async refreshRate(device) {
1399
+ if (device.refreshRate) {
1400
+ this.deviceRefreshRate = this.accessory.context.refreshRate = device.refreshRate;
1401
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config refreshRate: ${this.deviceRefreshRate}`);
1402
+ }
1403
+ else if (this.platform.config.options.refreshRate) {
1404
+ this.deviceRefreshRate = this.accessory.context.refreshRate = this.platform.config.options.refreshRate;
1405
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Platform Config refreshRate: ${this.deviceRefreshRate}`);
1406
+ }
1407
+ // pushRatePress
1408
+ if (device?.bot?.pushRatePress) {
1409
+ this.pushRatePress = device?.bot?.pushRatePress;
1410
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config Bot pushRatePress: ${this.pushRatePress}`);
1411
+ }
1412
+ else {
1413
+ this.pushRatePress = 15;
1414
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Default Bot pushRatePress: ${this.pushRatePress}`);
1415
+ }
1416
+ }
1417
+ async deviceConfig(device) {
1418
+ let config = {};
1419
+ if (device.bot) {
1420
+ config = device.bot;
1421
+ }
1422
+ if (device.connectionType !== undefined) {
1423
+ config.connectionType = device.connectionType;
1424
+ }
1425
+ if (device.external !== undefined) {
1426
+ config.external = device.external;
1427
+ }
1428
+ if (device.logging !== undefined) {
1429
+ config.logging = device.logging;
1430
+ }
1431
+ if (device.refreshRate !== undefined) {
1432
+ config.refreshRate = device.refreshRate;
1433
+ }
1434
+ if (device.scanDuration !== undefined) {
1435
+ config.scanDuration = device.scanDuration;
1436
+ }
1437
+ if (device.offline !== undefined) {
1438
+ config.offline = device.offline;
1439
+ }
1440
+ if (device.maxRetry !== undefined) {
1441
+ config.maxRetry = device.maxRetry;
1442
+ }
1443
+ if (device.webhook !== undefined) {
1444
+ config.webhook = device.webhook;
1445
+ }
1446
+ if (Object.entries(config).length !== 0) {
1447
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} Config: ${JSON.stringify(config)}`);
1448
+ }
1449
+ }
1450
+ async deviceLogs(device) {
1451
+ if (this.platform.debugMode) {
1452
+ this.deviceLogging = this.accessory.context.logging = 'debugMode';
1453
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Debug Mode Logging: ${this.deviceLogging}`);
1454
+ }
1455
+ else if (device.logging) {
1456
+ this.deviceLogging = this.accessory.context.logging = device.logging;
1457
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config Logging: ${this.deviceLogging}`);
1458
+ }
1459
+ else if (this.platform.config.options?.logging) {
1460
+ this.deviceLogging = this.accessory.context.logging = this.platform.config.options?.logging;
1461
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Platform Config Logging: ${this.deviceLogging}`);
1462
+ }
1463
+ else {
1464
+ this.deviceLogging = this.accessory.context.logging = 'standard';
1465
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Logging Not Set, Using: ${this.deviceLogging}`);
1466
+ }
1467
+ }
1468
+ /**
1469
+ * Logging for Device
1470
+ */
1471
+ infoLog(...log) {
1472
+ if (this.enablingDeviceLogging()) {
1473
+ this.platform.log.info(String(...log));
1474
+ }
1475
+ }
1476
+ warnLog(...log) {
1477
+ if (this.enablingDeviceLogging()) {
1478
+ this.platform.log.warn(String(...log));
1479
+ }
1480
+ }
1481
+ debugWarnLog(...log) {
1482
+ if (this.enablingDeviceLogging()) {
1483
+ if (this.deviceLogging?.includes('debug')) {
1484
+ this.platform.log.warn('[DEBUG]', String(...log));
1485
+ }
1486
+ }
1487
+ }
1488
+ errorLog(...log) {
1489
+ if (this.enablingDeviceLogging()) {
1490
+ this.platform.log.error(String(...log));
1491
+ }
1492
+ }
1493
+ debugErrorLog(...log) {
1494
+ if (this.enablingDeviceLogging()) {
1495
+ if (this.deviceLogging?.includes('debug')) {
1496
+ this.platform.log.error('[DEBUG]', String(...log));
1497
+ }
1498
+ }
1499
+ }
1500
+ debugLog(...log) {
1501
+ if (this.enablingDeviceLogging()) {
1502
+ if (this.deviceLogging === 'debug') {
1503
+ this.platform.log.info('[DEBUG]', String(...log));
1504
+ }
1505
+ else {
1506
+ this.platform.log.debug(String(...log));
1507
+ }
1508
+ }
1509
+ }
1510
+ enablingDeviceLogging() {
1511
+ return this.deviceLogging.includes('debug') || this.deviceLogging === 'standard';
1512
+ }
1513
+ }
1514
+ //# sourceMappingURL=bot-old.js.map