@switchbot/homebridge-switchbot 2.5.3-beta.13 → 2.5.3-beta.14

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