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