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