@switchbot/homebridge-switchbot 4.2.0 → 4.3.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,733 @@
1
+ /* Copyright(C) 2021-2024, donavanbecker (https://github.com/donavanbecker). All rights reserved.
2
+ *
3
+ * bot.ts: @switchbot/homebridge-switchbot.
4
+ */
5
+ import type { CharacteristicValue, PlatformAccessory, Service } from 'homebridge'
6
+ import type { bodyChange, device, relaySwitch1Context, relaySwitch1PMContext, relaySwitch1PMServiceData, relaySwitch1PMStatus, relaySwitch1ServiceData, relaySwitch1Status, SwitchBotBLE, SwitchbotDevice, WoRelaySwitch1, WoRelaySwitch1PM } from 'node-switchbot'
7
+
8
+ import type { SwitchBotPlatform } from '../platform.js'
9
+ import type { devicesConfig, relaySwitch1Config, relaySwitch1PMConfig } from '../settings.js'
10
+
11
+ /*
12
+ * For Testing Locally:
13
+ * import { SwitchBotBLEModel, SwitchBotBLEModelName } from '/Users/Shared/GitHub/OpenWonderLabs/node-switchbot/dist/index.js';
14
+ */
15
+ import { SwitchBotBLEModel, SwitchBotBLEModelName } from 'node-switchbot'
16
+ import { debounceTime, interval, skipWhile, Subject, take, tap } from 'rxjs'
17
+
18
+ import { formatDeviceIdAsMac } from '../utils.js'
19
+ import { deviceBase } from './device.js'
20
+
21
+ /**
22
+ * Platform Accessory
23
+ * An instance of this class is created for each accessory your platform registers
24
+ * Each accessory may expose multiple services of different service types.
25
+ */
26
+ export class RelaySwitch extends deviceBase {
27
+ // Services
28
+ private Switch?: {
29
+ Name: CharacteristicValue
30
+ Service: Service
31
+ }
32
+
33
+ private GarageDoor?: {
34
+ Name: CharacteristicValue
35
+ Service: Service
36
+ }
37
+
38
+ private Door?: {
39
+ Name: CharacteristicValue
40
+ Service: Service
41
+ }
42
+
43
+ private Window?: {
44
+ Name: CharacteristicValue
45
+ Service: Service
46
+ }
47
+
48
+ private WindowCovering?: {
49
+ Name: CharacteristicValue
50
+ Service: Service
51
+ }
52
+
53
+ private LockMechanism?: {
54
+ Name: CharacteristicValue
55
+ Service: Service
56
+ }
57
+
58
+ private Faucet?: {
59
+ Name: CharacteristicValue
60
+ Service: Service
61
+ }
62
+
63
+ private Fan?: {
64
+ Name: CharacteristicValue
65
+ Service: Service
66
+ }
67
+
68
+ private StatefulProgrammableSwitch?: {
69
+ Name: CharacteristicValue
70
+ Service: Service
71
+ }
72
+
73
+ private Outlet?: {
74
+ Name: CharacteristicValue
75
+ Service: Service
76
+ }
77
+
78
+ On!: boolean
79
+
80
+ // OpenAPI
81
+ deviceStatus!: relaySwitch1Status | relaySwitch1PMStatus
82
+
83
+ // Webhook
84
+ webhookContext!: relaySwitch1Context | relaySwitch1PMContext
85
+
86
+ // BLE
87
+ serviceData!: relaySwitch1ServiceData | relaySwitch1PMServiceData
88
+
89
+ // Config
90
+ allowPush?: boolean
91
+ relaySwitchDeviceType!: string
92
+
93
+ // Updates
94
+ relaySwitchUpdateInProgress!: boolean
95
+ doRelaySwitchUpdate!: Subject<void>
96
+
97
+ /**
98
+ * Constructs a new instance of the RelaySwitch device.
99
+ *
100
+ * @param {SwitchBotPlatform} platform - The platform instance.
101
+ * @param {PlatformAccessory} accessory - The platform accessory.
102
+ * @param {device & devicesConfig} device - The device configuration.
103
+ *
104
+ * Initializes the RelaySwitch device, sets up the battery service, maps the device type to the appropriate HomeKit service,
105
+ * removes unnecessary services, retrieves initial values, registers event handlers, and starts update intervals.
106
+ *
107
+ * @constructor
108
+ */
109
+ constructor(
110
+ readonly platform: SwitchBotPlatform,
111
+ accessory: PlatformAccessory,
112
+ device: device & devicesConfig,
113
+ ) {
114
+ super(platform, accessory, device)
115
+
116
+ this.getRelaySwitchConfigSettings(device)
117
+
118
+ // this is subject we use to track when we need to POST changes to the SwitchBot API
119
+ this.doRelaySwitchUpdate = new Subject()
120
+ this.relaySwitchUpdateInProgress = false
121
+
122
+ /**
123
+ * A mapping of device types to their corresponding HomeKit categories, services, and characteristics.
124
+ *
125
+ * Each key represents a device type and maps to an object containing:
126
+ * - `category`: The HomeKit category for the device.
127
+ * - `service`: The HomeKit service associated with the device.
128
+ * - `characteristic`: The HomeKit characteristic for the device.
129
+ */
130
+ const deviceTypeMap: { [key: string]: { category: number, service: any, characteristic: any } } = {
131
+ switch: { category: this.hap.Categories.SWITCH, service: this.hap.Service.Switch, characteristic: this.hap.Characteristic.On },
132
+ garagedoor: { category: this.hap.Categories.GARAGE_DOOR_OPENER, service: this.hap.Service.GarageDoorOpener, characteristic: this.hap.Characteristic.TargetDoorState },
133
+ door: { category: this.hap.Categories.DOOR, service: this.hap.Service.Door, characteristic: this.hap.Characteristic.TargetPosition },
134
+ window: { category: this.hap.Categories.WINDOW, service: this.hap.Service.Window, characteristic: this.hap.Characteristic.TargetPosition },
135
+ windowcovering: { category: this.hap.Categories.WINDOW_COVERING, service: this.hap.Service.WindowCovering, characteristic: this.hap.Characteristic.TargetPosition },
136
+ lock: { category: this.hap.Categories.DOOR_LOCK, service: this.hap.Service.LockMechanism, characteristic: this.hap.Characteristic.LockTargetState },
137
+ faucet: { category: this.hap.Categories.FAUCET, service: this.hap.Service.Faucet, characteristic: this.hap.Characteristic.Active },
138
+ fan: { category: this.hap.Categories.FAN, service: this.hap.Service.Fanv2, characteristic: this.hap.Characteristic.Active },
139
+ stateful: { category: this.hap.Categories.PROGRAMMABLE_SWITCH, service: this.hap.Service.StatefulProgrammableSwitch, characteristic: this.hap.Characteristic.ProgrammableSwitchOutputState },
140
+ outlet: { category: this.hap.Categories.OUTLET, service: this.hap.Service.Outlet, characteristic: this.hap.Characteristic.On },
141
+ }
142
+
143
+ /**
144
+ * The type of the device, determined by mapping the relaySwitchDeviceType to a value in the deviceTypeMap.
145
+ */
146
+ const deviceType = deviceTypeMap[this.relaySwitchDeviceType]
147
+
148
+ if (deviceType) {
149
+ // Set category
150
+ accessory.category = deviceType.category
151
+ // Initialize Service
152
+ const contextKey = this.relaySwitchDeviceType.charAt(0).toUpperCase() + this.relaySwitchDeviceType.slice(1)
153
+ accessory.context[contextKey] = accessory.context[contextKey] ?? {}
154
+ this[this.relaySwitchDeviceType.charAt(0).toUpperCase() + this.relaySwitchDeviceType.slice(1)] = {
155
+ Name: accessory.displayName,
156
+ Service: accessory.getService(deviceType.service) ?? accessory.addService(deviceType.service) as Service,
157
+ }
158
+ accessory.context[contextKey] = this[this.relaySwitchDeviceType.charAt(0).toUpperCase() + this.relaySwitchDeviceType.slice(1)] as object
159
+ this.debugLog(`Displaying as ${contextKey}`)
160
+ // Initialize Characteristics
161
+ this[this.relaySwitchDeviceType.charAt(0).toUpperCase() + this.relaySwitchDeviceType.slice(1)].Service.setCharacteristic(this.hap.Characteristic.Name, this[this.relaySwitchDeviceType.charAt(0).toUpperCase() + this.relaySwitchDeviceType.slice(1)].Name).getCharacteristic(deviceType.characteristic).onSet(this.OnSet.bind(this))
162
+ } else {
163
+ this.errorLog('Device Type not set')
164
+ }
165
+
166
+ /**
167
+ * An array of service removal functions that should be executed based on the current state of the device.
168
+ * Each element in the array is a function that removes a specific service if the corresponding condition is met.
169
+ */
170
+ const servicesToRemove = [
171
+ !this.StatefulProgrammableSwitch && this.removeStatefulProgrammableSwitchService,
172
+ !this.Outlet && this.removeOutletService,
173
+ !this.Window && this.removeWindowService,
174
+ !this.GarageDoor && this.removeGarageDoorService,
175
+ this.WindowCovering && this.removeWindowCoveringService,
176
+ !this.Switch && this.removeSwitchService,
177
+ !this.Faucet && this.removeFaucetService,
178
+ !this.Door && this.removeDoorService,
179
+ !this.LockMechanism && this.removeLockService,
180
+ !this.Fan && this.removeFanService,
181
+ ].filter(Boolean)
182
+
183
+ for (const removeService of servicesToRemove) {
184
+ if (typeof removeService === 'function') {
185
+ removeService.call(this, accessory)
186
+ }
187
+ }
188
+
189
+ // Retrieve initial values and updateHomekit
190
+ try {
191
+ this.debugLog('Retrieve initial values and update Homekit')
192
+ this.refreshStatus()
193
+ } catch (e: any) {
194
+ this.errorLog(`failed to retrieve initial values and update Homekit, Error: ${e.message ?? e}`)
195
+ }
196
+
197
+ // regisiter webhook event handler if enabled
198
+ try {
199
+ this.debugLog('Registering Webhook Event Handler')
200
+ this.registerWebhook()
201
+ } catch (e: any) {
202
+ this.errorLog(`failed to registerWebhook, Error: ${e.message ?? e}`)
203
+ }
204
+
205
+ // regisiter platform BLE event handler if enabled
206
+ try {
207
+ this.debugLog('Registering Platform BLE Event Handler')
208
+ this.registerPlatformBLE()
209
+ } catch (e: any) {
210
+ this.errorLog(`failed to registerPlatformBLE, Error: ${e.message ?? e}`)
211
+ }
212
+
213
+ // Start an update interval
214
+ interval(this.deviceRefreshRate * 1000)
215
+ .pipe(skipWhile(() => this.relaySwitchUpdateInProgress))
216
+ .subscribe(async () => {
217
+ await this.refreshStatus()
218
+ })
219
+
220
+ // Watch for RelaySwitch change events
221
+ // We put in a debounce of 1000ms so we don't make duplicate calls
222
+ this.doRelaySwitchUpdate
223
+ .pipe(
224
+ tap(() => {
225
+ this.relaySwitchUpdateInProgress = true
226
+ }),
227
+ debounceTime(this.devicePushRate * 1000),
228
+ )
229
+ .subscribe(async () => {
230
+ try {
231
+ await this.pushChanges()
232
+ } catch (e: any) {
233
+ await this.apiError(e)
234
+ this.errorLog(`failed pushChanges with ${device.connectionType} Connection, Error Message: ${JSON.stringify(e.message)}`)
235
+ }
236
+ this.relaySwitchUpdateInProgress = false
237
+ })
238
+ }
239
+
240
+ /**
241
+ * Parse the device status from the SwitchBotBLE API
242
+ */
243
+ async BLEparseStatus(): Promise<void> {
244
+ this.debugLog('BLEparseStatus')
245
+ this.debugLog(`(power, battery, deviceMode) = BLE:(${this.serviceData.state}), current:(${this.accessory.context.On})`)
246
+
247
+ // BLEmode (true if Switch Mode) | (false if Press Mode)
248
+ this.On = this.serviceData.mode ? this.serviceData.state : false
249
+ const mode = this.serviceData.mode ? 'Switch' : 'Press'
250
+ this.debugLog(`${mode} Mode, On: ${this.On}`)
251
+ this.accessory.context.On = this.On
252
+ }
253
+
254
+ /**
255
+ * Parse the device status from the SwitchBot OpenAPI
256
+ */
257
+ async openAPIparseStatus(): Promise<void> {
258
+ this.debugLog('openAPIparseStatus')
259
+ this.debugLog(`(power, battery, deviceMode) = API:(${this.deviceStatus.switchStatus}), current:(${this.accessory.context.On})`)
260
+
261
+ // On
262
+ this.On = this.deviceStatus.switchStatus !== 0
263
+ this.debugLog(`On: ${this.On}`)
264
+ this.accessory.context.On = this.On
265
+
266
+ // Firmware Version
267
+ if (this.deviceStatus.version) {
268
+ const version = this.deviceStatus.version as string
269
+ this.debugLog(`Firmware Version: ${version.replace(/^V|-.*$/g, '')}`)
270
+ const deviceVersion = version.replace(/^V|-.*$/g, '') ?? '0.0.0'
271
+ this.accessory
272
+ .getService(this.hap.Service.AccessoryInformation)!
273
+ .setCharacteristic(this.hap.Characteristic.HardwareRevision, deviceVersion)
274
+ .setCharacteristic(this.hap.Characteristic.FirmwareRevision, deviceVersion)
275
+ .getCharacteristic(this.hap.Characteristic.FirmwareRevision)
276
+ .updateValue(deviceVersion)
277
+ this.accessory.context.version = deviceVersion
278
+ this.debugLog(`version: ${deviceVersion}`)
279
+ }
280
+ }
281
+
282
+ async parseStatusWebhook(): Promise<void> {
283
+ this.debugLog('parseStatusWebhook')
284
+ this.debugLog(`(power, battery, deviceMode) = Webhook:(${this.webhookContext.switchStatus}), current:(${this.On})`)
285
+
286
+ // On
287
+ this.On = this.webhookContext.switchStatus !== 0
288
+ this.debugLog(`On: ${this.On}`)
289
+ }
290
+
291
+ /**
292
+ * Asks the SwitchBot API for the latest device information
293
+ */
294
+ async refreshStatus(): Promise<void> {
295
+ if (!this.device.enableCloudService && this.OpenAPI) {
296
+ this.errorLog(`refreshStatus enableCloudService: ${this.device.enableCloudService}`)
297
+ } else if (this.BLE) {
298
+ await this.BLERefreshStatus()
299
+ } else if (this.OpenAPI && this.platform.config.credentials?.token) {
300
+ await this.openAPIRefreshStatus()
301
+ } else {
302
+ await this.offlineOff()
303
+ this.debugWarnLog(`Connection Type: ${this.device.connectionType}, refreshStatus will not happen.`)
304
+ }
305
+ }
306
+
307
+ async BLERefreshStatus(): Promise<void> {
308
+ this.debugLog('BLERefreshStatus')
309
+ const switchBotBLE = await this.switchbotBLE()
310
+ if (switchBotBLE === undefined) {
311
+ await this.BLERefreshConnection(switchBotBLE)
312
+ } else {
313
+ // Start to monitor advertisement packets
314
+ (async () => {
315
+ // Start to monitor advertisement packets
316
+ const serviceData = await this.monitorAdvertisementPackets(switchBotBLE) as relaySwitch1ServiceData | relaySwitch1PMServiceData
317
+ // Update HomeKit
318
+ if ((serviceData.model === SwitchBotBLEModel.RelaySwitch1PM && serviceData.modelName === SwitchBotBLEModelName.RelaySwitch1PM) ?? (serviceData.model === SwitchBotBLEModel.RelaySwitch1 && serviceData.modelName === SwitchBotBLEModelName.RelaySwitch1)) {
319
+ this.serviceData = serviceData
320
+ if (serviceData !== undefined || serviceData !== null) {
321
+ await this.BLEparseStatus()
322
+ await this.updateHomeKitCharacteristics()
323
+ } else {
324
+ this.errorLog(`serviceData is either undefined or null, serviceData: ${JSON.stringify(serviceData)}`)
325
+ await this.BLERefreshConnection(switchBotBLE)
326
+ }
327
+ } else {
328
+ this.errorLog(`failed to get serviceData, serviceData: ${JSON.stringify(serviceData)}`)
329
+ await this.BLERefreshConnection(switchBotBLE)
330
+ }
331
+ })()
332
+ }
333
+ }
334
+
335
+ async registerPlatformBLE(): Promise<void> {
336
+ this.debugLog('registerPlatformBLE')
337
+ if (this.config.options?.BLE && !this.device.disablePlatformBLE) {
338
+ this.debugLog('is listening to Platform BLE.')
339
+ try {
340
+ const formattedDeviceId = formatDeviceIdAsMac(this.device.deviceId)
341
+ this.device.bleMac = formattedDeviceId
342
+ this.debugLog(`bleMac: ${this.device.bleMac}`)
343
+ this.platform.bleEventHandler[this.device.bleMac] = async (context: relaySwitch1ServiceData | relaySwitch1PMServiceData) => {
344
+ try {
345
+ this.serviceData = context
346
+ if (context !== undefined || context !== null) {
347
+ this.debugLog(`received BLE: ${JSON.stringify(context)}`)
348
+ await this.BLEparseStatus()
349
+ await this.updateHomeKitCharacteristics()
350
+ } else {
351
+ this.errorLog(`context is either undefined or null, context: ${JSON.stringify(context)}`)
352
+ await this.BLERefreshConnection(context)
353
+ }
354
+ } catch (e: any) {
355
+ this.errorLog(`failed to handle BLE. Received: ${JSON.stringify(context)} Error: ${e.message ?? e}`)
356
+ }
357
+ }
358
+ } catch (error) {
359
+ this.errorLog(`failed to format device ID as MAC, Error: ${error}`)
360
+ }
361
+ } else {
362
+ this.debugLog('is not listening to Platform BLE')
363
+ }
364
+ }
365
+
366
+ async openAPIRefreshStatus(): Promise<void> {
367
+ this.debugLog('openAPIRefreshStatus')
368
+ try {
369
+ const response = await this.deviceRefreshStatus()
370
+ const deviceStatus: any = response.body
371
+ this.debugLog(`statusCode: ${deviceStatus.statusCode}, deviceStatus: ${JSON.stringify(deviceStatus)}`)
372
+ if (await this.successfulStatusCodes(deviceStatus)) {
373
+ this.debugSuccessLog(`statusCode: ${deviceStatus.statusCode}, deviceStatus: ${JSON.stringify(deviceStatus)}`)
374
+ this.deviceStatus = deviceStatus.body
375
+ await this.openAPIparseStatus()
376
+ await this.updateHomeKitCharacteristics()
377
+ } else {
378
+ this.debugWarnLog(`statusCode: ${deviceStatus.statusCode}, deviceStatus: ${JSON.stringify(deviceStatus)}`)
379
+ }
380
+ } catch (e: any) {
381
+ await this.apiError(e)
382
+ this.errorLog(`failed openAPIRefreshStatus with ${this.device.connectionType} Connection, Error Message: ${JSON.stringify(e.message)}`)
383
+ }
384
+ }
385
+
386
+ async registerWebhook() {
387
+ if (this.device.webhook) {
388
+ this.debugLog('is listening webhook.')
389
+ this.platform.webhookEventHandler[this.device.deviceId] = async (context: relaySwitch1Context | relaySwitch1PMContext) => {
390
+ try {
391
+ this.webhookContext = context
392
+ if (context !== undefined || context !== null) {
393
+ this.debugLog(`received Webhook: ${JSON.stringify(context)}`)
394
+ await this.parseStatusWebhook()
395
+ await this.updateHomeKitCharacteristics()
396
+ } else {
397
+ this.errorLog(`context is either undefined or null, context: ${JSON.stringify(context)}`)
398
+ }
399
+ } catch (e: any) {
400
+ this.errorLog(`failed to handle webhook. Received: ${JSON.stringify(context)} Error: ${e.message ?? e}`)
401
+ }
402
+ }
403
+ } else {
404
+ this.debugLog('is not listening webhook.')
405
+ }
406
+ }
407
+
408
+ /**
409
+ * Pushes the requested changes to the SwitchBot API
410
+ * deviceType commandType Command command parameter Description
411
+ * RelaySwitch "command" "turnOff" "default" = set to OFF state
412
+ * RelaySwitch "command" "turnOn" "default" = set to ON state
413
+ */
414
+ async pushChanges(): Promise<void> {
415
+ if (!this.device.enableCloudService && this.OpenAPI) {
416
+ this.errorLog(`pushChanges enableCloudService: ${this.device.enableCloudService}`)
417
+ } else if (this.BLE) {
418
+ await this.BLEpushChanges()
419
+ } else if (this.OpenAPI && this.platform.config.credentials?.token) {
420
+ await this.openAPIpushChanges()
421
+ } else {
422
+ await this.offlineOff()
423
+ this.debugWarnLog(`Connection Type: ${this.device.connectionType}, pushChanges will not happen.`)
424
+ }
425
+ // Refresh the status from the API
426
+ interval(15000)
427
+ .pipe(skipWhile(() => this.relaySwitchUpdateInProgress))
428
+ .pipe(take(1))
429
+ .subscribe(async () => {
430
+ await this.refreshStatus()
431
+ })
432
+ }
433
+
434
+ async BLEpushChanges(): Promise<void> {
435
+ this.debugLog('BLEpushChanges')
436
+ if ((this.On !== this.accessory.context.On) || this.allowPush) {
437
+ this.debugLog(`BLEpushChanges On: ${this.On} OnCached: ${this.accessory.context.On}`)
438
+ const switchBotBLE = this.platform.switchBotBLE
439
+ try {
440
+ const formattedDeviceId = formatDeviceIdAsMac(this.device.deviceId)
441
+ this.device.bleMac = formattedDeviceId
442
+ this.debugLog(`bleMac: ${this.device.bleMac}`)
443
+ switchBotBLE
444
+ .discover({ model: this.device.bleModel, quick: true, id: this.device.bleMac })
445
+ .then(async (device_list: SwitchbotDevice[]) => {
446
+ const deviceList = device_list as WoRelaySwitch1[] | WoRelaySwitch1PM[]
447
+ this.infoLog(`On: ${this.On}`)
448
+ this.warnLog(`device_list: ${JSON.stringify(device_list)}`)
449
+ return await this.retryBLE({
450
+ max: this.maxRetryBLE(),
451
+ fn: async () => {
452
+ if (deviceList.length > 0) {
453
+ if (this.On) {
454
+ return await deviceList[0].turnOn()
455
+ } else {
456
+ return await deviceList[0].turnOff()
457
+ }
458
+ } else {
459
+ throw new Error('No device found')
460
+ }
461
+ },
462
+ })
463
+ })
464
+ .then(async () => {
465
+ this.successLog(`On: ${this.On} sent over SwitchBot BLE, sent successfully`)
466
+ await this.updateHomeKitCharacteristics()
467
+ })
468
+ .catch(async (e: any) => {
469
+ await this.apiError(e)
470
+ this.errorLog(`failed BLEpushChanges with ${this.device.connectionType} Connection, Error Message: ${JSON.stringify(e.message)}`)
471
+ await this.BLEPushConnection()
472
+ })
473
+ } catch (error) {
474
+ this.errorLog(`failed to format device ID as MAC, Error: ${error}`)
475
+ }
476
+ } else {
477
+ this.debugLog(`No Changes (BLEpushChanges), On: ${this.On} OnCached: ${this.accessory.context.On}`)
478
+ }
479
+ }
480
+
481
+ async openAPIpushChanges(): Promise<void> {
482
+ this.debugLog('openAPIpushChanges')
483
+ if ((this.On !== this.accessory.context.On) || this.allowPush) {
484
+ const bodyChange: bodyChange = {
485
+ command: this.On ? 'turnOn' : 'turnOff',
486
+ parameter: 'default',
487
+ commandType: 'command',
488
+ }
489
+ this.debugLog(`SwitchBot OpenAPI bodyChange: ${JSON.stringify(bodyChange)}`)
490
+ try {
491
+ const response = await this.pushChangeRequest(bodyChange)
492
+ const deviceStatus: any = response.body
493
+ this.debugLog(`statusCode: ${deviceStatus.statusCode}, deviceStatus: ${JSON.stringify(deviceStatus)}`)
494
+ if (await this.successfulStatusCodes(deviceStatus)) {
495
+ this.debugSuccessLog(`statusCode: ${deviceStatus.statusCode}, deviceStatus: ${JSON.stringify(deviceStatus)}`)
496
+ await this.updateHomeKitCharacteristics()
497
+ } else {
498
+ await this.statusCode(deviceStatus.statusCode)
499
+ }
500
+ } catch (e: any) {
501
+ await this.apiError(e)
502
+ this.errorLog(`failed openAPIpushChanges with ${this.device.connectionType} Connection, Error Message: ${JSON.stringify(e.message)}`)
503
+ }
504
+ } else {
505
+ this.debugLog(`No Changes (openAPIpushChanges), On: ${this.On} OnCached: ${this.accessory.context.On}`)
506
+ }
507
+ }
508
+
509
+ /**
510
+ * Handle requests to set the "On" characteristic
511
+ */
512
+ async OnSet(value: CharacteristicValue): Promise<void> {
513
+ this.debugLog(`value: ${value}`)
514
+ const deviceTypeActions: { [key: string]: () => void } = {
515
+ switch: () => this.On = value !== false,
516
+ garagedoor: () => this.On = value !== this.hap.Characteristic.TargetDoorState.CLOSED,
517
+ door: () => this.On = value !== 0,
518
+ window: () => this.On = value !== 0,
519
+ windowcovering: () => this.On = value !== 0,
520
+ lock: () => this.On = value !== this.hap.Characteristic.LockTargetState.SECURED,
521
+ faucet: () => this.On = value !== this.hap.Characteristic.Active.INACTIVE,
522
+ fan: () => this.On = value !== 0,
523
+ stateful: () => this.On = value !== 0,
524
+ default: () => this.On = value !== false,
525
+ }
526
+ const action = deviceTypeActions[this.relaySwitchDeviceType] || deviceTypeActions.default
527
+ action()
528
+ this.doRelaySwitchUpdate.next()
529
+ }
530
+
531
+ /**
532
+ * Updates the status for each of the HomeKit Characteristics
533
+ */
534
+ async updateHomeKitCharacteristics(): Promise<void> {
535
+ this.debugLog('updateHomeKitCharacteristics')
536
+ // State
537
+ const updateCharacteristic = async (service: Service, characteristic: any, value: any, logMessage: string) => {
538
+ service.updateCharacteristic(characteristic, value)
539
+ this.debugLog(logMessage)
540
+ }
541
+
542
+ const stateActions: { [key: string]: () => Promise<void> } = {
543
+ switch: async () => this.Switch && await updateCharacteristic(this.Switch.Service, this.hap.Characteristic.On, this.On, `updateCharacteristic On: ${this.On}`),
544
+ garagedoor: async () => {
545
+ if (this.GarageDoor) {
546
+ const targetState = this.On ? this.hap.Characteristic.TargetDoorState.OPEN : this.hap.Characteristic.TargetDoorState.CLOSED
547
+ const currentState = this.On ? this.hap.Characteristic.CurrentDoorState.OPEN : this.hap.Characteristic.CurrentDoorState.CLOSED
548
+ await updateCharacteristic(this.GarageDoor.Service, this.hap.Characteristic.TargetDoorState, targetState, `updateCharacteristic TargetDoorState: ${targetState}, CurrentDoorState: ${currentState} (${this.On})`)
549
+ await updateCharacteristic(this.GarageDoor.Service, this.hap.Characteristic.CurrentDoorState, currentState, '')
550
+ }
551
+ },
552
+ door: async () => {
553
+ if (this.Door) {
554
+ const position = this.On ? 100 : 0
555
+ await updateCharacteristic(this.Door.Service, this.hap.Characteristic.TargetPosition, position, `updateCharacteristic TargetPosition: ${position}, CurrentPosition: ${position} (${this.On})`)
556
+ await updateCharacteristic(this.Door.Service, this.hap.Characteristic.CurrentPosition, position, '')
557
+ await updateCharacteristic(this.Door.Service, this.hap.Characteristic.PositionState, this.hap.Characteristic.PositionState.STOPPED, '')
558
+ }
559
+ },
560
+ window: async () => {
561
+ if (this.Window) {
562
+ const position = this.On ? 100 : 0
563
+ await updateCharacteristic(this.Window.Service, this.hap.Characteristic.TargetPosition, position, `updateCharacteristic TargetPosition: ${position}, CurrentPosition: ${position} (${this.On})`)
564
+ await updateCharacteristic(this.Window.Service, this.hap.Characteristic.CurrentPosition, position, '')
565
+ await updateCharacteristic(this.Window.Service, this.hap.Characteristic.PositionState, this.hap.Characteristic.PositionState.STOPPED, '')
566
+ }
567
+ },
568
+ windowcovering: async () => {
569
+ if (this.WindowCovering) {
570
+ const position = this.On ? 100 : 0
571
+ await updateCharacteristic(this.WindowCovering.Service, this.hap.Characteristic.TargetPosition, position, `updateCharacteristic TargetPosition: ${position}, CurrentPosition: ${position} (${this.On})`)
572
+ await updateCharacteristic(this.WindowCovering.Service, this.hap.Characteristic.CurrentPosition, position, '')
573
+ await updateCharacteristic(this.WindowCovering.Service, this.hap.Characteristic.PositionState, this.hap.Characteristic.PositionState.STOPPED, '')
574
+ }
575
+ },
576
+ lock: async () => {
577
+ if (this.LockMechanism) {
578
+ const targetState = this.On ? this.hap.Characteristic.LockTargetState.UNSECURED : this.hap.Characteristic.LockTargetState.SECURED
579
+ const currentState = this.On ? this.hap.Characteristic.LockCurrentState.UNSECURED : this.hap.Characteristic.LockCurrentState.SECURED
580
+ await updateCharacteristic(this.LockMechanism.Service, this.hap.Characteristic.LockTargetState, targetState, `updateCharacteristic LockTargetState: ${targetState}, LockCurrentState: ${currentState} (${this.On})`)
581
+ await updateCharacteristic(this.LockMechanism.Service, this.hap.Characteristic.LockCurrentState, currentState, '')
582
+ }
583
+ },
584
+ faucet: async () => this.Faucet && await updateCharacteristic(this.Faucet.Service, this.hap.Characteristic.Active, this.On ? this.hap.Characteristic.Active.ACTIVE : this.hap.Characteristic.Active.INACTIVE, `updateCharacteristic Active: ${this.On}`),
585
+ fan: async () => this.Fan && await updateCharacteristic(this.Fan.Service, this.hap.Characteristic.Active, this.On ? this.hap.Characteristic.Active.ACTIVE : this.hap.Characteristic.Active.INACTIVE, `updateCharacteristic Active: ${this.On}`),
586
+ stateful: async () => {
587
+ if (this.StatefulProgrammableSwitch) {
588
+ await updateCharacteristic(this.StatefulProgrammableSwitch.Service, this.hap.Characteristic.ProgrammableSwitchEvent, this.hap.Characteristic.ProgrammableSwitchEvent.SINGLE_PRESS, `updateCharacteristic ProgrammableSwitchEvent: SINGLE_PRESS (${this.On})`)
589
+ await updateCharacteristic(this.StatefulProgrammableSwitch.Service, this.hap.Characteristic.ProgrammableSwitchOutputState, this.On ? 1 : 0, `updateCharacteristic ProgrammableSwitchOutputState: ${this.On ? 1 : 0}`)
590
+ }
591
+ },
592
+ outlet: async () => this.Outlet && await updateCharacteristic(this.Outlet.Service, this.hap.Characteristic.On, this.On, `updateCharacteristic On: ${this.On}`),
593
+ default: async () => this.errorLog(`relaySwitchDeviceType: ${this.relaySwitchDeviceType}, On: ${this.On}`),
594
+ }
595
+
596
+ const action = stateActions[this.relaySwitchDeviceType] || stateActions.default
597
+ await action()
598
+ }
599
+
600
+ async removeService(accessory: PlatformAccessory, serviceType: string, serviceName: string): Promise<void> {
601
+ const contextKey = serviceName.charAt(0).toUpperCase() + serviceName.slice(1)
602
+ accessory.context[contextKey] = accessory.context[contextKey] ?? {}
603
+ this[contextKey] = {
604
+ Name: accessory.context[contextKey].Name ?? accessory.displayName,
605
+ Service: accessory.getService(this.hap.Service[serviceType]) as Service,
606
+ }
607
+ accessory.context[contextKey] = this[contextKey] as object
608
+ this.debugWarnLog(`Removing any leftover ${contextKey} Service`)
609
+ accessory.removeService(this[contextKey].Service)
610
+ }
611
+
612
+ async removeOutletService(accessory: PlatformAccessory): Promise<void> {
613
+ await this.removeService(accessory, 'Outlet', 'outlet')
614
+ }
615
+
616
+ async removeGarageDoorService(accessory: PlatformAccessory): Promise<void> {
617
+ await this.removeService(accessory, 'GarageDoorOpener', 'garageDoor')
618
+ }
619
+
620
+ async removeDoorService(accessory: PlatformAccessory): Promise<void> {
621
+ await this.removeService(accessory, 'Door', 'door')
622
+ }
623
+
624
+ async removeLockService(accessory: PlatformAccessory): Promise<void> {
625
+ await this.removeService(accessory, 'LockMechanism', 'lockMechanism')
626
+ }
627
+
628
+ async removeFaucetService(accessory: PlatformAccessory): Promise<void> {
629
+ await this.removeService(accessory, 'Valve', 'faucet')
630
+ }
631
+
632
+ async removeFanService(accessory: PlatformAccessory): Promise<void> {
633
+ await this.removeService(accessory, 'Fan', 'fan')
634
+ }
635
+
636
+ async removeWindowService(accessory: PlatformAccessory): Promise<void> {
637
+ await this.removeService(accessory, 'Window', 'window')
638
+ }
639
+
640
+ async removeWindowCoveringService(accessory: PlatformAccessory): Promise<void> {
641
+ await this.removeService(accessory, 'WindowCovering', 'windowCovering')
642
+ }
643
+
644
+ async removeStatefulProgrammableSwitchService(accessory: PlatformAccessory): Promise<void> {
645
+ await this.removeService(accessory, 'StatefulProgrammableSwitch', 'statefulProgrammableSwitch')
646
+ }
647
+
648
+ async removeSwitchService(accessory: PlatformAccessory): Promise<void> {
649
+ await this.removeService(accessory, 'Switch', 'switch')
650
+ }
651
+
652
+ async getRelaySwitchConfigSettings(device: device & devicesConfig) {
653
+ // RelaySwitch Device Type
654
+ this.relaySwitchDeviceType = (device as relaySwitch1Config | relaySwitch1PMConfig).type ?? 'Outlet'
655
+ const relaySwitchDeviceType = (device as relaySwitch1Config | relaySwitch1PMConfig).type ? 'Device Config' : 'Default'
656
+ this.debugWarnLog(`Use ${relaySwitchDeviceType} Device Type: ${this.relaySwitchDeviceType}`)
657
+ // RelaySwitch Allow Push
658
+ this.allowPush = (device as relaySwitch1Config | relaySwitch1PMConfig).allowPush ?? false
659
+ const allowPush = (device as relaySwitch1Config | relaySwitch1PMConfig).allowPush
660
+ ? `Using Allow Push: ${this.allowPush}`
661
+ : `No Allow Push Set, Using default Allow Push: ${this.allowPush}`
662
+ this.debugWarnLog(allowPush)
663
+ }
664
+
665
+ async BLEPushConnection() {
666
+ if (this.platform.config.credentials?.token && this.device.connectionType === 'BLE/OpenAPI') {
667
+ this.warnLog('Using OpenAPI Connection to Push Changes')
668
+ await this.openAPIpushChanges()
669
+ }
670
+ }
671
+
672
+ async BLERefreshConnection(switchbot: SwitchBotBLE): Promise<void> {
673
+ this.errorLog(`wasn't able to establish BLE Connection, node-switchbot: ${switchbot}`)
674
+ if (this.platform.config.credentials?.token && this.device.connectionType === 'BLE/OpenAPI') {
675
+ this.warnLog('Using OpenAPI Connection to Refresh Status')
676
+ await this.openAPIRefreshStatus()
677
+ }
678
+ }
679
+
680
+ async offlineOff(): Promise<void> {
681
+ if (this.device.offline) {
682
+ const updateCharacteristics = (service: Service, characteristics: { [key: string]: any }) => {
683
+ for (const [characteristic, value] of Object.entries(characteristics)) {
684
+ service.updateCharacteristic(this.hap.Characteristic[characteristic], value)
685
+ }
686
+ }
687
+
688
+ const characteristicsMap: { [key: string]: { [key: string]: any } } = {
689
+ garagedoor: { TargetDoorState: 'CLOSED', CurrentDoorState: 'CLOSED', ObstructionDetected: false },
690
+ door: { TargetPosition: 0, CurrentPosition: 0, PositionState: 'STOPPED' },
691
+ window: { TargetPosition: 0, CurrentPosition: 0, PositionState: 'STOPPED' },
692
+ windowcovering: { TargetPosition: 0, CurrentPosition: 0, PositionState: 'STOPPED' },
693
+ lock: { LockTargetState: 'SECURED', LockCurrentState: 'SECURED' },
694
+ faucet: { Active: 'INACTIVE' },
695
+ fan: { On: false },
696
+ stateful: { ProgrammableSwitchEvent: 'SINGLE_PRESS', ProgrammableSwitchOutputState: 0 },
697
+ switch: { On: false },
698
+ outlet: { On: false },
699
+ }
700
+
701
+ const service = this[this.relaySwitchDeviceType.charAt(0).toUpperCase() + this.relaySwitchDeviceType.slice(1)]?.Service
702
+ if (service) {
703
+ updateCharacteristics(service, characteristicsMap[this.relaySwitchDeviceType])
704
+ }
705
+ }
706
+ }
707
+
708
+ async apiError(e: any): Promise<void> {
709
+ const updateCharacteristics = (service: Service, characteristics: { [key: string]: any }) => {
710
+ for (const [characteristic] of Object.entries(characteristics)) {
711
+ service.updateCharacteristic(this.hap.Characteristic[characteristic], e)
712
+ }
713
+ }
714
+
715
+ const characteristicsMap: { [key: string]: { [key: string]: any } } = {
716
+ garagedoor: { TargetDoorState: e, CurrentDoorState: e, ObstructionDetected: e },
717
+ door: { TargetPosition: e, CurrentPosition: e, PositionState: e },
718
+ window: { TargetPosition: e, CurrentPosition: e, PositionState: e },
719
+ windowcovering: { TargetPosition: e, CurrentPosition: e, PositionState: e },
720
+ lock: { LockTargetState: e, LockCurrentState: e },
721
+ faucet: { Active: e },
722
+ fan: { On: e },
723
+ stateful: { ProgrammableSwitchEvent: e, ProgrammableSwitchOutputState: e },
724
+ switch: { On: e },
725
+ outlet: { On: e },
726
+ }
727
+
728
+ const service = this[this.relaySwitchDeviceType.charAt(0).toUpperCase() + this.relaySwitchDeviceType.slice(1)]?.Service
729
+ if (service) {
730
+ updateCharacteristics(service, characteristicsMap[this.relaySwitchDeviceType])
731
+ }
732
+ }
733
+ }