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