@switchbot/homebridge-switchbot 3.5.0-beta.3 → 3.5.0-beta.31

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 (166) hide show
  1. package/CHANGELOG.md +4 -1
  2. package/config.schema.json +147 -9
  3. package/dist/device/blindtilt.d.ts +21 -94
  4. package/dist/device/blindtilt.d.ts.map +1 -1
  5. package/dist/device/blindtilt.js +347 -756
  6. package/dist/device/blindtilt.js.map +1 -1
  7. package/dist/device/bot.d.ts +25 -71
  8. package/dist/device/bot.d.ts.map +1 -1
  9. package/dist/device/bot.js +582 -759
  10. package/dist/device/bot.js.map +1 -1
  11. package/dist/device/ceilinglight.d.ts +13 -67
  12. package/dist/device/ceilinglight.d.ts.map +1 -1
  13. package/dist/device/ceilinglight.js +209 -587
  14. package/dist/device/ceilinglight.js.map +1 -1
  15. package/dist/device/colorbulb.d.ts +13 -74
  16. package/dist/device/colorbulb.d.ts.map +1 -1
  17. package/dist/device/colorbulb.js +250 -632
  18. package/dist/device/colorbulb.js.map +1 -1
  19. package/dist/device/contact.d.ts +14 -65
  20. package/dist/device/contact.d.ts.map +1 -1
  21. package/dist/device/contact.js +204 -531
  22. package/dist/device/contact.js.map +1 -1
  23. package/dist/device/curtain.d.ts +17 -86
  24. package/dist/device/curtain.d.ts.map +1 -1
  25. package/dist/device/curtain.js +335 -786
  26. package/dist/device/curtain.js.map +1 -1
  27. package/dist/device/device.d.ts +59 -0
  28. package/dist/device/device.d.ts.map +1 -0
  29. package/dist/device/device.js +654 -0
  30. package/dist/device/device.js.map +1 -0
  31. package/dist/device/fan.d.ts +51 -0
  32. package/dist/device/fan.d.ts.map +1 -0
  33. package/dist/device/fan.js +499 -0
  34. package/dist/device/fan.js.map +1 -0
  35. package/dist/device/hub.d.ts +15 -59
  36. package/dist/device/hub.d.ts.map +1 -1
  37. package/dist/device/hub.js +242 -596
  38. package/dist/device/hub.js.map +1 -1
  39. package/dist/device/humidifier.d.ts +10 -65
  40. package/dist/device/humidifier.d.ts.map +1 -1
  41. package/dist/device/humidifier.js +207 -571
  42. package/dist/device/humidifier.js.map +1 -1
  43. package/dist/device/iosensor.d.ts +11 -64
  44. package/dist/device/iosensor.d.ts.map +1 -1
  45. package/dist/device/iosensor.js +174 -584
  46. package/dist/device/iosensor.js.map +1 -1
  47. package/dist/device/lightstrip.d.ts +10 -68
  48. package/dist/device/lightstrip.d.ts.map +1 -1
  49. package/dist/device/lightstrip.js +252 -568
  50. package/dist/device/lightstrip.js.map +1 -1
  51. package/dist/device/lock.d.ts +15 -62
  52. package/dist/device/lock.d.ts.map +1 -1
  53. package/dist/device/lock.js +210 -542
  54. package/dist/device/lock.js.map +1 -1
  55. package/dist/device/meter.d.ts +13 -63
  56. package/dist/device/meter.d.ts.map +1 -1
  57. package/dist/device/meter.js +170 -577
  58. package/dist/device/meter.js.map +1 -1
  59. package/dist/device/meterplus.d.ts +13 -64
  60. package/dist/device/meterplus.d.ts.map +1 -1
  61. package/dist/device/meterplus.js +159 -577
  62. package/dist/device/meterplus.js.map +1 -1
  63. package/dist/device/motion.d.ts +13 -69
  64. package/dist/device/motion.d.ts.map +1 -1
  65. package/dist/device/motion.js +136 -518
  66. package/dist/device/motion.js.map +1 -1
  67. package/dist/device/plug.d.ts +9 -57
  68. package/dist/device/plug.d.ts.map +1 -1
  69. package/dist/device/plug.js +82 -452
  70. package/dist/device/plug.js.map +1 -1
  71. package/dist/device/robotvacuumcleaner.d.ts +11 -62
  72. package/dist/device/robotvacuumcleaner.d.ts.map +1 -1
  73. package/dist/device/robotvacuumcleaner.js +140 -451
  74. package/dist/device/robotvacuumcleaner.js.map +1 -1
  75. package/dist/device/waterdetector.d.ts +9 -70
  76. package/dist/device/waterdetector.d.ts.map +1 -1
  77. package/dist/device/waterdetector.js +121 -664
  78. package/dist/device/waterdetector.js.map +1 -1
  79. package/dist/index.js +1 -1
  80. package/dist/irdevice/airconditioner.d.ts +8 -48
  81. package/dist/irdevice/airconditioner.d.ts.map +1 -1
  82. package/dist/irdevice/airconditioner.js +309 -419
  83. package/dist/irdevice/airconditioner.js.map +1 -1
  84. package/dist/irdevice/airpurifier.d.ts +7 -38
  85. package/dist/irdevice/airpurifier.d.ts.map +1 -1
  86. package/dist/irdevice/airpurifier.js +72 -304
  87. package/dist/irdevice/airpurifier.js.map +1 -1
  88. package/dist/irdevice/camera.d.ts +6 -35
  89. package/dist/irdevice/camera.d.ts.map +1 -1
  90. package/dist/irdevice/camera.js +34 -278
  91. package/dist/irdevice/camera.js.map +1 -1
  92. package/dist/irdevice/fan.d.ts +6 -39
  93. package/dist/irdevice/fan.d.ts.map +1 -1
  94. package/dist/irdevice/fan.js +67 -311
  95. package/dist/irdevice/fan.js.map +1 -1
  96. package/dist/irdevice/irdevice.d.ts +40 -0
  97. package/dist/irdevice/irdevice.d.ts.map +1 -0
  98. package/dist/irdevice/irdevice.js +509 -0
  99. package/dist/irdevice/irdevice.js.map +1 -0
  100. package/dist/irdevice/light.d.ts +6 -34
  101. package/dist/irdevice/light.d.ts.map +1 -1
  102. package/dist/irdevice/light.js +23 -272
  103. package/dist/irdevice/light.js.map +1 -1
  104. package/dist/irdevice/other.d.ts +18 -47
  105. package/dist/irdevice/other.d.ts.map +1 -1
  106. package/dist/irdevice/other.js +352 -546
  107. package/dist/irdevice/other.js.map +1 -1
  108. package/dist/irdevice/tv.d.ts +7 -39
  109. package/dist/irdevice/tv.d.ts.map +1 -1
  110. package/dist/irdevice/tv.js +82 -321
  111. package/dist/irdevice/tv.js.map +1 -1
  112. package/dist/irdevice/vacuumcleaner.d.ts +6 -35
  113. package/dist/irdevice/vacuumcleaner.d.ts.map +1 -1
  114. package/dist/irdevice/vacuumcleaner.js +41 -284
  115. package/dist/irdevice/vacuumcleaner.js.map +1 -1
  116. package/dist/irdevice/waterheater.d.ts +6 -35
  117. package/dist/irdevice/waterheater.d.ts.map +1 -1
  118. package/dist/irdevice/waterheater.js +42 -287
  119. package/dist/irdevice/waterheater.js.map +1 -1
  120. package/dist/platform.d.ts +14 -1
  121. package/dist/platform.d.ts.map +1 -1
  122. package/dist/platform.js +237 -94
  123. package/dist/platform.js.map +1 -1
  124. package/dist/settings.d.ts +40 -10
  125. package/dist/settings.d.ts.map +1 -1
  126. package/dist/settings.js +0 -552
  127. package/dist/settings.js.map +1 -1
  128. package/dist/utils.d.ts +77 -0
  129. package/dist/utils.d.ts.map +1 -1
  130. package/dist/utils.js +638 -1
  131. package/dist/utils.js.map +1 -1
  132. package/package.json +16 -15
  133. package/src/custom.d.ts +2 -1
  134. package/src/device/blindtilt.ts +373 -782
  135. package/src/device/bot.ts +616 -844
  136. package/src/device/ceilinglight.ts +222 -607
  137. package/src/device/colorbulb.ts +264 -656
  138. package/src/device/contact.ts +229 -553
  139. package/src/device/curtain.ts +355 -810
  140. package/src/device/device.ts +681 -0
  141. package/src/device/fan.ts +548 -0
  142. package/src/device/hub.ts +268 -623
  143. package/src/device/humidifier.ts +237 -618
  144. package/src/device/iosensor.ts +200 -610
  145. package/src/device/lightstrip.ts +273 -596
  146. package/src/device/lock.ts +247 -582
  147. package/src/device/meter.ts +196 -601
  148. package/src/device/meterplus.ts +184 -602
  149. package/src/device/motion.ts +156 -541
  150. package/src/device/plug.ts +92 -480
  151. package/src/device/robotvacuumcleaner.ts +161 -477
  152. package/src/device/waterdetector.ts +139 -689
  153. package/src/index.ts +1 -1
  154. package/src/irdevice/airconditioner.ts +330 -446
  155. package/src/irdevice/airpurifier.ts +89 -321
  156. package/src/irdevice/camera.ts +42 -293
  157. package/src/irdevice/fan.ts +78 -327
  158. package/src/irdevice/irdevice.ts +526 -0
  159. package/src/irdevice/light.ts +32 -287
  160. package/src/irdevice/other.ts +396 -615
  161. package/src/irdevice/tv.ts +100 -339
  162. package/src/irdevice/vacuumcleaner.ts +49 -305
  163. package/src/irdevice/waterheater.ts +50 -310
  164. package/src/platform.ts +247 -102
  165. package/src/settings.ts +56 -565
  166. package/src/utils.ts +642 -1
@@ -1,198 +1,94 @@
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';
1
+ /* Copyright(C) 2021-2024, donavanbecker (https://github.com/donavanbecker). All rights reserved.
2
+ *
3
+ * waterdetector.ts: @switchbot/homebridge-switchbot.
4
+ */
5
+ import { deviceBase } from './device.js';
6
6
  import { interval, Subject } from 'rxjs';
7
7
  import { skipWhile } from 'rxjs/operators';
8
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';
9
+ import { Service, PlatformAccessory, CharacteristicValue } from 'homebridge';
10
+ import { device, devicesConfig, serviceData, deviceStatus, Devices } from '../settings.js';
11
11
 
12
12
  /**
13
13
  * Platform Accessory
14
14
  * An instance of this class is created for each accessory your platform registers
15
15
  * Each accessory may expose multiple services of different service types.
16
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;
17
+ export class WaterDetector extends deviceBase {
22
18
  // 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;
19
+ private Battery: {
20
+ Service: Service;
21
+ BatteryLevel: CharacteristicValue;
22
+ StatusLowBattery: CharacteristicValue;
23
+ ChargingState: CharacteristicValue;
24
+ };
25
+
26
+ private LeakSensor?: {
27
+ Service: Service;
28
+ StatusActive: CharacteristicValue;
29
+ LeakDetected: CharacteristicValue;
30
+ };
64
31
 
65
32
  // Updates
66
33
  WaterDetectorUpdateInProgress!: boolean;
67
34
  doWaterDetectorUpdate: Subject<void>;
68
35
 
69
- // Connection
70
- private readonly OpenAPI: boolean;
71
- private readonly BLE: boolean;
72
-
73
36
  constructor(
74
- private readonly platform: SwitchBotPlatform,
75
- private accessory: PlatformAccessory,
76
- public device: device & devicesConfig,
37
+ readonly platform: SwitchBotPlatform,
38
+ accessory: PlatformAccessory,
39
+ device: device & devicesConfig,
77
40
  ) {
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';
41
+ super(platform, accessory, device);
85
42
  // default placeholders
86
- this.deviceLogs(device);
87
- this.scan(device);
88
- this.refreshRate(device);
89
- this.deviceContext();
90
43
  this.setupHistoryService(device);
91
- this.setupMqtt(device);
92
- this.deviceConfig(device);
93
44
 
94
45
  // this is subject we use to track when we need to POST changes to the SwitchBot API
95
46
  this.doWaterDetectorUpdate = new Subject();
96
47
  this.WaterDetectorUpdateInProgress = false;
97
48
 
49
+ // Initialize Battery property
50
+ this.Battery = {
51
+ Service: accessory.getService(this.hap.Service.Battery)!,
52
+ BatteryLevel: accessory.context.BatteryLevel || 100,
53
+ StatusLowBattery: accessory.context.StatusLowBattery || this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL,
54
+ ChargingState: accessory.context.ChargingState || this.hap.Characteristic.ChargingState.NOT_CHARGEABLE,
55
+ };
56
+
57
+ // Initialize Leak Sensor property
58
+ if (!this.device.waterdetector?.hide_leak) {
59
+ this.LeakSensor = {
60
+ Service: accessory.getService(this.hap.Service.LeakSensor)!,
61
+ StatusActive: accessory.context.StatusActive || false,
62
+ LeakDetected: accessory.context.LeakDetected || this.hap.Characteristic.LeakDetected.LEAK_NOT_DETECTED,
63
+ };
64
+ }
65
+
98
66
  // Retrieve initial values and updateHomekit
99
67
  this.refreshStatus();
100
68
 
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
69
  // Leak Sensor Service
110
70
  if (device.waterdetector?.hide_leak) {
111
71
  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) {
72
+ this.LeakSensor!.Service = this.accessory.getService(this.hap.Service.LeakSensor) as Service;
73
+ accessory.removeService(this.LeakSensor!.Service);
74
+ } else if (!this.LeakSensor?.Service) {
115
75
  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;
76
+ const LeakSensorService = `${accessory.displayName} Leak Sensor`;
77
+ (this.LeakSensor!.Service = this.accessory.getService(this.hap.Service.LeakSensor)
78
+ || this.accessory.addService(this.hap.Service.LeakSensor)), LeakSensorService;
119
79
 
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
- }
80
+ this.LeakSensor!.Service.setCharacteristic(this.hap.Characteristic.Name, LeakSensorService);
124
81
  } else {
125
82
  this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Leak Sensor Service Not Added`);
126
83
  }
127
84
 
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
85
  // 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;
86
+ const BatteryService = `${accessory.displayName} Battery`;
87
+ (this.Battery.Service = this.accessory.getService(this.hap.Service.Battery)
88
+ || accessory.addService(this.hap.Service.Battery)), BatteryService;
190
89
 
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);
90
+ this.Battery.Service.setCharacteristic(this.hap.Characteristic.Name, BatteryService);
91
+ this.Battery.Service.setCharacteristic(this.hap.Characteristic.ChargingState, this.hap.Characteristic.ChargingState.NOT_CHARGEABLE);
196
92
 
197
93
  // Retrieve initial values and updateHomekit
198
94
  this.updateHomeKitCharacteristics();
@@ -205,22 +101,21 @@ export class WaterDetector {
205
101
  });
206
102
 
207
103
  //regisiter webhook event handler
208
- if (this.device.webhook) {
209
- this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} is listening webhook.`);
104
+ if (device.webhook && !this.device.waterdetector?.hide_leak) {
105
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} is listening webhook.`);
210
106
  this.platform.webhookEventHandler[this.device.deviceId] = async (context) => {
211
107
  try {
212
108
  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
- }
109
+ const { detectionState, battery } = context;
110
+ const { LeakDetected } = this.LeakSensor!;
111
+ const { BatteryLevel } = this.Battery!;
112
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ` +
113
+ '(detectionState, battery) = ' +
114
+ `Webhook:(${detectionState}, ${battery}), ` +
115
+ `current:(${LeakDetected}, ${BatteryLevel})`);
116
+ this.LeakSensor!.LeakDetected = detectionState;
117
+ this.Battery!.BatteryLevel = battery;
118
+ this.updateHomeKitCharacteristics();
224
119
  } catch (e: any) {
225
120
  this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} `
226
121
  + `failed to handle webhook. Received: ${JSON.stringify(context)} Error: ${e}`);
@@ -229,94 +124,56 @@ export class WaterDetector {
229
124
  }
230
125
  }
231
126
 
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> {
127
+ async BLEparseStatus(serviceData: serviceData): Promise<void> {
251
128
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLEparseStatus`);
252
-
253
129
  // Battery
254
- this.BatteryLevel = Number(this.BLE_BatteryLevel);
255
- if (this.BatteryLevel < 15) {
256
- this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
130
+ this.Battery.BatteryLevel = Number(serviceData.battery);
131
+ if (this.Battery.BatteryLevel < 15) {
132
+ this.Battery.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
257
133
  } else {
258
- this.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
134
+ this.Battery.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
259
135
  }
260
- this.debugLog(`${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel}, StatusLowBattery: ${this.StatusLowBattery}`);
136
+ this.debugLog(`${this.accessory.displayName} BatteryLevel: ${this.Battery.BatteryLevel}, StatusLowBattery: ${this.Battery.StatusLowBattery}`);
261
137
 
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`);
138
+ // LeakDetected
139
+ if (this.device.waterdetector?.hide_leak) {
140
+ this.LeakSensor!.LeakDetected = serviceData.status!;
141
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} LeakDetected: ${this.LeakSensor!.LeakDetected}`);
273
142
  }
274
143
  }
275
144
 
276
- async openAPIparseStatus(): Promise<void> {
145
+ async openAPIparseStatus(deviceStatus: deviceStatus): Promise<void> {
277
146
  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;
147
+ // StatusLowBattery
148
+ this.Battery.BatteryLevel = Number(deviceStatus.body.battery);
149
+ if (this.Battery.BatteryLevel < 10) {
150
+ this.Battery.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
282
151
  } 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`);
152
+ this.Battery.StatusLowBattery = this.hap.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
297
153
  }
154
+ this.debugLog(`${this.accessory.displayName} BatteryLevel: ${this.Battery.BatteryLevel}, StatusLowBattery: ${this.Battery.StatusLowBattery}`);
298
155
 
299
156
  // 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;
157
+ if (Number.isNaN(this.Battery.BatteryLevel)) {
158
+ this.Battery.BatteryLevel = 100;
305
159
  }
306
- if (Number.isNaN(this.BatteryLevel)) {
307
- this.BatteryLevel = 100;
160
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.Battery.BatteryLevel}`);
161
+
162
+ // LeakDetected
163
+ if (!this.device.waterdetector?.hide_leak) {
164
+ this.LeakSensor!.LeakDetected = deviceStatus.body.status!;
165
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} LeakDetected: ${this.LeakSensor!.LeakDetected}`);
308
166
  }
309
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel},`
310
- + ` StatusLowBattery: ${this.StatusLowBattery}`);
311
167
 
312
168
  // FirmwareRevision
313
- this.FirmwareRevision = this.OpenAPI_FirmwareRevision!;
314
- this.accessory.context.FirmwareRevision = this.FirmwareRevision;
169
+ this.accessory.context.FirmwareRevision = deviceStatus.body.version;
170
+ this.accessory
171
+ .getService(this.hap.Service.AccessoryInformation)!
172
+ .setCharacteristic(this.hap.Characteristic.FirmwareRevision, this.accessory.context.FirmwareRevision)
173
+ .getCharacteristic(this.hap.Characteristic.FirmwareRevision)
174
+ .updateValue(this.accessory.context.FirmwareRevision);
315
175
  }
316
176
 
317
- /**
318
- * Asks the SwitchBot API for the latest device information
319
- */
320
177
  async refreshStatus(): Promise<void> {
321
178
  if (!this.device.enableCloudService && this.OpenAPI) {
322
179
  this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} refreshStatus enableCloudService: ${this.device.enableCloudService}`);
@@ -346,107 +203,43 @@ export class WaterDetector {
346
203
  // Start to monitor advertisement packets
347
204
  (async () => {
348
205
  // Start to monitor advertisement packets
349
- await switchbot.startScan({
350
- model: 'w',
351
- id: this.device.bleMac,
352
- });
206
+ await switchbot.startScan({ model: this.device.bleModel, id: this.device.bleMac });
353
207
  // Set an event handler
354
208
  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') {
209
+ if (this.device.bleMac === ad.address && ad.model === this.device.bleModel) {
210
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} ${JSON.stringify(ad, null, ' ')}`);
211
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} address: ${ad.address}, model: ${ad.model}`);
358
212
  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
213
  } else {
364
214
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} serviceData: ${JSON.stringify(ad.serviceData)}`);
365
215
  }
366
216
  };
367
- // Wait 1 seconds
217
+ // Wait 10 seconds
368
218
  await switchbot.wait(this.scanDuration * 1000);
369
219
  // Stop to monitor
370
220
  await switchbot.stopScan();
371
221
  // Update HomeKit
372
- await this.BLEparseStatus();
222
+ await this.BLEparseStatus(switchbot.onadvertisement.serviceData);
373
223
  await this.updateHomeKitCharacteristics();
374
224
  })();
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 {
225
+ if (switchbot === undefined) {
428
226
  await this.BLERefreshConnection(switchbot);
429
- }*/
227
+ }
430
228
  }
431
229
 
432
230
  async openAPIRefreshStatus(): Promise<void> {
433
231
  this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIRefreshStatus`);
434
232
  try {
435
- const { body, statusCode } = await request(`${Devices}/${this.device.deviceId}/status`, {
436
- headers: this.platform.generateHeaders(),
437
- });
233
+ const { body, statusCode } = await this.platform.retryRequest(this.deviceMaxRetries, this.deviceDelayBetweenRetries,
234
+ `${Devices}/${this.device.deviceId}/status`, { headers: this.platform.generateHeaders() });
438
235
  this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} statusCode: ${statusCode}`);
439
236
  const deviceStatus: any = await body.json();
440
237
  this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} deviceStatus: ${JSON.stringify(deviceStatus)}`);
441
238
  this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} deviceStatus statusCode: ${deviceStatus.statusCode}`);
442
239
  if ((statusCode === 200 || statusCode === 100) && (deviceStatus.statusCode === 200 || deviceStatus.statusCode === 100)) {
443
- this.debugErrorLog(`${this.device.deviceType}: ${this.accessory.displayName} `
240
+ this.debugSuccessLog(`${this.device.deviceType}: ${this.accessory.displayName} `
444
241
  + `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();
242
+ this.openAPIparseStatus(deviceStatus);
450
243
  this.updateHomeKitCharacteristics();
451
244
  } else {
452
245
  this.statusCode(statusCode);
@@ -468,162 +261,54 @@ export class WaterDetector {
468
261
  const mqttmessage: string[] = [];
469
262
  const entry = { time: Math.round(new Date().valueOf() / 1000) };
470
263
  if (!this.device.waterdetector?.hide_leak) {
471
- if (this.LeakDetected === undefined) {
472
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} LeakDetected: ${this.LeakDetected}`);
264
+ if (this.LeakSensor!.LeakDetected === undefined) {
265
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} LeakDetected: ${this.LeakSensor!.LeakDetected}`);
473
266
  } else {
474
267
  if (this.device.mqttURL) {
475
- mqttmessage.push(`"LeakDetected": ${this.LeakDetected}`);
268
+ mqttmessage.push(`"LeakDetected": ${this.LeakSensor!.LeakDetected}`);
476
269
  }
477
270
  if (this.device.history) {
478
- entry['leak'] = this.LeakDetected;
271
+ entry['leak'] = this.LeakSensor!.LeakDetected;
479
272
  }
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}`);
273
+ this.accessory.context.LeakDetected = this.LeakSensor!.LeakDetected;
274
+ this.LeakSensor!.Service.updateCharacteristic(this.hap.Characteristic.LeakDetected, this.LeakSensor!.LeakDetected);
275
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic LeakDetected: ${this.LeakSensor!.LeakDetected}`);
483
276
  }
484
277
  }
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}`);
278
+ if (this.Battery.BatteryLevel === undefined) {
279
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.Battery.BatteryLevel}`);
520
280
  } else {
521
281
  if (this.device.mqttURL) {
522
- mqttmessage.push(`"battery": ${this.BatteryLevel}`);
282
+ mqttmessage.push(`"battery": ${this.Battery.BatteryLevel}`);
523
283
  }
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}`);
284
+ this.accessory.context.BatteryLevel = this.Battery.BatteryLevel;
285
+ this.Battery.Service.updateCharacteristic(this.hap.Characteristic.BatteryLevel, this.Battery.BatteryLevel);
286
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic BatteryLevel: ${this.Battery.BatteryLevel}`);
527
287
  }
528
- if (this.StatusLowBattery === undefined) {
529
- this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} StatusLowBattery: ${this.StatusLowBattery}`);
288
+ if (this.Battery.StatusLowBattery === undefined) {
289
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} StatusLowBattery: ${this.Battery.StatusLowBattery}`);
530
290
  } else {
531
291
  if (this.device.mqttURL) {
532
- mqttmessage.push(`"lowBattery": ${this.StatusLowBattery}`);
292
+ mqttmessage.push(`"lowBattery": ${this.Battery.StatusLowBattery}`);
533
293
  }
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}`);
294
+ this.accessory.context.StatusLowBattery = this.Battery.StatusLowBattery;
295
+ this.Battery.Service.updateCharacteristic(this.hap.Characteristic.StatusLowBattery, this.Battery.StatusLowBattery);
296
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic`
297
+ + ` StatusLowBattery: ${this.Battery.StatusLowBattery}`);
537
298
  }
538
299
  if (this.device.mqttURL) {
539
300
  this.mqttPublish(`{${mqttmessage.join(',')}}`);
540
301
  }
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}`);
302
+ if (!this.device.waterdetector?.hide_leak) {
303
+ if (Number(this.LeakSensor!.LeakDetected) > 0) {
304
+ // reject unreliable data
305
+ if (this.device.history) {
306
+ this.historyService?.addEntry(entry);
307
+ }
578
308
  }
579
309
  }
580
310
  }
581
311
 
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
312
  async BLERefreshConnection(switchbot: any): Promise<void> {
628
313
  this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} wasn't able to establish BLE Connection, node-switchbot:`
629
314
  + ` ${JSON.stringify(switchbot)}`);
@@ -633,252 +318,17 @@ export class WaterDetector {
633
318
  }
634
319
  }
635
320
 
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
321
  async offlineOff(): Promise<void> {
729
- if (this.device.offline) {
730
- await this.deviceContext();
731
- await this.updateHomeKitCharacteristics();
322
+ if (this.device.offline && !this.device.waterdetector?.hide_leak) {
323
+ this.LeakSensor!.Service.updateCharacteristic(this.hap.Characteristic.LeakDetected, this.hap.Characteristic.LeakDetected.LEAK_NOT_DETECTED);
732
324
  }
733
325
  }
734
326
 
735
327
  async apiError(e: any): Promise<void> {
736
328
  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}`);
329
+ this.LeakSensor!.Service.updateCharacteristic(this.hap.Characteristic.LeakDetected, e);
784
330
  }
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';
331
+ this.Battery.Service.updateCharacteristic(this.hap.Characteristic.BatteryLevel, e);
332
+ this.Battery.Service.updateCharacteristic(this.hap.Characteristic.StatusLowBattery, e);
883
333
  }
884
334
  }