@switchbot/homebridge-switchbot 3.5.0-beta.0 → 3.5.0-beta.10

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 (142) hide show
  1. package/CHANGELOG.md +3 -1
  2. package/config.schema.json +27 -6
  3. package/dist/device/blindtilt.d.ts +1 -0
  4. package/dist/device/blindtilt.d.ts.map +1 -1
  5. package/dist/device/blindtilt.js +9 -0
  6. package/dist/device/blindtilt.js.map +1 -1
  7. package/dist/device/bot.d.ts +1 -0
  8. package/dist/device/bot.d.ts.map +1 -1
  9. package/dist/device/bot.js +9 -0
  10. package/dist/device/bot.js.map +1 -1
  11. package/dist/device/ceilinglight.d.ts +1 -0
  12. package/dist/device/ceilinglight.d.ts.map +1 -1
  13. package/dist/device/ceilinglight.js +13 -0
  14. package/dist/device/ceilinglight.js.map +1 -1
  15. package/dist/device/colorbulb.d.ts +1 -0
  16. package/dist/device/colorbulb.d.ts.map +1 -1
  17. package/dist/device/colorbulb.js +15 -0
  18. package/dist/device/colorbulb.js.map +1 -1
  19. package/dist/device/contact.d.ts +1 -0
  20. package/dist/device/contact.d.ts.map +1 -1
  21. package/dist/device/contact.js +5 -0
  22. package/dist/device/contact.js.map +1 -1
  23. package/dist/device/curtain.d.ts +1 -0
  24. package/dist/device/curtain.d.ts.map +1 -1
  25. package/dist/device/curtain.js +9 -0
  26. package/dist/device/curtain.js.map +1 -1
  27. package/dist/device/hub.d.ts +1 -0
  28. package/dist/device/hub.d.ts.map +1 -1
  29. package/dist/device/hub.js +5 -0
  30. package/dist/device/hub.js.map +1 -1
  31. package/dist/device/humidifier.d.ts +1 -0
  32. package/dist/device/humidifier.d.ts.map +1 -1
  33. package/dist/device/humidifier.js +14 -1
  34. package/dist/device/humidifier.js.map +1 -1
  35. package/dist/device/iosensor.d.ts +1 -0
  36. package/dist/device/iosensor.d.ts.map +1 -1
  37. package/dist/device/iosensor.js +5 -0
  38. package/dist/device/iosensor.js.map +1 -1
  39. package/dist/device/lightstrip.d.ts +1 -0
  40. package/dist/device/lightstrip.d.ts.map +1 -1
  41. package/dist/device/lightstrip.js +13 -0
  42. package/dist/device/lightstrip.js.map +1 -1
  43. package/dist/device/lock.d.ts +1 -0
  44. package/dist/device/lock.d.ts.map +1 -1
  45. package/dist/device/lock.js +9 -0
  46. package/dist/device/lock.js.map +1 -1
  47. package/dist/device/meter.d.ts +1 -0
  48. package/dist/device/meter.d.ts.map +1 -1
  49. package/dist/device/meter.js +5 -0
  50. package/dist/device/meter.js.map +1 -1
  51. package/dist/device/meterplus.d.ts +1 -0
  52. package/dist/device/meterplus.d.ts.map +1 -1
  53. package/dist/device/meterplus.js +5 -0
  54. package/dist/device/meterplus.js.map +1 -1
  55. package/dist/device/motion.d.ts +1 -0
  56. package/dist/device/motion.d.ts.map +1 -1
  57. package/dist/device/motion.js +5 -0
  58. package/dist/device/motion.js.map +1 -1
  59. package/dist/device/plug.d.ts +1 -0
  60. package/dist/device/plug.d.ts.map +1 -1
  61. package/dist/device/plug.js +9 -0
  62. package/dist/device/plug.js.map +1 -1
  63. package/dist/device/robotvacuumcleaner.d.ts +1 -0
  64. package/dist/device/robotvacuumcleaner.d.ts.map +1 -1
  65. package/dist/device/robotvacuumcleaner.js +16 -4
  66. package/dist/device/robotvacuumcleaner.js.map +1 -1
  67. package/dist/device/waterdetector.d.ts +85 -0
  68. package/dist/device/waterdetector.d.ts.map +1 -0
  69. package/dist/device/waterdetector.js +656 -0
  70. package/dist/device/waterdetector.js.map +1 -0
  71. package/dist/irdevice/airconditioner.d.ts +1 -0
  72. package/dist/irdevice/airconditioner.d.ts.map +1 -1
  73. package/dist/irdevice/airconditioner.js +6 -0
  74. package/dist/irdevice/airconditioner.js.map +1 -1
  75. package/dist/irdevice/airpurifier.d.ts +1 -0
  76. package/dist/irdevice/airpurifier.d.ts.map +1 -1
  77. package/dist/irdevice/airpurifier.js +6 -0
  78. package/dist/irdevice/airpurifier.js.map +1 -1
  79. package/dist/irdevice/camera.d.ts +1 -0
  80. package/dist/irdevice/camera.d.ts.map +1 -1
  81. package/dist/irdevice/camera.js +6 -0
  82. package/dist/irdevice/camera.js.map +1 -1
  83. package/dist/irdevice/fan.d.ts +1 -0
  84. package/dist/irdevice/fan.d.ts.map +1 -1
  85. package/dist/irdevice/fan.js +6 -0
  86. package/dist/irdevice/fan.js.map +1 -1
  87. package/dist/irdevice/light.d.ts +1 -0
  88. package/dist/irdevice/light.d.ts.map +1 -1
  89. package/dist/irdevice/light.js +6 -0
  90. package/dist/irdevice/light.js.map +1 -1
  91. package/dist/irdevice/other.d.ts +1 -0
  92. package/dist/irdevice/other.d.ts.map +1 -1
  93. package/dist/irdevice/other.js +6 -0
  94. package/dist/irdevice/other.js.map +1 -1
  95. package/dist/irdevice/tv.d.ts +1 -0
  96. package/dist/irdevice/tv.d.ts.map +1 -1
  97. package/dist/irdevice/tv.js +6 -0
  98. package/dist/irdevice/tv.js.map +1 -1
  99. package/dist/irdevice/vacuumcleaner.d.ts +1 -0
  100. package/dist/irdevice/vacuumcleaner.d.ts.map +1 -1
  101. package/dist/irdevice/vacuumcleaner.js +6 -0
  102. package/dist/irdevice/vacuumcleaner.js.map +1 -1
  103. package/dist/irdevice/waterheater.d.ts +1 -0
  104. package/dist/irdevice/waterheater.d.ts.map +1 -1
  105. package/dist/irdevice/waterheater.js +6 -0
  106. package/dist/irdevice/waterheater.js.map +1 -1
  107. package/dist/platform.d.ts +2 -0
  108. package/dist/platform.d.ts.map +1 -1
  109. package/dist/platform.js +68 -0
  110. package/dist/platform.js.map +1 -1
  111. package/dist/settings.d.ts +5 -0
  112. package/dist/settings.d.ts.map +1 -1
  113. package/dist/settings.js.map +1 -1
  114. package/package.json +14 -14
  115. package/src/device/blindtilt.ts +19 -9
  116. package/src/device/bot.ts +10 -0
  117. package/src/device/ceilinglight.ts +14 -0
  118. package/src/device/colorbulb.ts +16 -0
  119. package/src/device/contact.ts +6 -0
  120. package/src/device/curtain.ts +10 -0
  121. package/src/device/hub.ts +6 -0
  122. package/src/device/humidifier.ts +15 -1
  123. package/src/device/iosensor.ts +6 -0
  124. package/src/device/lightstrip.ts +14 -0
  125. package/src/device/lock.ts +10 -0
  126. package/src/device/meter.ts +6 -0
  127. package/src/device/meterplus.ts +6 -0
  128. package/src/device/motion.ts +6 -0
  129. package/src/device/plug.ts +10 -0
  130. package/src/device/robotvacuumcleaner.ts +17 -4
  131. package/src/device/waterdetector.ts +695 -0
  132. package/src/irdevice/airconditioner.ts +7 -0
  133. package/src/irdevice/airpurifier.ts +7 -0
  134. package/src/irdevice/camera.ts +7 -0
  135. package/src/irdevice/fan.ts +7 -0
  136. package/src/irdevice/light.ts +7 -0
  137. package/src/irdevice/other.ts +7 -0
  138. package/src/irdevice/tv.ts +7 -0
  139. package/src/irdevice/vacuumcleaner.ts +7 -0
  140. package/src/irdevice/waterheater.ts +7 -0
  141. package/src/platform.ts +72 -0
  142. package/src/settings.ts +6 -0
@@ -0,0 +1,695 @@
1
+ import { hostname } from 'os';
2
+ import { request } from 'undici';
3
+ import { sleep } from '../utils.js';
4
+ import { MqttClient } from 'mqtt';
5
+ import asyncmqtt from 'async-mqtt';
6
+ import { interval, Subject } from 'rxjs';
7
+ import { skipWhile } from 'rxjs/operators';
8
+ import { SwitchBotPlatform } from '../platform.js';
9
+ import { Service, PlatformAccessory, CharacteristicValue, API, Logging, HAP } from 'homebridge';
10
+ import { device, devicesConfig, serviceData, deviceStatus, Devices, SwitchBotPlatformConfig } from '../settings.js';
11
+
12
+ /**
13
+ * Platform Accessory
14
+ * An instance of this class is created for each accessory your platform registers
15
+ * Each accessory may expose multiple services of different service types.
16
+ */
17
+ export class WaterDetector {
18
+ public readonly api: API;
19
+ public readonly log: Logging;
20
+ public readonly config!: SwitchBotPlatformConfig;
21
+ protected readonly hap: HAP;
22
+ // Services
23
+ leakService?: Service;
24
+ batteryService: Service;
25
+
26
+ // Characteristic Values
27
+ StatusActive!: CharacteristicValue;
28
+ LeakDetected!: CharacteristicValue;
29
+ BatteryLevel!: CharacteristicValue;
30
+ ChargingState!: CharacteristicValue;
31
+ StatusLowBattery!: CharacteristicValue;
32
+ FirmwareRevision!: CharacteristicValue;
33
+
34
+ // OpenAPI Status
35
+ OpenAPI_BatteryLevel: deviceStatus['battery'];
36
+ OpenAPI_FirmwareRevision: deviceStatus['version'];
37
+ OpenAPI_LeakDetected: deviceStatus['status'];
38
+
39
+ // BLE Status
40
+ BLE_BatteryLevel!: serviceData['battery'];
41
+ BLE_LeakDetected!: number;//serviceData['status'];
42
+
43
+ // BLE Others
44
+ BLE_IsConnected?: boolean;
45
+
46
+ //MQTT stuff
47
+ mqttClient: MqttClient | null = null;
48
+
49
+ // EVE history service handler
50
+ historyService?: any;
51
+
52
+ // Config
53
+ scanDuration!: number;
54
+ deviceLogging!: string;
55
+ deviceRefreshRate!: number;
56
+
57
+ // Updates
58
+ WaterDetectorUpdateInProgress!: boolean;
59
+ doWaterDetectorUpdate: Subject<void>;
60
+
61
+ // Connection
62
+ private readonly OpenAPI: boolean;
63
+ private readonly BLE: boolean;
64
+
65
+ constructor(
66
+ private readonly platform: SwitchBotPlatform,
67
+ private accessory: PlatformAccessory,
68
+ public device: device & devicesConfig,
69
+ ) {
70
+ this.api = this.platform.api;
71
+ this.log = this.platform.log;
72
+ this.config = this.platform.config;
73
+ this.hap = this.api.hap;
74
+ // Connection
75
+ this.BLE = this.device.connectionType === 'BLE' || this.device.connectionType === 'BLE/OpenAPI';
76
+ this.OpenAPI = this.device.connectionType === 'OpenAPI' || this.device.connectionType === 'BLE/OpenAPI';
77
+ // default placeholders
78
+ this.deviceLogs(device);
79
+ this.scan(device);
80
+ this.refreshRate(device);
81
+ this.deviceContext();
82
+ this.setupHistoryService(device);
83
+ this.setupMqtt(device);
84
+ this.deviceConfig(device);
85
+
86
+ // this is subject we use to track when we need to POST changes to the SwitchBot API
87
+ this.doWaterDetectorUpdate = new Subject();
88
+ this.WaterDetectorUpdateInProgress = false;
89
+
90
+ // Retrieve initial values and updateHomekit
91
+ this.refreshStatus();
92
+
93
+ // set accessory information
94
+ accessory
95
+ .getService(this.hap.Service.AccessoryInformation)!
96
+ .setCharacteristic(this.hap.Characteristic.Manufacturer, 'SwitchBot')
97
+ .setCharacteristic(this.hap.Characteristic.Model, 'WoWaterDetector')
98
+ .setCharacteristic(this.hap.Characteristic.SerialNumber, device.deviceId)
99
+ .setCharacteristic(this.hap.Characteristic.FirmwareRevision, accessory.context.FirmwareRevision);
100
+
101
+ // Leak Sensor Service
102
+ if (device.waterdetector?.hide_leak) {
103
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Removing Leak Sensor Service`);
104
+ this.leakService = this.accessory.getService(this.hap.Service.LeakSensor);
105
+ accessory.removeService(this.leakService!);
106
+ } else if (!this.leakService) {
107
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Add Leak Sensor Service`);
108
+ const leakService = `${accessory.displayName} Leak Sensor`;
109
+ (this.leakService = this.accessory.getService(this.hap.Service.LeakSensor)
110
+ || this.accessory.addService(this.hap.Service.LeakSensor)), leakService;
111
+
112
+ this.leakService.setCharacteristic(this.hap.Characteristic.Name, `${accessory.displayName} Leak Sensor`);
113
+ if (!this.leakService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
114
+ this.leakService.addCharacteristic(this.hap.Characteristic.ConfiguredName, `${accessory.displayName} Leak Sensor`);
115
+ }
116
+ } else {
117
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Leak Sensor Service Not Added`);
118
+ }
119
+
120
+ // Battery Service
121
+ const batteryService = `${accessory.displayName} Battery`;
122
+ (this.batteryService = this.accessory.getService(this.hap.Service.Battery)
123
+ || accessory.addService(this.hap.Service.Battery)), batteryService;
124
+
125
+ this.batteryService.setCharacteristic(this.hap.Characteristic.Name, `${accessory.displayName} Battery`);
126
+ if (!this.batteryService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
127
+ this.batteryService.addCharacteristic(this.hap.Characteristic.ConfiguredName, `${accessory.displayName} Battery`);
128
+ }
129
+ this.batteryService.setCharacteristic(this.hap.Characteristic.ChargingState, this.hap.Characteristic.ChargingState.NOT_CHARGEABLE);
130
+
131
+ // Retrieve initial values and updateHomekit
132
+ this.updateHomeKitCharacteristics();
133
+
134
+ // Start an update interval
135
+ interval(this.deviceRefreshRate * 1000)
136
+ .pipe(skipWhile(() => this.WaterDetectorUpdateInProgress))
137
+ .subscribe(async () => {
138
+ await this.refreshStatus();
139
+ });
140
+
141
+ //regisiter webhook event handler
142
+ if (this.device.webhook) {
143
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} is listening webhook.`);
144
+ this.platform.webhookEventHandler[this.device.deviceId] = async (context) => {
145
+ try {
146
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} received Webhook: ${JSON.stringify(context)}`);
147
+ const { status } = context;
148
+ const { LeakDetected } = this;
149
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ` +
150
+ '(status) = ' +
151
+ `Webhook:(${status}), ` +
152
+ `current:(${LeakDetected})`);
153
+ this.LeakDetected = status;
154
+ this.updateHomeKitCharacteristics();
155
+ } catch (e: any) {
156
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} `
157
+ + `failed to handle webhook. Received: ${JSON.stringify(context)} Error: ${e}`);
158
+ }
159
+ };
160
+ }
161
+ }
162
+
163
+ /**
164
+ * Parse the device status from the SwitchBot api
165
+ */
166
+ async parseStatus(): Promise<void> {
167
+ if (!this.device.enableCloudService && this.OpenAPI) {
168
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} parseStatus enableCloudService: ${this.device.enableCloudService}`);
169
+ } else if (this.BLE) {
170
+ await this.BLEparseStatus();
171
+ } else if (this.OpenAPI && this.platform.config.credentials?.token) {
172
+ await this.openAPIparseStatus();
173
+ } else {
174
+ await this.offlineOff();
175
+ this.debugWarnLog(
176
+ `${this.device.deviceType}: ${this.accessory.displayName} Connection Type:` + ` ${this.device.connectionType}, parseStatus will not happen.`,
177
+ );
178
+ }
179
+ }
180
+
181
+ async BLEparseStatus(): Promise<void> {
182
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLEparseStatus`);
183
+
184
+ // Battery
185
+ this.BatteryLevel = Number(this.BLE_BatteryLevel);
186
+ if (this.BatteryLevel < 15) {
187
+ this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
188
+ } else {
189
+ this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
190
+ }
191
+ this.debugLog(`${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel}, StatusLowBattery: ${this.StatusLowBattery}`);
192
+
193
+ // LeakDetected
194
+ this.LeakDetected = this.BLE_LeakDetected!;
195
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} LeakDetected: ${this.LeakDetected}`);
196
+ }
197
+
198
+ async openAPIparseStatus(): Promise<void> {
199
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIparseStatus`);
200
+ // StatusLowBattery
201
+ this.BatteryLevel = Number(this.OpenAPI_BatteryLevel);
202
+ if (this.BatteryLevel < 10) {
203
+ this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
204
+ } else {
205
+ this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
206
+ }
207
+ this.debugLog(`${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel}, StatusLowBattery: ${this.StatusLowBattery}`);
208
+
209
+ // BatteryLevel
210
+ if (Number.isNaN(this.BatteryLevel)) {
211
+ this.BatteryLevel = 100;
212
+ }
213
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel}`);
214
+
215
+ // LeakDetected
216
+ this.LeakDetected = this.OpenAPI_LeakDetected!;
217
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} LeakDetected: ${this.LeakDetected}`);
218
+
219
+ // FirmwareRevision
220
+ this.FirmwareRevision = this.OpenAPI_FirmwareRevision!;
221
+ this.accessory.context.FirmwareRevision = this.FirmwareRevision;
222
+ }
223
+
224
+ /**
225
+ * Asks the SwitchBot API for the latest device information
226
+ */
227
+ async refreshStatus(): Promise<void> {
228
+ if (!this.device.enableCloudService && this.OpenAPI) {
229
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} refreshStatus enableCloudService: ${this.device.enableCloudService}`);
230
+ } else if (this.BLE) {
231
+ await this.BLERefreshStatus();
232
+ } else if (this.OpenAPI && this.platform.config.credentials?.token) {
233
+ await this.openAPIRefreshStatus();
234
+ } else {
235
+ await this.offlineOff();
236
+ this.debugWarnLog(
237
+ `${this.device.deviceType}: ${this.accessory.displayName} Connection Type:` +
238
+ ` ${this.device.connectionType}, refreshStatus will not happen.`,
239
+ );
240
+ }
241
+ }
242
+
243
+ async BLERefreshStatus(): Promise<void> {
244
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLERefreshStatus`);
245
+ const switchbot = await this.platform.connectBLE();
246
+ // Convert to BLE Address
247
+ this.device.bleMac = this.device
248
+ .deviceId!.match(/.{1,2}/g)!
249
+ .join(':')
250
+ .toLowerCase();
251
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLE Address: ${this.device.bleMac}`);
252
+ this.getCustomBLEAddress(switchbot);
253
+ // Start to monitor advertisement packets
254
+ (async () => {
255
+ // Start to monitor advertisement packets
256
+ await switchbot.startScan({
257
+ model: 'l',
258
+ id: this.device.bleMac,
259
+ });
260
+ // Set an event handler
261
+ switchbot.onadvertisement = (ad: any) => {
262
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ${JSON.stringify(ad, null, ' ')}`);
263
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} address: ${ad.address}, model: ${ad.serviceData.model}`);
264
+ if (this.device.bleMac === ad.address && ad.serviceData.model === 'l') {
265
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} serviceData: ${JSON.stringify(ad.serviceData)}`);
266
+ this.BLE_LeakDetected = ad.serviceData.status;
267
+ this.BLE_BatteryLevel = ad.serviceData.battery;
268
+ } else {
269
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} serviceData: ${JSON.stringify(ad.serviceData)}`);
270
+ }
271
+ };
272
+ // Wait 1 seconds
273
+ await switchbot.wait(this.scanDuration * 1000);
274
+ // Stop to monitor
275
+ await switchbot.stopScan();
276
+ // Update HomeKit
277
+ await this.BLEparseStatus();
278
+ await this.updateHomeKitCharacteristics();
279
+ })();
280
+ }
281
+
282
+ async openAPIRefreshStatus(): Promise<void> {
283
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIRefreshStatus`);
284
+ try {
285
+ const { body, statusCode } = await request(`${Devices}/${this.device.deviceId}/status`, {
286
+ headers: this.platform.generateHeaders(),
287
+ });
288
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} statusCode: ${statusCode}`);
289
+ const deviceStatus: any = await body.json();
290
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} deviceStatus: ${JSON.stringify(deviceStatus)}`);
291
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} deviceStatus statusCode: ${deviceStatus.statusCode}`);
292
+ if ((statusCode === 200 || statusCode === 100) && (deviceStatus.statusCode === 200 || deviceStatus.statusCode === 100)) {
293
+ this.debugErrorLog(`${this.device.deviceType}: ${this.accessory.displayName} `
294
+ + `statusCode: ${statusCode} & deviceStatus StatusCode: ${deviceStatus.statusCode}`);
295
+ this.OpenAPI_LeakDetected = deviceStatus.body.status;
296
+ this.OpenAPI_BatteryLevel = deviceStatus.body.battery;
297
+ this.OpenAPI_FirmwareRevision = deviceStatus.body.version;
298
+ this.openAPIparseStatus();
299
+ this.updateHomeKitCharacteristics();
300
+ } else {
301
+ this.statusCode(statusCode);
302
+ this.statusCode(deviceStatus.statusCode);
303
+ }
304
+ } catch (e: any) {
305
+ this.apiError(e);
306
+ this.errorLog(
307
+ `${this.device.deviceType}: ${this.accessory.displayName} failed openAPIRefreshStatus with ${this.device.connectionType}` +
308
+ ` Connection, Error Message: ${JSON.stringify(e.message)}`,
309
+ );
310
+ }
311
+ }
312
+
313
+ /**
314
+ * Updates the status for each of the HomeKit Characteristics
315
+ */
316
+ async updateHomeKitCharacteristics(): Promise<void> {
317
+ const mqttmessage: string[] = [];
318
+ const entry = { time: Math.round(new Date().valueOf() / 1000) };
319
+ if (!this.device.waterdetector?.hide_leak) {
320
+ if (this.LeakDetected === undefined) {
321
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} LeakDetected: ${this.LeakDetected}`);
322
+ } else {
323
+ if (this.device.mqttURL) {
324
+ mqttmessage.push(`"LeakDetected": ${this.LeakDetected}`);
325
+ }
326
+ if (this.device.history) {
327
+ entry['leak'] = this.LeakDetected;
328
+ }
329
+ this.accessory.context.LeakDetected = this.LeakDetected;
330
+ this.leakService?.updateCharacteristic(this.hap.Characteristic.LeakDetected, this.LeakDetected);
331
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic LeakDetected: ${this.LeakDetected}`);
332
+ }
333
+ }
334
+ if (this.BatteryLevel === undefined) {
335
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel}`);
336
+ } else {
337
+ if (this.device.mqttURL) {
338
+ mqttmessage.push(`"battery": ${this.BatteryLevel}`);
339
+ }
340
+ this.accessory.context.BatteryLevel = this.BatteryLevel;
341
+ this.batteryService?.updateCharacteristic(this.hap.Characteristic.BatteryLevel, this.BatteryLevel);
342
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic BatteryLevel: ${this.BatteryLevel}`);
343
+ }
344
+ if (this.StatusLowBattery === undefined) {
345
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} StatusLowBattery: ${this.StatusLowBattery}`);
346
+ } else {
347
+ if (this.device.mqttURL) {
348
+ mqttmessage.push(`"lowBattery": ${this.StatusLowBattery}`);
349
+ }
350
+ this.accessory.context.StatusLowBattery = this.StatusLowBattery;
351
+ this.batteryService?.updateCharacteristic(this.hap.Characteristic.StatusLowBattery, this.StatusLowBattery);
352
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic StatusLowBattery: ${this.StatusLowBattery}`);
353
+ }
354
+ if (this.device.mqttURL) {
355
+ this.mqttPublish(`{${mqttmessage.join(',')}}`);
356
+ }
357
+ if (Number(this.LeakDetected) > 0) {
358
+ // reject unreliable data
359
+ if (this.device.history) {
360
+ this.historyService?.addEntry(entry);
361
+ }
362
+ }
363
+ }
364
+
365
+ /*
366
+ * Publish MQTT message for topics of
367
+ * 'homebridge-switchbot/meter/xx:xx:xx:xx:xx:xx'
368
+ */
369
+ mqttPublish(message: any) {
370
+ const mac = this.device.deviceId
371
+ ?.toLowerCase()
372
+ .match(/[\s\S]{1,2}/g)
373
+ ?.join(':');
374
+ const options = this.device.mqttPubOptions || {};
375
+ this.mqttClient?.publish(`homebridge-switchbot/meter/${mac}`, `${message}`, options);
376
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} MQTT message: ${message} options:${JSON.stringify(options)}`);
377
+ }
378
+
379
+ /*
380
+ * Setup MQTT hadler if URL is specified.
381
+ */
382
+ async setupMqtt(device: device & devicesConfig): Promise<void> {
383
+ if (device.mqttURL) {
384
+ try {
385
+ const { connectAsync } = asyncmqtt;
386
+ this.mqttClient = await connectAsync(device.mqttURL, device.mqttOptions || {});
387
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} MQTT connection has been established successfully.`);
388
+ this.mqttClient.on('error', (e: Error) => {
389
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Failed to publish MQTT messages. ${e}`);
390
+ });
391
+ } catch (e) {
392
+ this.mqttClient = null;
393
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Failed to establish MQTT connection. ${e}`);
394
+ }
395
+ }
396
+ }
397
+
398
+ /*
399
+ * Setup EVE history graph feature if enabled.
400
+ */
401
+ async setupHistoryService(device: device & devicesConfig): Promise<void> {
402
+ const mac = this.device
403
+ .deviceId!.match(/.{1,2}/g)!
404
+ .join(':')
405
+ .toLowerCase();
406
+ this.historyService = device.history
407
+ ? new this.platform.fakegatoAPI('room', this.accessory, {
408
+ log: this.platform.log,
409
+ storage: 'fs',
410
+ filename: `${hostname().split('.')[0]}_${mac}_persist.json`,
411
+ })
412
+ : null;
413
+ }
414
+
415
+ async stopScanning(switchbot: any) {
416
+ switchbot.stopScan();
417
+ if (this.BLE_IsConnected) {
418
+ await this.BLEparseStatus();
419
+ await this.updateHomeKitCharacteristics();
420
+ } else {
421
+ await this.BLERefreshConnection(switchbot);
422
+ }
423
+ }
424
+
425
+ async getCustomBLEAddress(switchbot: any) {
426
+ if (this.device.customBLEaddress && this.deviceLogging.includes('debug')) {
427
+ (async () => {
428
+ // Start to monitor advertisement packets
429
+ await switchbot.startScan({
430
+ model: 'i',
431
+ });
432
+ // Set an event handler
433
+ switchbot.onadvertisement = (ad: any) => {
434
+ this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} ad: ${JSON.stringify(ad, null, ' ')}`);
435
+ };
436
+ await sleep(10000);
437
+ // Stop to monitor
438
+ switchbot.stopScan();
439
+ })();
440
+ }
441
+ }
442
+
443
+ async BLERefreshConnection(switchbot: any): Promise<void> {
444
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} wasn't able to establish BLE Connection, node-switchbot:`
445
+ + ` ${JSON.stringify(switchbot)}`);
446
+ if (this.platform.config.credentials?.token && this.device.connectionType === 'BLE/OpenAPI') {
447
+ this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} Using OpenAPI Connection to Refresh Status`);
448
+ await this.openAPIRefreshStatus();
449
+ }
450
+ }
451
+
452
+ async scan(device: device & devicesConfig): Promise<void> {
453
+ if (device.scanDuration) {
454
+ this.scanDuration = this.accessory.context.scanDuration = device.scanDuration;
455
+ if (this.BLE) {
456
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config scanDuration: ${this.scanDuration}`);
457
+ }
458
+ } else {
459
+ this.scanDuration = this.accessory.context.scanDuration = 1;
460
+ if (this.BLE) {
461
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Default scanDuration: ${this.scanDuration}`);
462
+ }
463
+ }
464
+ }
465
+
466
+ async statusCode(statusCode: number): Promise<void> {
467
+ switch (statusCode) {
468
+ case 151:
469
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Command not supported by this deviceType, statusCode: ${statusCode}`);
470
+ break;
471
+ case 152:
472
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Device not found, statusCode: ${statusCode}`);
473
+ break;
474
+ case 160:
475
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Command is not supported, statusCode: ${statusCode}`);
476
+ break;
477
+ case 161:
478
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Device is offline, statusCode: ${statusCode}`);
479
+ this.offlineOff();
480
+ break;
481
+ case 171:
482
+ this.errorLog(
483
+ `${this.device.deviceType}: ${this.accessory.displayName} Hub Device is offline, statusCode: ${statusCode}. ` +
484
+ `Hub: ${this.device.hubDeviceId}`,
485
+ );
486
+ this.offlineOff();
487
+ break;
488
+ case 190:
489
+ this.errorLog(
490
+ `${this.device.deviceType}: ${this.accessory.displayName} Device internal error due to device states not synchronized with server,` +
491
+ ` Or command format is invalid, statusCode: ${statusCode}`,
492
+ );
493
+ break;
494
+ case 100:
495
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Command successfully sent, statusCode: ${statusCode}`);
496
+ break;
497
+ case 200:
498
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Request successful, statusCode: ${statusCode}`);
499
+ break;
500
+ case 400:
501
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Bad Request, The client has issued an invalid request. `
502
+ + `This is commonly used to specify validation errors in a request payload, statusCode: ${statusCode}`);
503
+ break;
504
+ case 401:
505
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Unauthorized, Authorization for the API is required, `
506
+ + `but the request has not been authenticated, statusCode: ${statusCode}`);
507
+ break;
508
+ case 403:
509
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Forbidden, The request has been authenticated but does not `
510
+ + `have appropriate permissions, or a requested resource is not found, statusCode: ${statusCode}`);
511
+ break;
512
+ case 404:
513
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Not Found, Specifies the requested path does not exist, `
514
+ + `statusCode: ${statusCode}`);
515
+ break;
516
+ case 406:
517
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Not Acceptable, The client has requested a MIME type via `
518
+ + `the Accept header for a value not supported by the server, statusCode: ${statusCode}`);
519
+ break;
520
+ case 415:
521
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Unsupported Media Type, The client has defined a contentType `
522
+ + `header that is not supported by the server, statusCode: ${statusCode}`);
523
+ break;
524
+ case 422:
525
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Unprocessable Entity, The client has made a valid request, `
526
+ + `but the server cannot process it. This is often used for APIs for which certain limits have been exceeded, statusCode: ${statusCode}`);
527
+ break;
528
+ case 429:
529
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Too Many Requests, The client has exceeded the number of `
530
+ + `requests allowed for a given time window, statusCode: ${statusCode}`);
531
+ break;
532
+ case 500:
533
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Internal Server Error, An unexpected error on the SmartThings `
534
+ + `servers has occurred. These errors should be rare, statusCode: ${statusCode}`);
535
+ break;
536
+ default:
537
+ this.infoLog(
538
+ `${this.device.deviceType}: ${this.accessory.displayName} Unknown statusCode: ` +
539
+ `${statusCode}, Submit Bugs Here: ' + 'https://tinyurl.com/SwitchBotBug`,
540
+ );
541
+ }
542
+ }
543
+
544
+ async offlineOff(): Promise<void> {
545
+ if (this.device.offline) {
546
+ await this.deviceContext();
547
+ await this.updateHomeKitCharacteristics();
548
+ }
549
+ }
550
+
551
+ async apiError(e: any): Promise<void> {
552
+ if (!this.device.waterdetector?.hide_leak) {
553
+ this.leakService?.updateCharacteristic(this.hap.Characteristic.LeakDetected, e);
554
+ }
555
+ this.batteryService?.updateCharacteristic(this.hap.Characteristic.BatteryLevel, e);
556
+ this.batteryService?.updateCharacteristic(this.hap.Characteristic.StatusLowBattery, e);
557
+ }
558
+
559
+ async deviceContext() {
560
+ if (this.LeakDetected === undefined) {
561
+ this.LeakDetected = 0;
562
+ } else {
563
+ this.LeakDetected = this.accessory.context.LeakDetected;
564
+ }
565
+ if (this.BatteryLevel === undefined) {
566
+ this.BatteryLevel = 100;
567
+ } else {
568
+ this.BatteryLevel = this.accessory.context.BatteryLevel;
569
+ }
570
+ if (this.StatusLowBattery === undefined) {
571
+ this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
572
+ this.accessory.context.StatusLowBattery = this.StatusLowBattery;
573
+ } else {
574
+ this.StatusLowBattery = this.accessory.context.StatusLowBattery;
575
+ }
576
+ if (this.FirmwareRevision === undefined) {
577
+ this.FirmwareRevision = this.platform.version;
578
+ this.accessory.context.FirmwareRevision = this.FirmwareRevision;
579
+ }
580
+ }
581
+
582
+ async refreshRate(device: device & devicesConfig): Promise<void> {
583
+ if (device.refreshRate) {
584
+ this.deviceRefreshRate = this.accessory.context.refreshRate = device.refreshRate;
585
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config refreshRate: ${this.deviceRefreshRate}`);
586
+ } else if (this.platform.config.options!.refreshRate) {
587
+ this.deviceRefreshRate = this.accessory.context.refreshRate = this.platform.config.options!.refreshRate;
588
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Platform Config refreshRate: ${this.deviceRefreshRate}`);
589
+ }
590
+ }
591
+
592
+ async deviceConfig(device: device & devicesConfig): Promise<void> {
593
+ let config = {};
594
+ if (device.waterdetector) {
595
+ config = device.waterdetector;
596
+ }
597
+ if (device.connectionType !== undefined) {
598
+ config['connectionType'] = device.connectionType;
599
+ }
600
+ if (device.external !== undefined) {
601
+ config['external'] = device.external;
602
+ }
603
+ if (device.mqttURL !== undefined) {
604
+ config['mqttURL'] = device.mqttURL;
605
+ }
606
+ if (device.logging !== undefined) {
607
+ config['logging'] = device.logging;
608
+ }
609
+ if (device.refreshRate !== undefined) {
610
+ config['refreshRate'] = device.refreshRate;
611
+ }
612
+ if (device.scanDuration !== undefined) {
613
+ config['scanDuration'] = device.scanDuration;
614
+ }
615
+ if (device.webhook !== undefined) {
616
+ config['webhook'] = device.webhook;
617
+ }
618
+ if (Object.entries(config).length !== 0) {
619
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} Config: ${JSON.stringify(config)}`);
620
+ }
621
+ }
622
+
623
+ async deviceLogs(device: device & devicesConfig): Promise<void> {
624
+ if (this.platform.debugMode) {
625
+ this.deviceLogging = this.accessory.context.logging = 'debugMode';
626
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Debug Mode Logging: ${this.deviceLogging}`);
627
+ } else if (device.logging) {
628
+ this.deviceLogging = this.accessory.context.logging = device.logging;
629
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config Logging: ${this.deviceLogging}`);
630
+ } else if (this.platform.config.options?.logging) {
631
+ this.deviceLogging = this.accessory.context.logging = this.platform.config.options?.logging;
632
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Platform Config Logging: ${this.deviceLogging}`);
633
+ } else {
634
+ this.deviceLogging = this.accessory.context.logging = 'standard';
635
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Logging Not Set, Using: ${this.deviceLogging}`);
636
+ }
637
+ }
638
+
639
+ /**
640
+ * Logging for Device
641
+ */
642
+ successLog(...log: any[]): void {
643
+ if (this.enablingDeviceLogging()) {
644
+ this.platform.log.success(String(...log));
645
+ }
646
+ }
647
+
648
+ infoLog(...log: any[]): void {
649
+ if (this.enablingDeviceLogging()) {
650
+ this.platform.log.info(String(...log));
651
+ }
652
+ }
653
+
654
+ warnLog(...log: any[]): void {
655
+ if (this.enablingDeviceLogging()) {
656
+ this.platform.log.warn(String(...log));
657
+ }
658
+ }
659
+
660
+ debugWarnLog(...log: any[]): void {
661
+ if (this.enablingDeviceLogging()) {
662
+ if (this.deviceLogging?.includes('debug')) {
663
+ this.platform.log.warn('[DEBUG]', String(...log));
664
+ }
665
+ }
666
+ }
667
+
668
+ errorLog(...log: any[]): void {
669
+ if (this.enablingDeviceLogging()) {
670
+ this.platform.log.error(String(...log));
671
+ }
672
+ }
673
+
674
+ debugErrorLog(...log: any[]): void {
675
+ if (this.enablingDeviceLogging()) {
676
+ if (this.deviceLogging?.includes('debug')) {
677
+ this.platform.log.error('[DEBUG]', String(...log));
678
+ }
679
+ }
680
+ }
681
+
682
+ debugLog(...log: any[]): void {
683
+ if (this.enablingDeviceLogging()) {
684
+ if (this.deviceLogging === 'debug') {
685
+ this.platform.log.info('[DEBUG]', String(...log));
686
+ } else {
687
+ this.platform.log.debug(String(...log));
688
+ }
689
+ }
690
+ }
691
+
692
+ enablingDeviceLogging(): boolean {
693
+ return this.deviceLogging.includes('debug') || this.deviceLogging === 'standard';
694
+ }
695
+ }