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