@switchbot/homebridge-switchbot 2.5.3-beta.8 → 2.5.3

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 (76) hide show
  1. package/.github/ISSUE_TEMPLATE/bug-report.yml +7 -7
  2. package/CHANGELOG.md +13 -0
  3. package/config.schema.json +6 -2
  4. package/dist/device/blindtilt.d.ts +1 -1
  5. package/dist/device/blindtilt.d.ts.map +1 -1
  6. package/dist/device/blindtilt.js +15 -17
  7. package/dist/device/blindtilt.js.map +1 -1
  8. package/dist/device/bot.d.ts +1 -1
  9. package/dist/device/bot.d.ts.map +1 -1
  10. package/dist/device/bot.js +12 -14
  11. package/dist/device/bot.js.map +1 -1
  12. package/dist/device/ceilinglight.d.ts +1 -1
  13. package/dist/device/ceilinglight.d.ts.map +1 -1
  14. package/dist/device/ceilinglight.js +10 -12
  15. package/dist/device/ceilinglight.js.map +1 -1
  16. package/dist/device/colorbulb.d.ts +1 -1
  17. package/dist/device/colorbulb.d.ts.map +1 -1
  18. package/dist/device/colorbulb.js +16 -18
  19. package/dist/device/colorbulb.js.map +1 -1
  20. package/dist/device/curtain.d.ts +1 -1
  21. package/dist/device/curtain.d.ts.map +1 -1
  22. package/dist/device/curtain.js +34 -37
  23. package/dist/device/curtain.js.map +1 -1
  24. package/dist/device/humidifier.js +2 -2
  25. package/dist/device/humidifier.js.map +1 -1
  26. package/dist/device/iosensor.d.ts +94 -0
  27. package/dist/device/iosensor.d.ts.map +1 -0
  28. package/dist/device/iosensor.js +692 -0
  29. package/dist/device/iosensor.js.map +1 -0
  30. package/dist/device/meter.js +1 -1
  31. package/dist/device/meter.js.map +1 -1
  32. package/dist/device/meterplus.d.ts +1 -0
  33. package/dist/device/meterplus.d.ts.map +1 -1
  34. package/dist/device/meterplus.js +2 -1
  35. package/dist/device/meterplus.js.map +1 -1
  36. package/dist/device/motion.d.ts +1 -1
  37. package/dist/device/motion.d.ts.map +1 -1
  38. package/dist/device/motion.js +7 -9
  39. package/dist/device/motion.js.map +1 -1
  40. package/dist/device/plug.d.ts +1 -1
  41. package/dist/device/plug.d.ts.map +1 -1
  42. package/dist/device/plug.js +10 -12
  43. package/dist/device/plug.js.map +1 -1
  44. package/dist/device/robotvacuumcleaner.d.ts +1 -1
  45. package/dist/device/robotvacuumcleaner.d.ts.map +1 -1
  46. package/dist/device/robotvacuumcleaner.js +10 -12
  47. package/dist/device/robotvacuumcleaner.js.map +1 -1
  48. package/dist/device/striplight.d.ts +1 -1
  49. package/dist/device/striplight.d.ts.map +1 -1
  50. package/dist/device/striplight.js +14 -16
  51. package/dist/device/striplight.js.map +1 -1
  52. package/dist/irdevice/airpurifier.js +1 -1
  53. package/dist/irdevice/airpurifier.js.map +1 -1
  54. package/dist/platform.d.ts +1 -0
  55. package/dist/platform.d.ts.map +1 -1
  56. package/dist/platform.js +58 -0
  57. package/dist/platform.js.map +1 -1
  58. package/homebridge-ui/public/index.html +1 -1
  59. package/package.json +13 -13
  60. package/src/device/blindtilt.ts +15 -17
  61. package/src/device/bot.ts +12 -14
  62. package/src/device/ceilinglight.ts +10 -12
  63. package/src/device/colorbulb.ts +16 -18
  64. package/src/device/curtain.ts +35 -39
  65. package/src/device/humidifier.ts +2 -2
  66. package/src/device/iosensor.ts +747 -0
  67. package/src/device/meter.ts +1 -1
  68. package/src/device/meterplus.ts +3 -1
  69. package/src/device/motion.ts +7 -9
  70. package/src/device/plug.ts +10 -12
  71. package/src/device/robotvacuumcleaner.ts +10 -12
  72. package/src/device/striplight.ts +14 -16
  73. package/src/irdevice/airpurifier.ts +1 -1
  74. package/src/platform.ts +61 -0
  75. package/src/settings.ts +3 -3
  76. package/.github/npm-version-script.js +0 -81
@@ -0,0 +1,747 @@
1
+ import https from 'https';
2
+ import crypto from 'crypto';
3
+ import { Context } from 'vm';
4
+ import { hostname } from 'os';
5
+ import { MqttClient } from 'mqtt';
6
+ import { connectAsync } from 'async-mqtt';
7
+ import { interval, Subject } from 'rxjs';
8
+ import { skipWhile } from 'rxjs/operators';
9
+ import superStringify from 'super-stringify';
10
+ import { SwitchBotPlatform } from '../platform';
11
+ import { Service, PlatformAccessory, Units, CharacteristicValue } from 'homebridge';
12
+ import { device, devicesConfig, serviceData, ad, switchbot, temperature, deviceStatus, HostDomain, DevicePath } from '../settings';
13
+ import { IncomingMessage } from 'http';
14
+ import { sleep } from '../utils';
15
+
16
+ /**
17
+ * Platform Accessory
18
+ * An instance of this class is created for each accessory your platform registers
19
+ * Each accessory may expose multiple services of different service types.
20
+ */
21
+ export class IOSensor {
22
+ // Services
23
+ batteryService?: Service;
24
+ temperatureservice?: Service;
25
+ humidityservice?: Service;
26
+
27
+ // Characteristic Values
28
+ CurrentRelativeHumidity!: CharacteristicValue;
29
+ CurrentTemperature?: CharacteristicValue;
30
+ BatteryLevel?: CharacteristicValue;
31
+ ChargingState?: CharacteristicValue;
32
+ StatusLowBattery?: CharacteristicValue;
33
+
34
+ // OpenAPI Others
35
+ Battery: deviceStatus['battery'];
36
+ Temperature: deviceStatus['temperature'];
37
+ Humidity: deviceStatus['humidity'];
38
+ deviceStatus!: any; //deviceStatusResponse;
39
+
40
+ // BLE Others
41
+ connected?: boolean;
42
+ switchbot!: switchbot;
43
+ serviceData!: serviceData;
44
+ address!: ad['address'];
45
+ temperature!: serviceData['temperature'];
46
+ celsius!: temperature['c'];
47
+ fahrenheit!: temperature['f'];
48
+ battery!: serviceData['battery'];
49
+ humidity!: serviceData['humidity'];
50
+
51
+ //MQTT stuff
52
+ mqttClient: MqttClient | null = null;
53
+
54
+ // EVE history service handler
55
+ historyService?: any;
56
+
57
+ // Config
58
+ scanDuration!: number;
59
+ deviceLogging!: string;
60
+ deviceRefreshRate!: number;
61
+
62
+ // Updates
63
+ ioSensorUpdateInProgress!: boolean;
64
+ doIOSensorUpdate: Subject<void>;
65
+
66
+ // Connection
67
+ private readonly BLE = (this.device.connectionType === 'BLE' || this.device.connectionType === 'BLE/OpenAPI');
68
+ private readonly OpenAPI = (this.device.connectionType === 'OpenAPI' || this.device.connectionType === 'BLE/OpenAPI');
69
+
70
+ constructor(private readonly platform: SwitchBotPlatform, private accessory: PlatformAccessory, public device: device & devicesConfig) {
71
+ // default placeholders
72
+ this.logs(device);
73
+ this.scan(device);
74
+ this.refreshRate(device);
75
+ this.config(device);
76
+ this.context();
77
+ this.setupHistoryService(device);
78
+ this.setupMqtt(device);
79
+
80
+ // this is subject we use to track when we need to POST changes to the SwitchBot API
81
+ this.doIOSensorUpdate = new Subject();
82
+ this.ioSensorUpdateInProgress = false;
83
+
84
+ // Retrieve initial values and updateHomekit
85
+ this.refreshStatus();
86
+
87
+ // set accessory information
88
+ accessory
89
+ .getService(this.platform.Service.AccessoryInformation)!
90
+ .setCharacteristic(this.platform.Characteristic.Manufacturer, 'SwitchBot')
91
+ .setCharacteristic(this.platform.Characteristic.Model, 'WoIOSensor')
92
+ .setCharacteristic(this.platform.Characteristic.SerialNumber, device.deviceId!)
93
+ .setCharacteristic(this.platform.Characteristic.FirmwareRevision, this.FirmwareRevision(accessory, device))
94
+ .getCharacteristic(this.platform.Characteristic.FirmwareRevision)
95
+ .updateValue(this.FirmwareRevision(accessory, device));
96
+
97
+ // Temperature Sensor Service
98
+ if (device.meter?.hide_temperature) {
99
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Removing Temperature Sensor Service`);
100
+ this.temperatureservice = this.accessory.getService(this.platform.Service.TemperatureSensor);
101
+ accessory.removeService(this.temperatureservice!);
102
+ } else if (!this.temperatureservice) {
103
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Add Temperature Sensor Service`);
104
+ (this.temperatureservice =
105
+ this.accessory.getService(this.platform.Service.TemperatureSensor) || this.accessory.addService(this.platform.Service.TemperatureSensor)),
106
+ `${accessory.displayName} Temperature Sensor`;
107
+
108
+ this.temperatureservice.setCharacteristic(this.platform.Characteristic.Name, `${accessory.displayName} Temperature Sensor`);
109
+ if (!this.temperatureservice.testCharacteristic(this.platform.Characteristic.ConfiguredName)) {
110
+ this.temperatureservice.addCharacteristic(this.platform.Characteristic.ConfiguredName, `${accessory.displayName} Temperature Sensor`);
111
+ }
112
+ this.temperatureservice
113
+ .getCharacteristic(this.platform.Characteristic.CurrentTemperature)
114
+ .setProps({
115
+ unit: Units['CELSIUS'],
116
+ validValueRanges: [-273.15, 100],
117
+ minValue: -273.15,
118
+ maxValue: 100,
119
+ minStep: 0.1,
120
+ })
121
+ .onGet(() => {
122
+ return this.CurrentTemperature!;
123
+ });
124
+ } else {
125
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Temperature Sensor Service Not Added`);
126
+ }
127
+
128
+ // Humidity Sensor Service
129
+ if (device.meter?.hide_humidity) {
130
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Removing Humidity Sensor Service`);
131
+ this.humidityservice = this.accessory.getService(this.platform.Service.HumiditySensor);
132
+ accessory.removeService(this.humidityservice!);
133
+ } else if (!this.humidityservice) {
134
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Add Humidity Sensor Service`);
135
+ (this.humidityservice =
136
+ this.accessory.getService(this.platform.Service.HumiditySensor) || this.accessory.addService(this.platform.Service.HumiditySensor)),
137
+ `${accessory.displayName} Humidity Sensor`;
138
+
139
+ this.humidityservice.setCharacteristic(this.platform.Characteristic.Name, `${accessory.displayName} Humidity Sensor`);
140
+ if (!this.humidityservice.testCharacteristic(this.platform.Characteristic.ConfiguredName)) {
141
+ this.humidityservice.addCharacteristic(this.platform.Characteristic.ConfiguredName, `${accessory.displayName} Humidity Sensor`);
142
+ }
143
+ this.humidityservice
144
+ .getCharacteristic(this.platform.Characteristic.CurrentRelativeHumidity)
145
+ .setProps({
146
+ minStep: 0.1,
147
+ })
148
+ .onGet(() => {
149
+ return this.CurrentRelativeHumidity;
150
+ });
151
+ } else {
152
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Humidity Sensor Service Not Added`);
153
+ }
154
+
155
+ // Battery Service
156
+ (this.batteryService = this.accessory.getService(this.platform.Service.Battery) || this.accessory.addService(this.platform.Service.Battery)),
157
+ `${accessory.displayName} Battery`;
158
+
159
+ this.batteryService.setCharacteristic(this.platform.Characteristic.Name, `${accessory.displayName} Battery`);
160
+ if (!this.batteryService.testCharacteristic(this.platform.Characteristic.ConfiguredName)) {
161
+ this.batteryService.addCharacteristic(this.platform.Characteristic.ConfiguredName, `${accessory.displayName} Battery`);
162
+ }
163
+ this.batteryService.setCharacteristic(this.platform.Characteristic.ChargingState, this.platform.Characteristic.ChargingState.NOT_CHARGEABLE);
164
+
165
+ // Retrieve initial values and updateHomekit
166
+ this.updateHomeKitCharacteristics();
167
+
168
+ // Start an update interval
169
+ interval(this.deviceRefreshRate * 1000)
170
+ .pipe(skipWhile(() => this.ioSensorUpdateInProgress))
171
+ .subscribe(async () => {
172
+ await this.refreshStatus();
173
+ });
174
+ }
175
+
176
+ /**
177
+ * Parse the device status from the SwitchBot api
178
+ */
179
+ async parseStatus(): Promise<void> {
180
+ if (!this.device.enableCloudService && this.OpenAPI) {
181
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} parseStatus enableCloudService: ${this.device.enableCloudService}`);
182
+ } else if (this.BLE) {
183
+ await this.BLEparseStatus();
184
+ } else if (this.OpenAPI && this.platform.config.credentials?.token) {
185
+ await this.openAPIparseStatus();
186
+ } else {
187
+ await this.offlineOff();
188
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} Connection Type:`
189
+ + ` ${this.device.connectionType}, parseStatus will not happen.`);
190
+ }
191
+ }
192
+
193
+ async BLEparseStatus(): Promise<void> {
194
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLEparseStatus`);
195
+
196
+ // Battery
197
+ this.BatteryLevel = Number(this.battery);
198
+ if (this.BatteryLevel < 15) {
199
+ this.StatusLowBattery = this.platform.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
200
+ } else {
201
+ this.StatusLowBattery = this.platform.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
202
+ }
203
+ this.debugLog(`${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel}, StatusLowBattery: ${this.StatusLowBattery}`);
204
+
205
+ // Humidity
206
+ if (!this.device.meter?.hide_humidity) {
207
+ this.CurrentRelativeHumidity = this.humidity!;
208
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Humidity: ${this.CurrentRelativeHumidity}%`);
209
+ }
210
+
211
+ // Current Temperature
212
+ if (!this.device.meter?.hide_temperature) {
213
+ this.celsius < 0 ? 0 : this.celsius > 100 ? 100 : this.celsius;
214
+ this.CurrentTemperature = this.celsius;
215
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Temperature: ${this.CurrentTemperature}°c`);
216
+ }
217
+ }
218
+
219
+
220
+ async openAPIparseStatus(): Promise<void> {
221
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIparseStatus`);
222
+ // Battery
223
+ this.BatteryLevel = Number(this.Battery);
224
+ if (this.BatteryLevel < 15) {
225
+ this.StatusLowBattery = this.platform.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
226
+ } else {
227
+ this.StatusLowBattery = this.platform.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
228
+ }
229
+ this.debugLog(`${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel}, StatusLowBattery: ${this.StatusLowBattery}`);
230
+
231
+ // Current Relative Humidity
232
+ if (!this.device.meter?.hide_humidity) {
233
+ this.CurrentRelativeHumidity = this.Humidity!;
234
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Humidity: ${this.CurrentRelativeHumidity}%`);
235
+ }
236
+
237
+ // Current Temperature
238
+ if (!this.device.meter?.hide_temperature) {
239
+ this.CurrentTemperature = this.Temperature!;
240
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Temperature: ${this.CurrentTemperature}°c`);
241
+ }
242
+ }
243
+
244
+ /**
245
+ * Asks the SwitchBot API for the latest device information
246
+ */
247
+ async refreshStatus(): Promise<void> {
248
+ if (!this.device.enableCloudService && this.OpenAPI) {
249
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} refreshStatus enableCloudService: ${this.device.enableCloudService}`);
250
+ } else if (this.BLE) {
251
+ await this.BLERefreshStatus();
252
+ } else if (this.OpenAPI && this.platform.config.credentials?.token) {
253
+ await this.openAPIRefreshStatus();
254
+ } else {
255
+ await this.offlineOff();
256
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} Connection Type:`
257
+ + ` ${this.device.connectionType}, refreshStatus will not happen.`);
258
+ }
259
+ }
260
+
261
+ async BLERefreshStatus(): Promise<void> {
262
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLERefreshStatus`);
263
+ const switchbot = await this.platform.connectBLE();
264
+ // Convert to BLE Address
265
+ this.device.bleMac = this.device
266
+ .deviceId!.match(/.{1,2}/g)!
267
+ .join(':')
268
+ .toLowerCase();
269
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLE Address: ${this.device.bleMac}`);
270
+ this.getCustomBLEAddress(switchbot);
271
+ // Start to monitor advertisement packets
272
+ if (switchbot !== false) {
273
+ switchbot
274
+ .startScan({
275
+ model: 'i',
276
+ id: this.device.bleMac,
277
+ })
278
+ .then(async () => {
279
+ // Set an event hander
280
+ switchbot.onadvertisement = async (ad: ad) => {
281
+ this.address = ad.address;
282
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Config BLE Address: ${this.device.bleMac},`
283
+ + ` BLE Address Found: ${this.address}`);
284
+ if (ad.serviceData.humidity! > 0) {
285
+ // reject unreliable data
286
+ this.humidity = ad.serviceData.humidity;
287
+ }
288
+ this.serviceData = ad.serviceData;
289
+ this.temperature = ad.serviceData.temperature;
290
+ this.celsius = ad.serviceData.temperature!.c;
291
+ this.fahrenheit = ad.serviceData.temperature!.f;
292
+ this.battery = ad.serviceData.battery;
293
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} serviceData: ${superStringify(ad.serviceData)}`);
294
+ this.debugLog(
295
+ `${this.device.deviceType}: ${this.accessory.displayName} model: ${ad.serviceData.model}, modelName: ${ad.serviceData.modelName}, ` +
296
+ `temperature: ${superStringify(ad.serviceData.temperature?.c)}, humidity: ${ad.serviceData.humidity}, ` +
297
+ `battery: ${ad.serviceData.battery}`,
298
+ );
299
+
300
+ if (this.serviceData) {
301
+ this.connected = true;
302
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} connected: ${this.connected}`);
303
+ await this.stopScanning(switchbot);
304
+ } else {
305
+ this.connected = false;
306
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} connected: ${this.connected}`);
307
+ }
308
+ };
309
+ // Wait
310
+ return await sleep(this.scanDuration * 1000);
311
+ })
312
+ .then(async () => {
313
+ // Stop to monitor
314
+ await this.stopScanning(switchbot);
315
+ })
316
+ .catch(async (e: any) => {
317
+ this.apiError(e);
318
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} failed BLERefreshStatus with ${this.device.connectionType}`
319
+ + ` Connection, Error Message: ${superStringify(e.message)}`);
320
+ await this.BLERefreshConnection(switchbot);
321
+ });
322
+ } else {
323
+ await this.BLERefreshConnection(switchbot);
324
+ }
325
+ }
326
+
327
+ async openAPIRefreshStatus(): Promise<void> {
328
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIRefreshStatus`);
329
+ try {
330
+ const t = Date.now();
331
+ const nonce = 'requestID';
332
+ const data = this.platform.config.credentials?.token + t + nonce;
333
+ const signTerm = crypto.createHmac('sha256', this.platform.config.credentials?.secret).update(Buffer.from(data, 'utf-8')).digest();
334
+ const sign = signTerm.toString('base64');
335
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} sign: ${sign}`);
336
+ const options = {
337
+ hostname: HostDomain,
338
+ port: 443,
339
+ path: `${DevicePath}/${this.device.deviceId}/status`,
340
+ method: 'GET',
341
+ headers: {
342
+ Authorization: this.platform.config.credentials?.token,
343
+ sign: sign,
344
+ nonce: nonce,
345
+ t: t,
346
+ 'Content-Type': 'application/json',
347
+ },
348
+ };
349
+ const req = https.request(options, (res) => {
350
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIRefreshStatus statusCode: ${res.statusCode}`);
351
+ let rawData = '';
352
+ res.on('data', (d) => {
353
+ rawData += d;
354
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} d: ${d}`);
355
+ });
356
+ res.on('end', () => {
357
+ try {
358
+ this.deviceStatus = JSON.parse(rawData);
359
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIRefreshStatus: ${superStringify(this.deviceStatus)}`);
360
+ this.Humidity = this.deviceStatus.body.humidity!;
361
+ this.Temperature = this.deviceStatus.body.temperature!;
362
+ this.Battery = this.deviceStatus.body.battery!;
363
+ this.parseStatus();
364
+ this.updateHomeKitCharacteristics();
365
+ } catch (e: any) {
366
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} error message: ${e.message}`);
367
+ }
368
+ });
369
+ });
370
+ req.on('error', (e: any) => {
371
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} error message: ${e.message}`);
372
+ });
373
+ req.end();
374
+ } catch (e: any) {
375
+ this.apiError(e);
376
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} failed openAPIRefreshStatus with ${this.device.connectionType}`
377
+ + ` Connection, Error Message: ${superStringify(e.message)}`);
378
+ }
379
+ }
380
+
381
+ /**
382
+ * Updates the status for each of the HomeKit Characteristics
383
+ */
384
+ async updateHomeKitCharacteristics(): Promise<void> {
385
+ const mqttmessage: string[] = [];
386
+ const entry = { time: Math.round(new Date().valueOf() / 1000) };
387
+ if (!this.device.meter?.hide_humidity) {
388
+ if (this.CurrentRelativeHumidity === undefined) {
389
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} CurrentRelativeHumidity: ${this.CurrentRelativeHumidity}`);
390
+ } else {
391
+ this.accessory.context.CurrentRelativeHumidity = this.CurrentRelativeHumidity;
392
+ this.humidityservice?.updateCharacteristic(this.platform.Characteristic.CurrentRelativeHumidity, this.CurrentRelativeHumidity);
393
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName}`
394
+ + ` updateCharacteristic CurrentRelativeHumidity: ${this.CurrentRelativeHumidity}`);
395
+ if (this.device.mqttURL) {
396
+ mqttmessage.push(`"humidity": ${this.CurrentRelativeHumidity}`);
397
+ }
398
+ if (this.device.history) {
399
+ entry['humidity'] = this.CurrentRelativeHumidity;
400
+ }
401
+ }
402
+ }
403
+ if (!this.device.meter?.hide_temperature) {
404
+ if (this.CurrentTemperature === undefined) {
405
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} CurrentTemperature: ${this.CurrentTemperature}`);
406
+ } else {
407
+ if (this.device.mqttURL) {
408
+ mqttmessage.push(`"temperature": ${this.CurrentTemperature}`);
409
+ }
410
+ if (this.device.history){
411
+ entry['temp'] = this.CurrentTemperature;
412
+ }
413
+ this.accessory.context.CurrentTemperature = this.CurrentTemperature;
414
+ this.temperatureservice?.updateCharacteristic(this.platform.Characteristic.CurrentTemperature, this.CurrentTemperature);
415
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic CurrentTemperature: ${this.CurrentTemperature}`);
416
+ }
417
+ }
418
+ if (this.BatteryLevel === undefined) {
419
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel}`);
420
+ } else {
421
+ if (this.device.mqttURL) {
422
+ mqttmessage.push(`"battery": ${this.BatteryLevel}`);
423
+ }
424
+ this.accessory.context.BatteryLevel = this.BatteryLevel;
425
+ this.batteryService?.updateCharacteristic(this.platform.Characteristic.BatteryLevel, this.BatteryLevel);
426
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic BatteryLevel: ${this.BatteryLevel}`);
427
+ }
428
+ if (this.StatusLowBattery === undefined) {
429
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} StatusLowBattery: ${this.StatusLowBattery}`);
430
+ } else {
431
+ if (this.device.mqttURL) {
432
+ mqttmessage.push(`"lowBattery": ${this.StatusLowBattery}`);
433
+ }
434
+ this.accessory.context.StatusLowBattery = this.StatusLowBattery;
435
+ this.batteryService?.updateCharacteristic(this.platform.Characteristic.StatusLowBattery, this.StatusLowBattery);
436
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic StatusLowBattery: ${this.StatusLowBattery}`);
437
+ }
438
+ if (this.device.mqttURL) {
439
+ this.mqttPublish(`{${mqttmessage.join(',')}}`);
440
+ }
441
+ if (Number(this.CurrentRelativeHumidity) > 0) {
442
+ // reject unreliable data
443
+ if (this.device.history) {
444
+ this.historyService?.addEntry(entry);
445
+ }
446
+ }
447
+ }
448
+
449
+ /*
450
+ * Publish MQTT message for topics of
451
+ * 'homebridge-switchbot/meter/xx:xx:xx:xx:xx:xx'
452
+ */
453
+ mqttPublish(message: any) {
454
+ const mac = this.device.deviceId
455
+ ?.toLowerCase()
456
+ .match(/[\s\S]{1,2}/g)
457
+ ?.join(':');
458
+ const options = this.device.mqttPubOptions || {};
459
+ this.mqttClient?.publish(`homebridge-switchbot/meter/${mac}`, `${message}`, options);
460
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} MQTT message: ${message} options:${superStringify(options)}`);
461
+ }
462
+
463
+ /*
464
+ * Setup MQTT hadler if URL is specifed.
465
+ */
466
+ async setupMqtt(device: device & devicesConfig): Promise<void> {
467
+ if (device.mqttURL) {
468
+ try {
469
+ this.mqttClient = await connectAsync(device.mqttURL, device.mqttOptions || {});
470
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} MQTT connection has been established successfully.`);
471
+ this.mqttClient.on('error', (e: Error) => {
472
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Failed to publish MQTT messages. ${e}`);
473
+ });
474
+ } catch (e) {
475
+ this.mqttClient = null;
476
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Failed to establish MQTT connection. ${e}`);
477
+ }
478
+ }
479
+ }
480
+
481
+ /*
482
+ * Setup EVE history graph feature if enabled.
483
+ */
484
+ async setupHistoryService(device: device & devicesConfig): Promise<void> {
485
+ const mac = this.device
486
+ .deviceId!.match(/.{1,2}/g)!
487
+ .join(':')
488
+ .toLowerCase();
489
+ this.historyService = device.history
490
+ ? new this.platform.fakegatoAPI('room', this.accessory, {
491
+ log: this.platform.log,
492
+ storage: 'fs',
493
+ filename: `${hostname().split('.')[0]}_${mac}_persist.json`,
494
+ })
495
+ : null;
496
+ }
497
+
498
+ async stopScanning(switchbot: any) {
499
+ switchbot.stopScan();
500
+ if (this.connected) {
501
+ await this.BLEparseStatus();
502
+ await this.updateHomeKitCharacteristics();
503
+ } else {
504
+ await this.BLERefreshConnection(switchbot);
505
+ }
506
+ }
507
+
508
+ async getCustomBLEAddress(switchbot: any) {
509
+ if (this.device.customBLEaddress && this.deviceLogging.includes('debug')) {
510
+ (async () => {
511
+ // Start to monitor advertisement packets
512
+ await switchbot.startScan({
513
+ model: 'i',
514
+ });
515
+ // Set an event handler
516
+ switchbot.onadvertisement = (ad: any) => {
517
+ this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} ad: ${superStringify(ad, null, ' ')}`);
518
+ };
519
+ await sleep(10000);
520
+ // Stop to monitor
521
+ switchbot.stopScan();
522
+ })();
523
+ }
524
+ }
525
+
526
+ async BLERefreshConnection(switchbot: any): Promise<void> {
527
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} wasn't able to establish BLE Connection, node-switchbot: ${switchbot}`);
528
+ if (this.platform.config.credentials?.token && this.device.connectionType === 'BLE/OpenAPI') {
529
+ this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} Using OpenAPI Connection to Refresh Status`);
530
+ await this.openAPIRefreshStatus();
531
+ }
532
+ }
533
+
534
+ async scan(device: device & devicesConfig): Promise<void> {
535
+ if (device.scanDuration) {
536
+ this.scanDuration = this.accessory.context.scanDuration = device.scanDuration;
537
+ if (this.BLE) {
538
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config scanDuration: ${this.scanDuration}`);
539
+ }
540
+ } else {
541
+ this.scanDuration = this.accessory.context.scanDuration = 1;
542
+ if (this.BLE) {
543
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Default scanDuration: ${this.scanDuration}`);
544
+ }
545
+ }
546
+ }
547
+
548
+ async statusCode({ res }: { res: IncomingMessage }): Promise<void> {
549
+ switch (res.statusCode) {
550
+ case 151:
551
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Command not supported by this device type.`);
552
+ break;
553
+ case 152:
554
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Device not found.`);
555
+ break;
556
+ case 160:
557
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Command is not supported.`);
558
+ break;
559
+ case 161:
560
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Device is offline.`);
561
+ await this.offlineOff();
562
+ break;
563
+ case 171:
564
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} is offline. Hub: ${this.device.hubDeviceId}`);
565
+ await this.offlineOff();
566
+ break;
567
+ case 190:
568
+ this.errorLog(
569
+ `${this.device.deviceType}: ${this.accessory.displayName} Device internal error due to device states not synchronized with server,` +
570
+ ` Or command: ${superStringify(res)} format is invalid`,
571
+ );
572
+ break;
573
+ case 100:
574
+ if (this.platform.debugMode) {
575
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Command successfully sent.`);
576
+ }
577
+ break;
578
+ default:
579
+ if (this.platform.debugMode) {
580
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Unknown statusCode.`);
581
+ }
582
+ }
583
+ }
584
+
585
+ async offlineOff(): Promise<void> {
586
+ if (this.device.offline) {
587
+ await this.context();
588
+ await this.updateHomeKitCharacteristics();
589
+ }
590
+ }
591
+
592
+ async apiError(e: any): Promise<void> {
593
+ if (!this.device.meter?.hide_humidity) {
594
+ this.humidityservice?.updateCharacteristic(this.platform.Characteristic.CurrentRelativeHumidity, e);
595
+ }
596
+ if (!this.device.meter?.hide_temperature) {
597
+ this.temperatureservice?.updateCharacteristic(this.platform.Characteristic.CurrentTemperature, e);
598
+ }
599
+ this.batteryService?.updateCharacteristic(this.platform.Characteristic.BatteryLevel, e);
600
+ this.batteryService?.updateCharacteristic(this.platform.Characteristic.StatusLowBattery, e);
601
+ }
602
+
603
+ FirmwareRevision(accessory: PlatformAccessory<Context>, device: device & devicesConfig): CharacteristicValue {
604
+ let FirmwareRevision: string;
605
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName}`
606
+ + ` accessory.context.FirmwareRevision: ${accessory.context.FirmwareRevision}`);
607
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} device.firmware: ${device.firmware}`);
608
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} this.platform.version: ${this.platform.version}`);
609
+ if (accessory.context.FirmwareRevision) {
610
+ FirmwareRevision = accessory.context.FirmwareRevision;
611
+ } else if (device.firmware) {
612
+ FirmwareRevision = device.firmware;
613
+ } else {
614
+ FirmwareRevision = this.platform.version;
615
+ }
616
+ return FirmwareRevision;
617
+ }
618
+
619
+ async context() {
620
+ if (this.CurrentRelativeHumidity === undefined) {
621
+ this.CurrentRelativeHumidity = 0;
622
+ } else {
623
+ this.CurrentRelativeHumidity = this.accessory.context.CurrentRelativeHumidity;
624
+ }
625
+ if (this.CurrentTemperature === undefined) {
626
+ this.CurrentTemperature = 0;
627
+ } else {
628
+ this.CurrentTemperature = this.accessory.context.CurrentTemperature;
629
+ }
630
+ if (this.BatteryLevel === undefined) {
631
+ this.BatteryLevel = 100;
632
+ } else {
633
+ this.BatteryLevel = this.accessory.context.BatteryLevel;
634
+ }
635
+ if (this.StatusLowBattery === undefined) {
636
+ this.StatusLowBattery = this.platform.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
637
+ this.accessory.context.StatusLowBattery = this.StatusLowBattery;
638
+ } else {
639
+ this.StatusLowBattery = this.accessory.context.StatusLowBattery;
640
+ }
641
+ }
642
+
643
+ async refreshRate(device: device & devicesConfig): Promise<void> {
644
+ if (device.refreshRate) {
645
+ this.deviceRefreshRate = this.accessory.context.refreshRate = device.refreshRate;
646
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config refreshRate: ${this.deviceRefreshRate}`);
647
+ } else if (this.platform.config.options!.refreshRate) {
648
+ this.deviceRefreshRate = this.accessory.context.refreshRate = this.platform.config.options!.refreshRate;
649
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Platform Config refreshRate: ${this.deviceRefreshRate}`);
650
+ }
651
+ }
652
+
653
+ async config(device: device & devicesConfig): Promise<void> {
654
+ let config = {};
655
+ if (device.meter) {
656
+ config = device.meter;
657
+ }
658
+ if (device.connectionType !== undefined) {
659
+ config['connectionType'] = device.connectionType;
660
+ }
661
+ if (device.external !== undefined) {
662
+ config['external'] = device.external;
663
+ }
664
+ if (device.mqttURL !== undefined) {
665
+ config['mqttURL'] = device.mqttURL;
666
+ }
667
+ if (device.logging !== undefined) {
668
+ config['logging'] = device.logging;
669
+ }
670
+ if (device.refreshRate !== undefined) {
671
+ config['refreshRate'] = device.refreshRate;
672
+ }
673
+ if (device.scanDuration !== undefined) {
674
+ config['scanDuration'] = device.scanDuration;
675
+ }
676
+ if (Object.entries(config).length !== 0) {
677
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Config: ${superStringify(config)}`);
678
+ }
679
+ }
680
+
681
+ async logs(device: device & devicesConfig): Promise<void> {
682
+ if (this.platform.debugMode) {
683
+ this.deviceLogging = this.accessory.context.logging = 'debugMode';
684
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Debug Mode Logging: ${this.deviceLogging}`);
685
+ } else if (device.logging) {
686
+ this.deviceLogging = this.accessory.context.logging = device.logging;
687
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config Logging: ${this.deviceLogging}`);
688
+ } else if (this.platform.config.options?.logging) {
689
+ this.deviceLogging = this.accessory.context.logging = this.platform.config.options?.logging;
690
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Platform Config Logging: ${this.deviceLogging}`);
691
+ } else {
692
+ this.deviceLogging = this.accessory.context.logging = 'standard';
693
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Logging Not Set, Using: ${this.deviceLogging}`);
694
+ }
695
+ }
696
+
697
+ /**
698
+ * Logging for Device
699
+ */
700
+ infoLog(...log: any[]): void {
701
+ if (this.enablingDeviceLogging()) {
702
+ this.platform.log.info(String(...log));
703
+ }
704
+ }
705
+
706
+ warnLog(...log: any[]): void {
707
+ if (this.enablingDeviceLogging()) {
708
+ this.platform.log.warn(String(...log));
709
+ }
710
+ }
711
+
712
+ debugWarnLog(...log: any[]): void {
713
+ if (this.enablingDeviceLogging()) {
714
+ if (this.deviceLogging?.includes('debug')) {
715
+ this.platform.log.warn('[DEBUG]', String(...log));
716
+ }
717
+ }
718
+ }
719
+
720
+ errorLog(...log: any[]): void {
721
+ if (this.enablingDeviceLogging()) {
722
+ this.platform.log.error(String(...log));
723
+ }
724
+ }
725
+
726
+ debugErrorLog(...log: any[]): void {
727
+ if (this.enablingDeviceLogging()) {
728
+ if (this.deviceLogging?.includes('debug')) {
729
+ this.platform.log.error('[DEBUG]', String(...log));
730
+ }
731
+ }
732
+ }
733
+
734
+ debugLog(...log: any[]): void {
735
+ if (this.enablingDeviceLogging()) {
736
+ if (this.deviceLogging === 'debug') {
737
+ this.platform.log.info('[DEBUG]', String(...log));
738
+ } else {
739
+ this.platform.log.debug(String(...log));
740
+ }
741
+ }
742
+ }
743
+
744
+ enablingDeviceLogging(): boolean {
745
+ return this.deviceLogging.includes('debug') || this.deviceLogging === 'standard';
746
+ }
747
+ }