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

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,884 @@
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, Units, CharacteristicValue, API, Logging, HAP } from 'homebridge';
10
+ import { device, devicesConfig, serviceData, temperature, 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
+ humidityservice?: Service;
26
+ temperatureservice?: Service;
27
+
28
+ // Characteristic Values
29
+ StatusActive!: CharacteristicValue;
30
+ LeakDetected!: CharacteristicValue;
31
+ BatteryLevel!: CharacteristicValue;
32
+ ChargingState!: CharacteristicValue;
33
+ StatusLowBattery!: CharacteristicValue;
34
+ FirmwareRevision!: CharacteristicValue;
35
+ CurrentTemperature!: CharacteristicValue;
36
+ CurrentRelativeHumidity!: CharacteristicValue;
37
+
38
+ // OpenAPI Status
39
+ OpenAPI_BatteryLevel: deviceStatus['battery'];
40
+ OpenAPI_FirmwareRevision: deviceStatus['version'];
41
+ OpenAPI_CurrentTemperature: deviceStatus['temperature'];
42
+ OpenAPI_CurrentRelativeHumidity: deviceStatus['humidity'];
43
+
44
+ // BLE Status
45
+ BLE_Celsius!: temperature['c'];
46
+ BLE_Fahrenheit!: temperature['f'];
47
+ BLE_BatteryLevel!: serviceData['battery'];
48
+ BLE_CurrentTemperature!: serviceData['temperature'];
49
+ BLE_CurrentRelativeHumidity!: serviceData['humidity'];
50
+
51
+ // BLE Others
52
+ BLE_IsConnected?: boolean;
53
+
54
+ //MQTT stuff
55
+ mqttClient: MqttClient | null = null;
56
+
57
+ // EVE history service handler
58
+ historyService?: any;
59
+
60
+ // Config
61
+ scanDuration!: number;
62
+ deviceLogging!: string;
63
+ deviceRefreshRate!: number;
64
+
65
+ // Updates
66
+ WaterDetectorUpdateInProgress!: boolean;
67
+ doWaterDetectorUpdate: Subject<void>;
68
+
69
+ // Connection
70
+ private readonly OpenAPI: boolean;
71
+ private readonly BLE: boolean;
72
+
73
+ constructor(
74
+ private readonly platform: SwitchBotPlatform,
75
+ private accessory: PlatformAccessory,
76
+ public device: device & devicesConfig,
77
+ ) {
78
+ this.api = this.platform.api;
79
+ this.log = this.platform.log;
80
+ this.config = this.platform.config;
81
+ this.hap = this.api.hap;
82
+ // Connection
83
+ this.BLE = this.device.connectionType === 'BLE' || this.device.connectionType === 'BLE/OpenAPI';
84
+ this.OpenAPI = this.device.connectionType === 'OpenAPI' || this.device.connectionType === 'BLE/OpenAPI';
85
+ // default placeholders
86
+ this.deviceLogs(device);
87
+ this.scan(device);
88
+ this.refreshRate(device);
89
+ this.deviceContext();
90
+ this.setupHistoryService(device);
91
+ this.setupMqtt(device);
92
+ this.deviceConfig(device);
93
+
94
+ // this is subject we use to track when we need to POST changes to the SwitchBot API
95
+ this.doWaterDetectorUpdate = new Subject();
96
+ this.WaterDetectorUpdateInProgress = false;
97
+
98
+ // Retrieve initial values and updateHomekit
99
+ this.refreshStatus();
100
+
101
+ // set accessory information
102
+ accessory
103
+ .getService(this.hap.Service.AccessoryInformation)!
104
+ .setCharacteristic(this.hap.Characteristic.Manufacturer, 'SwitchBot')
105
+ .setCharacteristic(this.hap.Characteristic.Model, 'WoWaterDetector')
106
+ .setCharacteristic(this.hap.Characteristic.SerialNumber, device.deviceId)
107
+ .setCharacteristic(this.hap.Characteristic.FirmwareRevision, accessory.context.FirmwareRevision);
108
+
109
+ // Leak Sensor Service
110
+ if (device.waterdetector?.hide_leak) {
111
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Removing Leak Sensor Service`);
112
+ this.leakService = this.accessory.getService(this.hap.Service.LeakSensor);
113
+ accessory.removeService(this.leakService!);
114
+ } else if (!this.leakService) {
115
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Add Leak Sensor Service`);
116
+ const leakService = `${accessory.displayName} Leak Sensor`;
117
+ (this.leakService = this.accessory.getService(this.hap.Service.LeakSensor)
118
+ || this.accessory.addService(this.hap.Service.LeakSensor)), leakService;
119
+
120
+ this.leakService.setCharacteristic(this.hap.Characteristic.Name, `${accessory.displayName} Leak Sensor`);
121
+ if (!this.leakService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
122
+ this.leakService.addCharacteristic(this.hap.Characteristic.ConfiguredName, `${accessory.displayName} Leak Sensor`);
123
+ }
124
+ } else {
125
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Leak Sensor Service Not Added`);
126
+ }
127
+
128
+ // Temperature Sensor Service
129
+ if (device.waterdetector?.hide_temperature) {
130
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Removing Temperature Sensor Service`);
131
+ this.temperatureservice = this.accessory.getService(this.hap.Service.TemperatureSensor);
132
+ accessory.removeService(this.temperatureservice!);
133
+ } else if (!this.temperatureservice) {
134
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Add Temperature Sensor Service`);
135
+ const temperatureservice = `${accessory.displayName} Temperature Sensor`;
136
+ (this.temperatureservice = this.accessory.getService(this.hap.Service.TemperatureSensor)
137
+ || this.accessory.addService(this.hap.Service.TemperatureSensor)), temperatureservice;
138
+
139
+ this.temperatureservice.setCharacteristic(this.hap.Characteristic.Name, `${accessory.displayName} Temperature Sensor`);
140
+ if (!this.temperatureservice.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
141
+ this.temperatureservice.addCharacteristic(this.hap.Characteristic.ConfiguredName, `${accessory.displayName} Temperature Sensor`);
142
+ }
143
+ this.temperatureservice
144
+ .getCharacteristic(this.hap.Characteristic.CurrentTemperature)
145
+ .setProps({
146
+ unit: Units['CELSIUS'],
147
+ validValueRanges: [-273.15, 100],
148
+ minValue: -273.15,
149
+ maxValue: 100,
150
+ minStep: 0.1,
151
+ })
152
+ .onGet(() => {
153
+ return this.CurrentTemperature!;
154
+ });
155
+ } else {
156
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Temperature Sensor Service Not Added`);
157
+ }
158
+
159
+ // Humidity Sensor Service
160
+ if (device.waterdetector?.hide_humidity) {
161
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Removing Humidity Sensor Service`);
162
+ this.humidityservice = this.accessory.getService(this.hap.Service.HumiditySensor);
163
+ accessory.removeService(this.humidityservice!);
164
+ } else if (!this.humidityservice) {
165
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Add Humidity Sensor Service`);
166
+ const humidityservice = `${accessory.displayName} Humidity Sensor`;
167
+ (this.humidityservice = this.accessory.getService(this.hap.Service.HumiditySensor)
168
+ || this.accessory.addService(this.hap.Service.HumiditySensor)), humidityservice;
169
+
170
+ this.humidityservice.setCharacteristic(this.hap.Characteristic.Name, `${accessory.displayName} Humidity Sensor`);
171
+ if (!this.humidityservice.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
172
+ this.humidityservice.addCharacteristic(this.hap.Characteristic.ConfiguredName, `${accessory.displayName} Humidity Sensor`);
173
+ }
174
+ this.humidityservice
175
+ .getCharacteristic(this.hap.Characteristic.CurrentRelativeHumidity)
176
+ .setProps({
177
+ minStep: 0.1,
178
+ })
179
+ .onGet(() => {
180
+ return this.CurrentRelativeHumidity;
181
+ });
182
+ } else {
183
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Humidity Sensor Service Not Added`);
184
+ }
185
+
186
+ // Battery Service
187
+ const batteryService = `${accessory.displayName} Battery`;
188
+ (this.batteryService = this.accessory.getService(this.hap.Service.Battery)
189
+ || accessory.addService(this.hap.Service.Battery)), batteryService;
190
+
191
+ this.batteryService.setCharacteristic(this.hap.Characteristic.Name, `${accessory.displayName} Battery`);
192
+ if (!this.batteryService.testCharacteristic(this.hap.Characteristic.ConfiguredName)) {
193
+ this.batteryService.addCharacteristic(this.hap.Characteristic.ConfiguredName, `${accessory.displayName} Battery`);
194
+ }
195
+ this.batteryService.setCharacteristic(this.hap.Characteristic.ChargingState, this.hap.Characteristic.ChargingState.NOT_CHARGEABLE);
196
+
197
+ // Retrieve initial values and updateHomekit
198
+ this.updateHomeKitCharacteristics();
199
+
200
+ // Start an update interval
201
+ interval(this.deviceRefreshRate * 1000)
202
+ .pipe(skipWhile(() => this.WaterDetectorUpdateInProgress))
203
+ .subscribe(async () => {
204
+ await this.refreshStatus();
205
+ });
206
+
207
+ //regisiter webhook event handler
208
+ if (this.device.webhook) {
209
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} is listening webhook.`);
210
+ this.platform.webhookEventHandler[this.device.deviceId] = async (context) => {
211
+ try {
212
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} received Webhook: ${JSON.stringify(context)}`);
213
+ if (context.scale === 'CELSIUS') {
214
+ const { temperature, humidity } = context;
215
+ const { CurrentTemperature, CurrentRelativeHumidity } = this;
216
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ` +
217
+ '(temperature, humidity) = ' +
218
+ `Webhook:(${temperature}, ${humidity}), ` +
219
+ `current:(${CurrentTemperature}, ${CurrentRelativeHumidity})`);
220
+ this.CurrentRelativeHumidity = humidity;
221
+ this.CurrentTemperature = temperature;
222
+ this.updateHomeKitCharacteristics();
223
+ }
224
+ } catch (e: any) {
225
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} `
226
+ + `failed to handle webhook. Received: ${JSON.stringify(context)} Error: ${e}`);
227
+ }
228
+ };
229
+ }
230
+ }
231
+
232
+ /**
233
+ * Parse the device status from the SwitchBot api
234
+ */
235
+ async parseStatus(): Promise<void> {
236
+ if (!this.device.enableCloudService && this.OpenAPI) {
237
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} parseStatus enableCloudService: ${this.device.enableCloudService}`);
238
+ } else if (this.BLE) {
239
+ await this.BLEparseStatus();
240
+ } else if (this.OpenAPI && this.platform.config.credentials?.token) {
241
+ await this.openAPIparseStatus();
242
+ } else {
243
+ await this.offlineOff();
244
+ this.debugWarnLog(
245
+ `${this.device.deviceType}: ${this.accessory.displayName} Connection Type:` + ` ${this.device.connectionType}, parseStatus will not happen.`,
246
+ );
247
+ }
248
+ }
249
+
250
+ async BLEparseStatus(): Promise<void> {
251
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLEparseStatus`);
252
+
253
+ // Battery
254
+ this.BatteryLevel = Number(this.BLE_BatteryLevel);
255
+ if (this.BatteryLevel < 15) {
256
+ this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
257
+ } else {
258
+ this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
259
+ }
260
+ this.debugLog(`${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel}, StatusLowBattery: ${this.StatusLowBattery}`);
261
+
262
+ // Humidity
263
+ if (!this.device.waterdetector?.hide_humidity) {
264
+ this.CurrentRelativeHumidity = this.BLE_CurrentRelativeHumidity!;
265
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Humidity: ${this.CurrentRelativeHumidity}%`);
266
+ }
267
+
268
+ // Current Temperature
269
+ if (!this.device.waterdetector?.hide_temperature) {
270
+ this.BLE_Celsius < 0 ? 0 : this.BLE_Celsius > 100 ? 100 : this.BLE_Celsius;
271
+ this.CurrentTemperature = this.BLE_Celsius;
272
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Temperature: ${this.CurrentTemperature}°c`);
273
+ }
274
+ }
275
+
276
+ async openAPIparseStatus(): Promise<void> {
277
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIparseStatus`);
278
+ // Battery
279
+ this.BatteryLevel = Number(this.OpenAPI_BatteryLevel);
280
+ if (this.BatteryLevel < 15) {
281
+ this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
282
+ } else {
283
+ this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
284
+ }
285
+ this.debugLog(`${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel}, StatusLowBattery: ${this.StatusLowBattery}`);
286
+
287
+ // Current Relative Humidity
288
+ if (!this.device.waterdetector?.hide_humidity) {
289
+ this.CurrentRelativeHumidity = this.OpenAPI_CurrentRelativeHumidity!;
290
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Humidity: ${this.CurrentRelativeHumidity}%`);
291
+ }
292
+
293
+ // Current Temperature
294
+ if (!this.device.waterdetector?.hide_temperature) {
295
+ this.CurrentTemperature = this.OpenAPI_CurrentTemperature!;
296
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Temperature: ${this.CurrentTemperature}°c`);
297
+ }
298
+
299
+ // BatteryLevel
300
+ this.BatteryLevel = Number(this.OpenAPI_BatteryLevel);
301
+ if (this.BatteryLevel < 10) {
302
+ this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
303
+ } else {
304
+ this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
305
+ }
306
+ if (Number.isNaN(this.BatteryLevel)) {
307
+ this.BatteryLevel = 100;
308
+ }
309
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel},`
310
+ + ` StatusLowBattery: ${this.StatusLowBattery}`);
311
+
312
+ // FirmwareRevision
313
+ this.FirmwareRevision = this.OpenAPI_FirmwareRevision!;
314
+ this.accessory.context.FirmwareRevision = this.FirmwareRevision;
315
+ }
316
+
317
+ /**
318
+ * Asks the SwitchBot API for the latest device information
319
+ */
320
+ async refreshStatus(): Promise<void> {
321
+ if (!this.device.enableCloudService && this.OpenAPI) {
322
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} refreshStatus enableCloudService: ${this.device.enableCloudService}`);
323
+ } else if (this.BLE) {
324
+ await this.BLERefreshStatus();
325
+ } else if (this.OpenAPI && this.platform.config.credentials?.token) {
326
+ await this.openAPIRefreshStatus();
327
+ } else {
328
+ await this.offlineOff();
329
+ this.debugWarnLog(
330
+ `${this.device.deviceType}: ${this.accessory.displayName} Connection Type:` +
331
+ ` ${this.device.connectionType}, refreshStatus will not happen.`,
332
+ );
333
+ }
334
+ }
335
+
336
+ async BLERefreshStatus(): Promise<void> {
337
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLERefreshStatus`);
338
+ const switchbot = await this.platform.connectBLE();
339
+ // Convert to BLE Address
340
+ this.device.bleMac = this.device
341
+ .deviceId!.match(/.{1,2}/g)!
342
+ .join(':')
343
+ .toLowerCase();
344
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLE Address: ${this.device.bleMac}`);
345
+ this.getCustomBLEAddress(switchbot);
346
+ // Start to monitor advertisement packets
347
+ (async () => {
348
+ // Start to monitor advertisement packets
349
+ await switchbot.startScan({
350
+ model: 'w',
351
+ id: this.device.bleMac,
352
+ });
353
+ // Set an event handler
354
+ switchbot.onadvertisement = (ad: any) => {
355
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ${JSON.stringify(ad, null, ' ')}`);
356
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} address: ${ad.address}, model: ${ad.serviceData.model}`);
357
+ if (this.device.bleMac === ad.address && ad.serviceData.model === 'w') {
358
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} serviceData: ${JSON.stringify(ad.serviceData)}`);
359
+ this.BLE_CurrentTemperature = ad.serviceData.temperature;
360
+ this.BLE_Celsius = ad.serviceData.temperature!.c;
361
+ this.BLE_Fahrenheit = ad.serviceData.temperature!.f;
362
+ this.BLE_BatteryLevel = ad.serviceData.battery;
363
+ } else {
364
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} serviceData: ${JSON.stringify(ad.serviceData)}`);
365
+ }
366
+ };
367
+ // Wait 1 seconds
368
+ await switchbot.wait(this.scanDuration * 1000);
369
+ // Stop to monitor
370
+ await switchbot.stopScan();
371
+ // Update HomeKit
372
+ await this.BLEparseStatus();
373
+ await this.updateHomeKitCharacteristics();
374
+ })();
375
+ /*if (switchbot !== false) {
376
+ switchbot
377
+ .startScan({
378
+ model: 'w',
379
+ id: this.device.bleMac,
380
+ })
381
+ .then(async () => {
382
+ // Set an event handler
383
+ switchbot.onadvertisement = async (ad: ad) => {
384
+ this.debugLog(
385
+ `${this.device.deviceType}: ${this.accessory.displayName} Config BLE Address: ${this.device.bleMac},` +
386
+ ` BLE Address Found: ${ad.address}`,
387
+ );
388
+ if (ad.serviceData.humidity! > 0) {
389
+ // reject unreliable data
390
+ this.BLE_CurrentRelativeHumidity = ad.serviceData.humidity;
391
+ }
392
+ this.BLE_CurrentTemperature = ad.serviceData.temperature;
393
+ this.BLE_Celsius = ad.serviceData.temperature!.c;
394
+ this.BLE_Fahrenheit = ad.serviceData.temperature!.f;
395
+ this.BLE_BatteryLevel = ad.serviceData.battery;
396
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} serviceData: ${JSON.stringify(ad.serviceData)}`);
397
+ this.debugLog(
398
+ `${this.device.deviceType}: ${this.accessory.displayName} model: ${ad.serviceData.model}, modelName: ${ad.serviceData.modelName}, ` +
399
+ `temperature: ${JSON.stringify(ad.serviceData.temperature?.c)}, humidity: ${ad.serviceData.humidity}, ` +
400
+ `battery: ${ad.serviceData.battery}`,
401
+ );
402
+
403
+ if (ad.serviceData) {
404
+ this.BLE_IsConnected = true;
405
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} connected: ${this.BLE_IsConnected}`);
406
+ await this.stopScanning(switchbot);
407
+ } else {
408
+ this.BLE_IsConnected = false;
409
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} connected: ${this.BLE_IsConnected}`);
410
+ }
411
+ };
412
+ // Wait
413
+ return await sleep(this.scanDuration * 1000);
414
+ })
415
+ .then(async () => {
416
+ // Stop to monitor
417
+ await this.stopScanning(switchbot);
418
+ })
419
+ .catch(async (e: any) => {
420
+ this.apiError(e);
421
+ this.errorLog(
422
+ `${this.device.deviceType}: ${this.accessory.displayName} failed BLERefreshStatus with ${this.device.connectionType}` +
423
+ ` Connection, Error Message: ${JSON.stringify(e.message)}`,
424
+ );
425
+ await this.BLERefreshConnection(switchbot);
426
+ });
427
+ } else {
428
+ await this.BLERefreshConnection(switchbot);
429
+ }*/
430
+ }
431
+
432
+ async openAPIRefreshStatus(): Promise<void> {
433
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIRefreshStatus`);
434
+ try {
435
+ const { body, statusCode } = await request(`${Devices}/${this.device.deviceId}/status`, {
436
+ headers: this.platform.generateHeaders(),
437
+ });
438
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} statusCode: ${statusCode}`);
439
+ const deviceStatus: any = await body.json();
440
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} deviceStatus: ${JSON.stringify(deviceStatus)}`);
441
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} deviceStatus statusCode: ${deviceStatus.statusCode}`);
442
+ if ((statusCode === 200 || statusCode === 100) && (deviceStatus.statusCode === 200 || deviceStatus.statusCode === 100)) {
443
+ this.debugErrorLog(`${this.device.deviceType}: ${this.accessory.displayName} `
444
+ + `statusCode: ${statusCode} & deviceStatus StatusCode: ${deviceStatus.statusCode}`);
445
+ this.OpenAPI_CurrentRelativeHumidity = deviceStatus.body.humidity!;
446
+ this.OpenAPI_CurrentTemperature = deviceStatus.body.temperature!;
447
+ this.OpenAPI_BatteryLevel = deviceStatus.body.battery;
448
+ this.OpenAPI_FirmwareRevision = deviceStatus.body.version;
449
+ this.openAPIparseStatus();
450
+ this.updateHomeKitCharacteristics();
451
+ } else {
452
+ this.statusCode(statusCode);
453
+ this.statusCode(deviceStatus.statusCode);
454
+ }
455
+ } catch (e: any) {
456
+ this.apiError(e);
457
+ this.errorLog(
458
+ `${this.device.deviceType}: ${this.accessory.displayName} failed openAPIRefreshStatus with ${this.device.connectionType}` +
459
+ ` Connection, Error Message: ${JSON.stringify(e.message)}`,
460
+ );
461
+ }
462
+ }
463
+
464
+ /**
465
+ * Updates the status for each of the HomeKit Characteristics
466
+ */
467
+ async updateHomeKitCharacteristics(): Promise<void> {
468
+ const mqttmessage: string[] = [];
469
+ const entry = { time: Math.round(new Date().valueOf() / 1000) };
470
+ if (!this.device.waterdetector?.hide_leak) {
471
+ if (this.LeakDetected === undefined) {
472
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} LeakDetected: ${this.LeakDetected}`);
473
+ } else {
474
+ if (this.device.mqttURL) {
475
+ mqttmessage.push(`"LeakDetected": ${this.LeakDetected}`);
476
+ }
477
+ if (this.device.history) {
478
+ entry['leak'] = this.LeakDetected;
479
+ }
480
+ this.accessory.context.LeakDetected = this.LeakDetected;
481
+ this.leakService?.updateCharacteristic(this.hap.Characteristic.LeakDetected, this.LeakDetected);
482
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic LeakDetected: ${this.LeakDetected}`);
483
+ }
484
+ }
485
+ if (!this.device.waterdetector?.hide_humidity) {
486
+ if (this.CurrentRelativeHumidity === undefined) {
487
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} CurrentRelativeHumidity: ${this.CurrentRelativeHumidity}`);
488
+ } else {
489
+ this.accessory.context.CurrentRelativeHumidity = this.CurrentRelativeHumidity;
490
+ this.humidityservice?.updateCharacteristic(this.hap.Characteristic.CurrentRelativeHumidity, this.CurrentRelativeHumidity);
491
+ this.debugLog(
492
+ `${this.device.deviceType}: ${this.accessory.displayName}` +
493
+ ` updateCharacteristic CurrentRelativeHumidity: ${this.CurrentRelativeHumidity}`,
494
+ );
495
+ if (this.device.mqttURL) {
496
+ mqttmessage.push(`"humidity": ${this.CurrentRelativeHumidity}`);
497
+ }
498
+ if (this.device.history) {
499
+ entry['humidity'] = this.CurrentRelativeHumidity;
500
+ }
501
+ }
502
+ }
503
+ if (!this.device.waterdetector?.hide_temperature) {
504
+ if (this.CurrentTemperature === undefined) {
505
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} CurrentTemperature: ${this.CurrentTemperature}`);
506
+ } else {
507
+ if (this.device.mqttURL) {
508
+ mqttmessage.push(`"temperature": ${this.CurrentTemperature}`);
509
+ }
510
+ if (this.device.history) {
511
+ entry['temp'] = this.CurrentTemperature;
512
+ }
513
+ this.accessory.context.CurrentTemperature = this.CurrentTemperature;
514
+ this.temperatureservice?.updateCharacteristic(this.hap.Characteristic.CurrentTemperature, this.CurrentTemperature);
515
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic CurrentTemperature: ${this.CurrentTemperature}`);
516
+ }
517
+ }
518
+ if (this.BatteryLevel === undefined) {
519
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel}`);
520
+ } else {
521
+ if (this.device.mqttURL) {
522
+ mqttmessage.push(`"battery": ${this.BatteryLevel}`);
523
+ }
524
+ this.accessory.context.BatteryLevel = this.BatteryLevel;
525
+ this.batteryService?.updateCharacteristic(this.hap.Characteristic.BatteryLevel, this.BatteryLevel);
526
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic BatteryLevel: ${this.BatteryLevel}`);
527
+ }
528
+ if (this.StatusLowBattery === undefined) {
529
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} StatusLowBattery: ${this.StatusLowBattery}`);
530
+ } else {
531
+ if (this.device.mqttURL) {
532
+ mqttmessage.push(`"lowBattery": ${this.StatusLowBattery}`);
533
+ }
534
+ this.accessory.context.StatusLowBattery = this.StatusLowBattery;
535
+ this.batteryService?.updateCharacteristic(this.hap.Characteristic.StatusLowBattery, this.StatusLowBattery);
536
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic StatusLowBattery: ${this.StatusLowBattery}`);
537
+ }
538
+ if (this.device.mqttURL) {
539
+ this.mqttPublish(`{${mqttmessage.join(',')}}`);
540
+ }
541
+ if (Number(this.CurrentRelativeHumidity) > 0) {
542
+ // reject unreliable data
543
+ if (this.device.history) {
544
+ this.historyService?.addEntry(entry);
545
+ }
546
+ }
547
+ }
548
+
549
+ /*
550
+ * Publish MQTT message for topics of
551
+ * 'homebridge-switchbot/meter/xx:xx:xx:xx:xx:xx'
552
+ */
553
+ mqttPublish(message: any) {
554
+ const mac = this.device.deviceId
555
+ ?.toLowerCase()
556
+ .match(/[\s\S]{1,2}/g)
557
+ ?.join(':');
558
+ const options = this.device.mqttPubOptions || {};
559
+ this.mqttClient?.publish(`homebridge-switchbot/meter/${mac}`, `${message}`, options);
560
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} MQTT message: ${message} options:${JSON.stringify(options)}`);
561
+ }
562
+
563
+ /*
564
+ * Setup MQTT hadler if URL is specified.
565
+ */
566
+ async setupMqtt(device: device & devicesConfig): Promise<void> {
567
+ if (device.mqttURL) {
568
+ try {
569
+ const { connectAsync } = asyncmqtt;
570
+ this.mqttClient = await connectAsync(device.mqttURL, device.mqttOptions || {});
571
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} MQTT connection has been established successfully.`);
572
+ this.mqttClient.on('error', (e: Error) => {
573
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Failed to publish MQTT messages. ${e}`);
574
+ });
575
+ } catch (e) {
576
+ this.mqttClient = null;
577
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Failed to establish MQTT connection. ${e}`);
578
+ }
579
+ }
580
+ }
581
+
582
+ /*
583
+ * Setup EVE history graph feature if enabled.
584
+ */
585
+ async setupHistoryService(device: device & devicesConfig): Promise<void> {
586
+ const mac = this.device
587
+ .deviceId!.match(/.{1,2}/g)!
588
+ .join(':')
589
+ .toLowerCase();
590
+ this.historyService = device.history
591
+ ? new this.platform.fakegatoAPI('room', this.accessory, {
592
+ log: this.platform.log,
593
+ storage: 'fs',
594
+ filename: `${hostname().split('.')[0]}_${mac}_persist.json`,
595
+ })
596
+ : null;
597
+ }
598
+
599
+ async stopScanning(switchbot: any) {
600
+ switchbot.stopScan();
601
+ if (this.BLE_IsConnected) {
602
+ await this.BLEparseStatus();
603
+ await this.updateHomeKitCharacteristics();
604
+ } else {
605
+ await this.BLERefreshConnection(switchbot);
606
+ }
607
+ }
608
+
609
+ async getCustomBLEAddress(switchbot: any) {
610
+ if (this.device.customBLEaddress && this.deviceLogging.includes('debug')) {
611
+ (async () => {
612
+ // Start to monitor advertisement packets
613
+ await switchbot.startScan({
614
+ model: 'i',
615
+ });
616
+ // Set an event handler
617
+ switchbot.onadvertisement = (ad: any) => {
618
+ this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} ad: ${JSON.stringify(ad, null, ' ')}`);
619
+ };
620
+ await sleep(10000);
621
+ // Stop to monitor
622
+ switchbot.stopScan();
623
+ })();
624
+ }
625
+ }
626
+
627
+ async BLERefreshConnection(switchbot: any): Promise<void> {
628
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} wasn't able to establish BLE Connection, node-switchbot:`
629
+ + ` ${JSON.stringify(switchbot)}`);
630
+ if (this.platform.config.credentials?.token && this.device.connectionType === 'BLE/OpenAPI') {
631
+ this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} Using OpenAPI Connection to Refresh Status`);
632
+ await this.openAPIRefreshStatus();
633
+ }
634
+ }
635
+
636
+ async scan(device: device & devicesConfig): Promise<void> {
637
+ if (device.scanDuration) {
638
+ this.scanDuration = this.accessory.context.scanDuration = device.scanDuration;
639
+ if (this.BLE) {
640
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config scanDuration: ${this.scanDuration}`);
641
+ }
642
+ } else {
643
+ this.scanDuration = this.accessory.context.scanDuration = 1;
644
+ if (this.BLE) {
645
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Default scanDuration: ${this.scanDuration}`);
646
+ }
647
+ }
648
+ }
649
+
650
+ async statusCode(statusCode: number): Promise<void> {
651
+ switch (statusCode) {
652
+ case 151:
653
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Command not supported by this deviceType, statusCode: ${statusCode}`);
654
+ break;
655
+ case 152:
656
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Device not found, statusCode: ${statusCode}`);
657
+ break;
658
+ case 160:
659
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Command is not supported, statusCode: ${statusCode}`);
660
+ break;
661
+ case 161:
662
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Device is offline, statusCode: ${statusCode}`);
663
+ this.offlineOff();
664
+ break;
665
+ case 171:
666
+ this.errorLog(
667
+ `${this.device.deviceType}: ${this.accessory.displayName} Hub Device is offline, statusCode: ${statusCode}. ` +
668
+ `Hub: ${this.device.hubDeviceId}`,
669
+ );
670
+ this.offlineOff();
671
+ break;
672
+ case 190:
673
+ this.errorLog(
674
+ `${this.device.deviceType}: ${this.accessory.displayName} Device internal error due to device states not synchronized with server,` +
675
+ ` Or command format is invalid, statusCode: ${statusCode}`,
676
+ );
677
+ break;
678
+ case 100:
679
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Command successfully sent, statusCode: ${statusCode}`);
680
+ break;
681
+ case 200:
682
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Request successful, statusCode: ${statusCode}`);
683
+ break;
684
+ case 400:
685
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Bad Request, The client has issued an invalid request. `
686
+ + `This is commonly used to specify validation errors in a request payload, statusCode: ${statusCode}`);
687
+ break;
688
+ case 401:
689
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Unauthorized, Authorization for the API is required, `
690
+ + `but the request has not been authenticated, statusCode: ${statusCode}`);
691
+ break;
692
+ case 403:
693
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Forbidden, The request has been authenticated but does not `
694
+ + `have appropriate permissions, or a requested resource is not found, statusCode: ${statusCode}`);
695
+ break;
696
+ case 404:
697
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Not Found, Specifies the requested path does not exist, `
698
+ + `statusCode: ${statusCode}`);
699
+ break;
700
+ case 406:
701
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Not Acceptable, The client has requested a MIME type via `
702
+ + `the Accept header for a value not supported by the server, statusCode: ${statusCode}`);
703
+ break;
704
+ case 415:
705
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Unsupported Media Type, The client has defined a contentType `
706
+ + `header that is not supported by the server, statusCode: ${statusCode}`);
707
+ break;
708
+ case 422:
709
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Unprocessable Entity, The client has made a valid request, `
710
+ + `but the server cannot process it. This is often used for APIs for which certain limits have been exceeded, statusCode: ${statusCode}`);
711
+ break;
712
+ case 429:
713
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Too Many Requests, The client has exceeded the number of `
714
+ + `requests allowed for a given time window, statusCode: ${statusCode}`);
715
+ break;
716
+ case 500:
717
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Internal Server Error, An unexpected error on the SmartThings `
718
+ + `servers has occurred. These errors should be rare, statusCode: ${statusCode}`);
719
+ break;
720
+ default:
721
+ this.infoLog(
722
+ `${this.device.deviceType}: ${this.accessory.displayName} Unknown statusCode: ` +
723
+ `${statusCode}, Submit Bugs Here: ' + 'https://tinyurl.com/SwitchBotBug`,
724
+ );
725
+ }
726
+ }
727
+
728
+ async offlineOff(): Promise<void> {
729
+ if (this.device.offline) {
730
+ await this.deviceContext();
731
+ await this.updateHomeKitCharacteristics();
732
+ }
733
+ }
734
+
735
+ async apiError(e: any): Promise<void> {
736
+ if (!this.device.waterdetector?.hide_leak) {
737
+ this.leakService?.updateCharacteristic(this.hap.Characteristic.LeakDetected, e);
738
+ }
739
+ if (!this.device.waterdetector?.hide_humidity) {
740
+ this.humidityservice?.updateCharacteristic(this.hap.Characteristic.CurrentRelativeHumidity, e);
741
+ }
742
+ if (!this.device.waterdetector?.hide_temperature) {
743
+ this.temperatureservice?.updateCharacteristic(this.hap.Characteristic.CurrentTemperature, e);
744
+ }
745
+ this.batteryService?.updateCharacteristic(this.hap.Characteristic.BatteryLevel, e);
746
+ this.batteryService?.updateCharacteristic(this.hap.Characteristic.StatusLowBattery, e);
747
+ }
748
+
749
+ async deviceContext() {
750
+ if (this.CurrentRelativeHumidity === undefined) {
751
+ this.CurrentRelativeHumidity = 0;
752
+ } else {
753
+ this.CurrentRelativeHumidity = this.accessory.context.CurrentRelativeHumidity;
754
+ }
755
+ if (this.CurrentTemperature === undefined) {
756
+ this.CurrentTemperature = 0;
757
+ } else {
758
+ this.CurrentTemperature = this.accessory.context.CurrentTemperature;
759
+ }
760
+ if (this.BatteryLevel === undefined) {
761
+ this.BatteryLevel = 100;
762
+ } else {
763
+ this.BatteryLevel = this.accessory.context.BatteryLevel;
764
+ }
765
+ if (this.StatusLowBattery === undefined) {
766
+ this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
767
+ this.accessory.context.StatusLowBattery = this.StatusLowBattery;
768
+ } else {
769
+ this.StatusLowBattery = this.accessory.context.StatusLowBattery;
770
+ }
771
+ if (this.FirmwareRevision === undefined) {
772
+ this.FirmwareRevision = this.platform.version;
773
+ this.accessory.context.FirmwareRevision = this.FirmwareRevision;
774
+ }
775
+ }
776
+
777
+ async refreshRate(device: device & devicesConfig): Promise<void> {
778
+ if (device.refreshRate) {
779
+ this.deviceRefreshRate = this.accessory.context.refreshRate = device.refreshRate;
780
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config refreshRate: ${this.deviceRefreshRate}`);
781
+ } else if (this.platform.config.options!.refreshRate) {
782
+ this.deviceRefreshRate = this.accessory.context.refreshRate = this.platform.config.options!.refreshRate;
783
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Platform Config refreshRate: ${this.deviceRefreshRate}`);
784
+ }
785
+ }
786
+
787
+ async deviceConfig(device: device & devicesConfig): Promise<void> {
788
+ let config = {};
789
+ if (device.waterdetector) {
790
+ config = device.waterdetector;
791
+ }
792
+ if (device.connectionType !== undefined) {
793
+ config['connectionType'] = device.connectionType;
794
+ }
795
+ if (device.external !== undefined) {
796
+ config['external'] = device.external;
797
+ }
798
+ if (device.mqttURL !== undefined) {
799
+ config['mqttURL'] = device.mqttURL;
800
+ }
801
+ if (device.logging !== undefined) {
802
+ config['logging'] = device.logging;
803
+ }
804
+ if (device.refreshRate !== undefined) {
805
+ config['refreshRate'] = device.refreshRate;
806
+ }
807
+ if (device.scanDuration !== undefined) {
808
+ config['scanDuration'] = device.scanDuration;
809
+ }
810
+ if (device.webhook !== undefined) {
811
+ config['webhook'] = device.webhook;
812
+ }
813
+ if (Object.entries(config).length !== 0) {
814
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} Config: ${JSON.stringify(config)}`);
815
+ }
816
+ }
817
+
818
+ async deviceLogs(device: device & devicesConfig): Promise<void> {
819
+ if (this.platform.debugMode) {
820
+ this.deviceLogging = this.accessory.context.logging = 'debugMode';
821
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Debug Mode Logging: ${this.deviceLogging}`);
822
+ } else if (device.logging) {
823
+ this.deviceLogging = this.accessory.context.logging = device.logging;
824
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config Logging: ${this.deviceLogging}`);
825
+ } else if (this.platform.config.options?.logging) {
826
+ this.deviceLogging = this.accessory.context.logging = this.platform.config.options?.logging;
827
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Platform Config Logging: ${this.deviceLogging}`);
828
+ } else {
829
+ this.deviceLogging = this.accessory.context.logging = 'standard';
830
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Logging Not Set, Using: ${this.deviceLogging}`);
831
+ }
832
+ }
833
+
834
+ /**
835
+ * Logging for Device
836
+ */
837
+ infoLog(...log: any[]): void {
838
+ if (this.enablingDeviceLogging()) {
839
+ this.platform.log.info(String(...log));
840
+ }
841
+ }
842
+
843
+ warnLog(...log: any[]): void {
844
+ if (this.enablingDeviceLogging()) {
845
+ this.platform.log.warn(String(...log));
846
+ }
847
+ }
848
+
849
+ debugWarnLog(...log: any[]): void {
850
+ if (this.enablingDeviceLogging()) {
851
+ if (this.deviceLogging?.includes('debug')) {
852
+ this.platform.log.warn('[DEBUG]', String(...log));
853
+ }
854
+ }
855
+ }
856
+
857
+ errorLog(...log: any[]): void {
858
+ if (this.enablingDeviceLogging()) {
859
+ this.platform.log.error(String(...log));
860
+ }
861
+ }
862
+
863
+ debugErrorLog(...log: any[]): void {
864
+ if (this.enablingDeviceLogging()) {
865
+ if (this.deviceLogging?.includes('debug')) {
866
+ this.platform.log.error('[DEBUG]', String(...log));
867
+ }
868
+ }
869
+ }
870
+
871
+ debugLog(...log: any[]): void {
872
+ if (this.enablingDeviceLogging()) {
873
+ if (this.deviceLogging === 'debug') {
874
+ this.platform.log.info('[DEBUG]', String(...log));
875
+ } else {
876
+ this.platform.log.debug(String(...log));
877
+ }
878
+ }
879
+ }
880
+
881
+ enablingDeviceLogging(): boolean {
882
+ return this.deviceLogging.includes('debug') || this.deviceLogging === 'standard';
883
+ }
884
+ }