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