@switchbot/homebridge-switchbot 2.4.1-beta.5 → 2.4.1-beta.7

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,1185 @@
1
+ import https from 'https';
2
+ import crypto from 'crypto';
3
+ import { Context } from 'vm';
4
+ import { MqttClient } from 'mqtt';
5
+ import { IncomingMessage } from 'http';
6
+ import { interval, Subject } from 'rxjs';
7
+ import { connectAsync } from 'async-mqtt';
8
+ import superStringify from 'super-stringify';
9
+ import { SwitchBotPlatform } from '../platform';
10
+ import { debounceTime, skipWhile, take, tap } from 'rxjs/operators';
11
+ import { Service, PlatformAccessory, CharacteristicValue } from 'homebridge';
12
+ import { device, devicesConfig, serviceData, switchbot, deviceStatus, ad, HostDomain, DevicePath } from '../settings';
13
+ import { sleep } from '../utils';
14
+
15
+ export class BlindTilt {
16
+ // Services
17
+ windowCoveringService: Service;
18
+ lightSensorService?: Service;
19
+ batteryService?: Service;
20
+
21
+ // Characteristic Values
22
+ CurrentPosition!: CharacteristicValue;
23
+ PositionState!: CharacteristicValue;
24
+ TargetPosition!: CharacteristicValue;
25
+ CurrentAmbientLightLevel?: CharacteristicValue;
26
+ BatteryLevel?: CharacteristicValue;
27
+ StatusLowBattery?: CharacteristicValue;
28
+
29
+ // OpenAPI Others
30
+ deviceStatus!: any; //deviceStatusResponse;
31
+ slidePosition: deviceStatus['slidePosition'];
32
+ moving: deviceStatus['moving'];
33
+ brightness: deviceStatus['brightness'];
34
+ setPositionMode?: string | number;
35
+ Mode!: string;
36
+
37
+ // BLE Others
38
+ connected?: boolean;
39
+ switchbot!: switchbot;
40
+ serviceData!: serviceData;
41
+ spaceBetweenLevels!: number;
42
+ address!: ad['address'];
43
+ calibration: serviceData['calibration'];
44
+ battery: serviceData['battery'];
45
+ position: serviceData['position'];
46
+ inMotion: serviceData['inMotion'];
47
+ lightLevel: serviceData['lightLevel'];
48
+
49
+ // Target
50
+ setNewTarget!: boolean;
51
+ setNewTargetTimer!: NodeJS.Timeout;
52
+
53
+ //MQTT stuff
54
+ mqttClient: MqttClient | null = null;
55
+
56
+ // Config
57
+ set_minStep!: number;
58
+ updateRate!: number;
59
+ set_minLux!: number;
60
+ set_maxLux!: number;
61
+ scanDuration!: number;
62
+ deviceLogging!: string;
63
+ deviceRefreshRate!: number;
64
+ setCloseMode!: string;
65
+ setOpenMode!: string;
66
+
67
+ // Updates
68
+ blindTiltUpdateInProgress!: boolean;
69
+ doBlindTiltUpdate!: Subject<void>;
70
+
71
+ // Connection
72
+ private readonly BLE = (this.device.connectionType === 'BLE' || this.device.connectionType === 'BLE/OpenAPI');
73
+ private readonly OpenAPI = (this.device.connectionType === 'OpenAPI' || this.device.connectionType === 'BLE/OpenAPI');
74
+
75
+ constructor(private readonly platform: SwitchBotPlatform, private accessory: PlatformAccessory, public device: device & devicesConfig) {
76
+ // default placeholders
77
+ this.logs(device);
78
+ this.refreshRate(device);
79
+ this.scan(device);
80
+ this.config(device);
81
+ this.setupMqtt(device);
82
+ this.context();
83
+
84
+ // this is subject we use to track when we need to POST changes to the SwitchBot API
85
+ this.doBlindTiltUpdate = new Subject();
86
+ this.blindTiltUpdateInProgress = false;
87
+ this.setNewTarget = false;
88
+
89
+ // Retrieve initial values and updateHomekit
90
+ this.refreshStatus();
91
+
92
+ // set accessory information
93
+ accessory
94
+ .getService(this.platform.Service.AccessoryInformation)!
95
+ .setCharacteristic(this.platform.Characteristic.Manufacturer, 'SwitchBot')
96
+ .setCharacteristic(this.platform.Characteristic.Model, 'W2701600')
97
+ .setCharacteristic(this.platform.Characteristic.SerialNumber, device.deviceId)
98
+ .setCharacteristic(this.platform.Characteristic.FirmwareRevision, this.FirmwareRevision(accessory, device))
99
+ .getCharacteristic(this.platform.Characteristic.FirmwareRevision)
100
+ .updateValue(this.FirmwareRevision(accessory, device));
101
+
102
+ // get the WindowCovering service if it exists, otherwise create a new WindowCovering service
103
+ // you can create multiple services for each accessory
104
+ (this.windowCoveringService =
105
+ accessory.getService(this.platform.Service.WindowCovering) || accessory.addService(this.platform.Service.WindowCovering)),
106
+ `${device.deviceName} ${device.deviceType}`;
107
+
108
+ // To avoid "Cannot add a Service with the same UUID another Service without also defining a unique 'subtype' property." error,
109
+ // when creating multiple services of the same type, you need to use the following syntax to specify a name and subtype id:
110
+ // accessory.getService('NAME') ?? accessory.addService(this.platform.Service.WindowCovering, 'NAME', 'USER_DEFINED_SUBTYPE');
111
+
112
+ // set the service name, this is what is displayed as the default name on the Home app
113
+ // in this example we are using the name we stored in the `accessory.context` in the `discoverDevices` method.
114
+ this.windowCoveringService.setCharacteristic(this.platform.Characteristic.Name, accessory.displayName);
115
+ if (!this.windowCoveringService.testCharacteristic(this.platform.Characteristic.ConfiguredName)) {
116
+ this.windowCoveringService.addCharacteristic(this.platform.Characteristic.ConfiguredName, accessory.displayName);
117
+ }
118
+
119
+ // each service must implement at-minimum the "required characteristics" for the given service type
120
+ // see https://developers.homebridge.io/#/service/WindowCovering
121
+
122
+ // create handlers for required characteristics
123
+ this.windowCoveringService.setCharacteristic(this.platform.Characteristic.PositionState, this.PositionState);
124
+
125
+ this.windowCoveringService
126
+ .getCharacteristic(this.platform.Characteristic.CurrentPosition)
127
+ .setProps({
128
+ minStep: this.minStep(device),
129
+ minValue: 0,
130
+ maxValue: 100,
131
+ validValueRanges: [0, 100],
132
+ })
133
+ .onGet(() => {
134
+ return this.CurrentPosition;
135
+ });
136
+
137
+ this.windowCoveringService
138
+ .getCharacteristic(this.platform.Characteristic.TargetPosition)
139
+ .setProps({
140
+ minStep: this.minStep(device),
141
+ validValueRanges: [0, 100],
142
+ })
143
+ .onSet(this.TargetPositionSet.bind(this));
144
+
145
+ // Light Sensor Service
146
+ if (device.curtain?.hide_lightsensor) {
147
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Removing Light Sensor Service`);
148
+ this.lightSensorService = this.accessory.getService(this.platform.Service.LightSensor);
149
+ accessory.removeService(this.lightSensorService!);
150
+ } else if (!this.lightSensorService) {
151
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Add Light Sensor Service`);
152
+ (this.lightSensorService =
153
+ this.accessory.getService(this.platform.Service.LightSensor) || this.accessory.addService(this.platform.Service.LightSensor)),
154
+ `${accessory.displayName} Light Sensor`;
155
+
156
+ this.lightSensorService.setCharacteristic(this.platform.Characteristic.Name, `${accessory.displayName} Light Sensor`);
157
+ if (!this.lightSensorService?.testCharacteristic(this.platform.Characteristic.ConfiguredName)) {
158
+ this.lightSensorService.addCharacteristic(this.platform.Characteristic.ConfiguredName, `${accessory.displayName} Light Sensor`);
159
+ }
160
+ } else {
161
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Light Sensor Service Not Added`);
162
+ }
163
+
164
+ // Battery Service
165
+ if (!this.BLE) {
166
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Removing Battery Service`);
167
+ this.batteryService = this.accessory.getService(this.platform.Service.Battery);
168
+ accessory.removeService(this.batteryService!);
169
+ } else if (this.BLE && !this.batteryService) {
170
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Add Battery Service`);
171
+ (this.batteryService = this.accessory.getService(this.platform.Service.Battery) || this.accessory.addService(this.platform.Service.Battery)),
172
+ `${accessory.displayName} Battery`;
173
+
174
+ this.batteryService.setCharacteristic(this.platform.Characteristic.Name, `${accessory.displayName} Battery`);
175
+ if (!this.batteryService.testCharacteristic(this.platform.Characteristic.ConfiguredName)) {
176
+ this.batteryService.addCharacteristic(this.platform.Characteristic.ConfiguredName, `${accessory.displayName} Battery`);
177
+ }
178
+ } else {
179
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Battery Service Not Added`);
180
+ }
181
+
182
+ // Update Homekit
183
+ this.updateHomeKitCharacteristics();
184
+
185
+ // Start an update interval
186
+ interval(this.deviceRefreshRate * 1000)
187
+ .pipe(skipWhile(() => this.blindTiltUpdateInProgress))
188
+ .subscribe(async () => {
189
+ await this.refreshStatus();
190
+ });
191
+
192
+ // update slide progress
193
+ interval(this.updateRate * 1000)
194
+ //.pipe(skipWhile(() => this.blindTiltUpdateInProgress))
195
+ .subscribe(async () => {
196
+ if (this.PositionState === this.platform.Characteristic.PositionState.STOPPED) {
197
+ return;
198
+ }
199
+ this.debugLog(`${this.device.deviceType}: ${accessory.displayName} Refresh Status When Moving, PositionState: ${this.PositionState}`);
200
+ await this.refreshStatus();
201
+ });
202
+
203
+ // Watch for BlindTilt change events
204
+ // We put in a debounce of 100ms so we don't make duplicate calls
205
+ this.doBlindTiltUpdate
206
+ .pipe(
207
+ tap(() => {
208
+ this.blindTiltUpdateInProgress = true;
209
+ }),
210
+ debounceTime(this.platform.config.options!.pushRate! * 1000),
211
+ )
212
+ .subscribe(async () => {
213
+ try {
214
+ await this.pushChanges();
215
+ } catch (e: any) {
216
+ this.apiError(e);
217
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} failed pushChanges with ${this.device.connectionType} Connection,`
218
+ + ` Error Message: ${superStringify(e.message)}`);
219
+ }
220
+ this.blindTiltUpdateInProgress = false;
221
+ });
222
+ }
223
+
224
+ /**
225
+ * Parse the device status from the SwitchBot api
226
+ */
227
+ async parseStatus(): Promise<void> {
228
+ if (!this.device.enableCloudService && this.OpenAPI) {
229
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} parseStatus enableCloudService: ${this.device.enableCloudService}`);
230
+ } else if (this.BLE) {
231
+ await this.BLEparseStatus();
232
+ } else if (this.OpenAPI && this.platform.config.credentials?.token) {
233
+ await this.openAPIparseStatus();
234
+ } else {
235
+ await this.offlineOff();
236
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} Connection Type:`
237
+ + ` ${this.device.connectionType}, parseStatus will not happen.`);
238
+ }
239
+ }
240
+
241
+ async BLEparseStatus(): Promise<void> {
242
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLEparseStatus`);
243
+ // CurrentPosition
244
+ this.CurrentPosition = 100 - Number(this.position);
245
+ await this.setMinMax();
246
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} CurrentPosition ${this.CurrentPosition}`);
247
+ if (this.setNewTarget) {
248
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Checking Status ...`);
249
+ }
250
+
251
+ if (this.setNewTarget && this.inMotion) {
252
+ await this.setMinMax();
253
+ if (this.TargetPosition > this.CurrentPosition) {
254
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Closing, CurrentPosition: ${this.CurrentPosition}`);
255
+ this.PositionState = this.platform.Characteristic.PositionState.INCREASING;
256
+ this.windowCoveringService.getCharacteristic(this.platform.Characteristic.PositionState).updateValue(this.PositionState);
257
+ this.debugLog(`${this.device.deviceType}: ${this.CurrentPosition} INCREASING PositionState: ${this.PositionState}`);
258
+ } else if (this.TargetPosition < this.CurrentPosition) {
259
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Opening, CurrentPosition: ${this.CurrentPosition}`);
260
+ this.PositionState = this.platform.Characteristic.PositionState.DECREASING;
261
+ this.windowCoveringService.getCharacteristic(this.platform.Characteristic.PositionState).updateValue(this.PositionState);
262
+ this.debugLog(`${this.device.deviceType}: ${this.CurrentPosition} DECREASING PositionState: ${this.PositionState}`);
263
+ } else {
264
+ this.debugLog(`${this.device.deviceType}: ${this.CurrentPosition} Standby, CurrentPosition: ${this.CurrentPosition}`);
265
+ this.PositionState = this.platform.Characteristic.PositionState.STOPPED;
266
+ this.windowCoveringService.getCharacteristic(this.platform.Characteristic.PositionState).updateValue(this.PositionState);
267
+ this.debugLog(`${this.device.deviceType}: ${this.CurrentPosition} STOPPED PositionState: ${this.PositionState}`);
268
+ }
269
+ } else {
270
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Standby, CurrentPosition: ${this.CurrentPosition}`);
271
+ this.TargetPosition = this.CurrentPosition;
272
+ this.PositionState = this.platform.Characteristic.PositionState.STOPPED;
273
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Stopped`);
274
+ }
275
+ this.debugLog(
276
+ `${this.device.deviceType}: ${this.accessory.displayName} CurrentPosition: ${this.CurrentPosition},` +
277
+ ` TargetPosition: ${this.TargetPosition}, PositionState: ${this.PositionState},`,
278
+ );
279
+
280
+ if (!this.device.curtain?.hide_lightsensor) {
281
+ this.set_minLux = this.minLux();
282
+ this.set_maxLux = this.maxLux();
283
+ this.spaceBetweenLevels = 9;
284
+
285
+ // Brightness
286
+ switch (this.lightLevel) {
287
+ case 1:
288
+ this.CurrentAmbientLightLevel = this.set_minLux;
289
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} LightLevel: ${this.lightLevel}`);
290
+ break;
291
+ case 2:
292
+ this.CurrentAmbientLightLevel = (this.set_maxLux - this.set_minLux) / this.spaceBetweenLevels;
293
+ this.debugLog(
294
+ `${this.device.deviceType}: ${this.accessory.displayName} LightLevel: ${this.lightLevel},` +
295
+ ` Calculation: ${(this.set_maxLux - this.set_minLux) / this.spaceBetweenLevels}`,
296
+ );
297
+ break;
298
+ case 3:
299
+ this.CurrentAmbientLightLevel = ((this.set_maxLux - this.set_minLux) / this.spaceBetweenLevels) * 2;
300
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} LightLevel: ${this.lightLevel}`);
301
+ break;
302
+ case 4:
303
+ this.CurrentAmbientLightLevel = ((this.set_maxLux - this.set_minLux) / this.spaceBetweenLevels) * 3;
304
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} LightLevel: ${this.lightLevel}`);
305
+ break;
306
+ case 5:
307
+ this.CurrentAmbientLightLevel = ((this.set_maxLux - this.set_minLux) / this.spaceBetweenLevels) * 4;
308
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} LightLevel: ${this.lightLevel}`);
309
+ break;
310
+ case 6:
311
+ this.CurrentAmbientLightLevel = ((this.set_maxLux - this.set_minLux) / this.spaceBetweenLevels) * 5;
312
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} LightLevel: ${this.lightLevel}`);
313
+ break;
314
+ case 7:
315
+ this.CurrentAmbientLightLevel = ((this.set_maxLux - this.set_minLux) / this.spaceBetweenLevels) * 6;
316
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} LightLevel: ${this.lightLevel}`);
317
+ break;
318
+ case 8:
319
+ this.CurrentAmbientLightLevel = ((this.set_maxLux - this.set_minLux) / this.spaceBetweenLevels) * 7;
320
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} LightLevel: ${this.lightLevel}`);
321
+ break;
322
+ case 9:
323
+ this.CurrentAmbientLightLevel = ((this.set_maxLux - this.set_minLux) / this.spaceBetweenLevels) * 8;
324
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} LightLevel: ${this.lightLevel}`);
325
+ break;
326
+ case 10:
327
+ default:
328
+ this.CurrentAmbientLightLevel = this.set_maxLux;
329
+ this.debugLog();
330
+ }
331
+ this.debugLog(
332
+ `${this.device.deviceType}: ${this.accessory.displayName} LightLevel: ${this.lightLevel},`
333
+ + ` CurrentAmbientLightLevel: ${this.CurrentAmbientLightLevel}`,
334
+ );
335
+ }
336
+ // Battery
337
+ this.BatteryLevel = Number(this.battery);
338
+ if (this.BatteryLevel < 10) {
339
+ this.StatusLowBattery = this.platform.Characteristic.StatusLowBattery.BATTERY_LEVEL_LOW;
340
+ } else {
341
+ this.StatusLowBattery = this.platform.Characteristic.StatusLowBattery.BATTERY_LEVEL_NORMAL;
342
+ }
343
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel},`
344
+ +` StatusLowBattery: ${this.StatusLowBattery}`);
345
+ }
346
+
347
+ async openAPIparseStatus(): Promise<void> {
348
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIparseStatus`);
349
+ // CurrentPosition
350
+ this.CurrentPosition = 100 - Number(this.slidePosition);
351
+ await this.setMinMax();
352
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} CurrentPosition: ${this.CurrentPosition}`);
353
+ if (this.setNewTarget) {
354
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Checking Status ...`);
355
+ }
356
+
357
+ if (this.setNewTarget && this.moving) {
358
+ await this.setMinMax();
359
+ if (this.TargetPosition > this.CurrentPosition) {
360
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Closing, CurrentPosition: ${this.CurrentPosition} `);
361
+ this.PositionState = this.platform.Characteristic.PositionState.INCREASING;
362
+ this.windowCoveringService.getCharacteristic(this.platform.Characteristic.PositionState).updateValue(this.PositionState);
363
+ this.debugLog(`${this.device.deviceType}: ${this.CurrentPosition} INCREASING PositionState: ${this.PositionState}`);
364
+ } else if (this.TargetPosition < this.CurrentPosition) {
365
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Opening, CurrentPosition: ${this.CurrentPosition} `);
366
+ this.PositionState = this.platform.Characteristic.PositionState.DECREASING;
367
+ this.windowCoveringService.getCharacteristic(this.platform.Characteristic.PositionState).updateValue(this.PositionState);
368
+ this.debugLog(`${this.device.deviceType}: ${this.CurrentPosition} DECREASING PositionState: ${this.PositionState}`);
369
+ } else {
370
+ this.debugLog(`${this.device.deviceType}: ${this.CurrentPosition} Standby, CurrentPosition: ${this.CurrentPosition}`);
371
+ this.PositionState = this.platform.Characteristic.PositionState.STOPPED;
372
+ this.windowCoveringService.getCharacteristic(this.platform.Characteristic.PositionState).updateValue(this.PositionState);
373
+ this.debugLog(`${this.device.deviceType}: ${this.CurrentPosition} STOPPED PositionState: ${this.PositionState}`);
374
+ }
375
+ } else {
376
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Standby, CurrentPosition: ${this.CurrentPosition}`);
377
+ this.TargetPosition = this.CurrentPosition;
378
+ this.PositionState = this.platform.Characteristic.PositionState.STOPPED;
379
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Stopped`);
380
+ }
381
+ this.debugLog(
382
+ `${this.device.deviceType}: ${this.accessory.displayName} CurrentPosition: ${this.CurrentPosition},` +
383
+ ` TargetPosition: ${this.TargetPosition}, PositionState: ${this.PositionState},`,
384
+ );
385
+
386
+ if (!this.device.curtain?.hide_lightsensor) {
387
+ this.set_minLux = this.minLux();
388
+ this.set_maxLux = this.maxLux();
389
+ // Brightness
390
+ switch (this.brightness) {
391
+ case 'dim':
392
+ this.CurrentAmbientLightLevel = this.set_minLux;
393
+ break;
394
+ case 'bright':
395
+ default:
396
+ this.CurrentAmbientLightLevel = this.set_maxLux;
397
+ }
398
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} CurrentAmbientLightLevel: ${this.CurrentAmbientLightLevel}`);
399
+ }
400
+ }
401
+
402
+ async refreshStatus(): Promise<void> {
403
+ if (!this.device.enableCloudService && this.OpenAPI) {
404
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} refreshStatus enableCloudService: ${this.device.enableCloudService}`);
405
+ } else if (this.BLE) {
406
+ await this.BLERefreshStatus();
407
+ } else if (this.OpenAPI && this.platform.config.credentials?.token) {
408
+ await this.openAPIRefreshStatus();
409
+ } else {
410
+ await this.offlineOff();
411
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} Connection Type:`
412
+ + ` ${this.device.connectionType}, refreshStatus will not happen.`);
413
+ }
414
+ }
415
+
416
+ async BLERefreshStatus(): Promise<void> {
417
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLERefreshStatus`);
418
+ const switchbot = await this.platform.connectBLE();
419
+ // Convert to BLE Address
420
+ this.device.bleMac = this.device
421
+ .deviceId!.match(/.{1,2}/g)!
422
+ .join(':')
423
+ .toLowerCase();
424
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLE Address: ${this.device.bleMac}`);
425
+ this.getCustomBLEAddress(switchbot);
426
+ // Start to monitor advertisement packets
427
+ if (switchbot !== false) {
428
+ switchbot
429
+ .startScan({
430
+ model: 'c',
431
+ id: this.device.bleMac,
432
+ })
433
+ .then(async () => {
434
+ // Set an event hander
435
+ switchbot.onadvertisement = async (ad: any) => {
436
+ this.address = ad.address;
437
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Config BLE Address: ${this.device.bleMac},`
438
+ + ` BLE Address Found: ${this.address}`);
439
+ this.serviceData = ad.serviceData;
440
+ this.calibration = ad.serviceData.calibration;
441
+ this.battery = ad.serviceData.battery;
442
+ this.inMotion = ad.serviceData.inMotion;
443
+ this.position = ad.serviceData.position;
444
+ this.lightLevel = ad.serviceData.lightLevel;
445
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} serviceData: ${superStringify(ad.serviceData)}`);
446
+ this.debugLog(
447
+ `${this.device.deviceType}: ${this.accessory.displayName} calibration: ${ad.serviceData.calibration}, ` +
448
+ `position: ${ad.serviceData.position}, lightLevel: ${ad.serviceData.lightLevel}, battery: ${ad.serviceData.battery}, ` +
449
+ `inMotion: ${ad.serviceData.inMotion}`);
450
+
451
+ if (this.serviceData) {
452
+ this.connected = true;
453
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} connected: ${this.connected}`);
454
+ await this.stopScanning(switchbot);
455
+ } else {
456
+ this.connected = false;
457
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} connected: ${this.connected}`);
458
+ }
459
+ };
460
+ // Wait
461
+ return await switchbot.wait(this.scanDuration * 1000);
462
+ })
463
+ .then(async () => {
464
+ // Stop to monitor
465
+ await this.stopScanning(switchbot);
466
+ })
467
+ .catch(async (e: any) => {
468
+ this.apiError(e);
469
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} failed BLERefreshStatus with ${this.device.connectionType}`
470
+ + ` Connection, Error Message: ${superStringify(e.message)}`);
471
+ await this.BLERefreshConnection(switchbot);
472
+ });
473
+ } else {
474
+ await this.BLERefreshConnection(switchbot);
475
+ }
476
+ }
477
+
478
+ async openAPIRefreshStatus(): Promise<void> {
479
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIRefreshStatus`);
480
+ try {
481
+ const t = Date.now();
482
+ const nonce = 'requestID';
483
+ const data = this.platform.config.credentials?.token + t + nonce;
484
+ const signTerm = crypto.createHmac('sha256', this.platform.config.credentials?.secret).update(Buffer.from(data, 'utf-8')).digest();
485
+ const sign = signTerm.toString('base64');
486
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} sign: ${sign}`);
487
+ const options = {
488
+ hostname: HostDomain,
489
+ port: 443,
490
+ path: `${DevicePath}/${this.device.deviceId}/status`,
491
+ method: 'GET',
492
+ headers: {
493
+ Authorization: this.platform.config.credentials?.token,
494
+ sign: sign,
495
+ nonce: nonce,
496
+ t: t,
497
+ 'Content-Type': 'application/json',
498
+ },
499
+ };
500
+ const req = https.request(options, (res) => {
501
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} statusCode: ${res.statusCode}`);
502
+ let rawData = '';
503
+ res.on('data', (d) => {
504
+ rawData += d;
505
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} d: ${d}`);
506
+ });
507
+ res.on('end', () => {
508
+ try {
509
+ this.deviceStatus = JSON.parse(rawData);
510
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} refreshStatus: ${superStringify(this.deviceStatus)}`);
511
+ this.slidePosition = this.deviceStatus.body.slidePosition;
512
+ this.moving = this.deviceStatus.body.moving;
513
+ this.brightness = this.deviceStatus.body.brightness;
514
+ this.openAPIparseStatus();
515
+ this.updateHomeKitCharacteristics();
516
+ } catch (e: any) {
517
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} error message: ${e.message}`);
518
+ }
519
+ });
520
+ });
521
+ req.on('error', (e: any) => {
522
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} error message: ${e.message}`);
523
+ });
524
+ req.end();
525
+ } catch (e: any) {
526
+ this.apiError(e);
527
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} failed openAPIRefreshStatus with ${this.device.connectionType}`
528
+ + ` Connection, Error Message: ${superStringify(e.message)}`);
529
+ }
530
+ }
531
+
532
+ async pushChanges(): Promise<void> {
533
+ if (!this.device.enableCloudService && this.OpenAPI) {
534
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} pushChanges enableCloudService: ${this.device.enableCloudService}`);
535
+ } else if (this.BLE) {
536
+ await this.BLEpushChanges();
537
+ } else if (this.OpenAPI && this.platform.config.credentials?.token) {
538
+ await this.openAPIpushChanges();
539
+ } else {
540
+ await this.offlineOff();
541
+ this.debugWarnLog(`${this.device.deviceType}: ${this.accessory.displayName} Connection Type:`
542
+ + ` ${this.device.connectionType}, pushChanges will not happen.`);
543
+ }
544
+ // Refresh the status from the API
545
+ interval(15000)
546
+ .pipe(skipWhile(() => this.blindTiltUpdateInProgress))
547
+ .pipe(take(1))
548
+ .subscribe(async () => {
549
+ await this.refreshStatus();
550
+ });
551
+ }
552
+
553
+ async BLEpushChanges(): Promise<void> {
554
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLEpushChanges`);
555
+ if (this.TargetPosition !== this.CurrentPosition) {
556
+ const switchbot = await this.platform.connectBLE();
557
+ // Convert to BLE Address
558
+ this.device.bleMac = this.device
559
+ .deviceId!.match(/.{1,2}/g)!
560
+ .join(':')
561
+ .toLowerCase();
562
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BLE Address: ${this.device.bleMac}`);
563
+ this.SilentPerformance();
564
+ const adjustedMode = this.setPositionMode || null;
565
+ if (adjustedMode === null) {
566
+ this.Mode = 'Default Mode';
567
+ }
568
+ this.debugLog(`${this.accessory.displayName} Mode: ${this.Mode}`);
569
+ if (switchbot !== false) {
570
+ switchbot
571
+ .discover({ model: 'c', quick: true, id: this.device.bleMac })
572
+ .then(async (device_list: any) => {
573
+ this.infoLog(`${this.accessory.displayName} Target Position: ${this.TargetPosition}`);
574
+ return await this.retry({
575
+ max: await this.maxRetry(),
576
+ fn: () => {
577
+ return device_list[0].runToPos(100 - Number(this.TargetPosition), adjustedMode);
578
+ },
579
+ });
580
+ })
581
+ .then(() => {
582
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Done.`);
583
+ })
584
+ .catch(async (e: any) => {
585
+ this.apiError(e);
586
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} failed BLEpushChanges with ${this.device.connectionType}`
587
+ + ` Connection, Error Message: ${superStringify(e.message)}`);
588
+ await this.BLEPushConnection();
589
+ });
590
+ } else {
591
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} wasn't able to establish BLE Connection`);
592
+ await this.BLEPushConnection();
593
+ }
594
+ } else {
595
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} No BLEpushChanges, CurrentPosition & TargetPosition Are the Same.` +
596
+ ` CurrentPosition: ${this.CurrentPosition}, TargetPosition ${this.TargetPosition}`,
597
+ );
598
+ }
599
+ }
600
+
601
+ async retry({ max, fn }: { max: number; fn: { (): any; (): Promise<any> } }): Promise<null> {
602
+ return fn().catch(async (err: any) => {
603
+ if (max === 0) {
604
+ throw err;
605
+ }
606
+ this.infoLog(err);
607
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Retrying`);
608
+ await sleep(1000);
609
+ return this.retry({ max: max - 1, fn });
610
+ });
611
+ }
612
+
613
+ async maxRetry(): Promise<number> {
614
+ let maxRetry: number;
615
+ if (this.device.maxRetry) {
616
+ maxRetry = this.device.maxRetry;
617
+ } else {
618
+ maxRetry = 5;
619
+ }
620
+ return maxRetry;
621
+ }
622
+
623
+ async openAPIpushChanges(): Promise<void> {
624
+ try {
625
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} OpenAPI pushChanges`);
626
+ if ((this.TargetPosition !== this.CurrentPosition) || this.device.disableCaching) {
627
+ // Make Push On request to the API
628
+ const t = Date.now();
629
+ const nonce = 'requestID';
630
+ const data = this.platform.config.credentials?.token + t + nonce;
631
+ const signTerm = crypto.createHmac('sha256', this.platform.config.credentials?.secret)
632
+ .update(Buffer.from(data, 'utf-8'))
633
+ .digest();
634
+ const sign = signTerm.toString('base64');
635
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} sign: ${sign}`);
636
+ this.debugLog(`Pushing ${this.TargetPosition}`);
637
+ const adjustedTargetPosition = 100 - Number(this.TargetPosition);
638
+ if (this.TargetPosition > 50) {
639
+ this.setPositionMode = this.device.curtain?.setOpenMode;
640
+ } else {
641
+ this.setPositionMode = this.device.curtain?.setCloseMode;
642
+ }
643
+ if (this.setPositionMode === '1') {
644
+ this.Mode = 'Silent Mode';
645
+ } else if (this.setPositionMode === '0') {
646
+ this.Mode = 'Performance Mode';
647
+ } else {
648
+ this.Mode = 'Default Mode';
649
+ }
650
+ this.debugLog(`${this.accessory.displayName} Mode: ${this.Mode}`);
651
+ const adjustedMode = this.setPositionMode || 'ff';
652
+ const body = superStringify({
653
+ 'command': 'setPosition',
654
+ 'parameter': `0,${adjustedMode},${adjustedTargetPosition}`,
655
+ 'commandType': 'command',
656
+ });
657
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Sending request to SwitchBot API, body: ${body},`);
658
+ const options = {
659
+ hostname: HostDomain,
660
+ port: 443,
661
+ path: `${DevicePath}/${this.device.deviceId}/commands`,
662
+ method: 'POST',
663
+ headers: {
664
+ 'Authorization': this.platform.config.credentials?.token,
665
+ 'sign': sign,
666
+ 'nonce': nonce,
667
+ 't': t,
668
+ 'Content-Type': 'application/json',
669
+ 'Content-Length': body.length,
670
+ },
671
+ };
672
+ const req = https.request(options, res => {
673
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIpushChanges statusCode: ${res.statusCode}`);
674
+ this.statusCode({ res });
675
+ res.on('data', d => {
676
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} d: ${d}`);
677
+ });
678
+ });
679
+ req.on('error', (e: any) => {
680
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} error message: ${e.message}`);
681
+ });
682
+ req.write(body);
683
+ req.end();
684
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} openAPIpushChanges: ${superStringify(req)}`);
685
+ } else {
686
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} No OpenAPI Changes, CurrentPosition & TargetPosition Are the Same.`
687
+ +` CurrentPosition: ${this.CurrentPosition}, TargetPosition ${this.TargetPosition}`,
688
+ );
689
+ }
690
+ } catch (e: any) {
691
+ this.apiError(e);
692
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} failed openAPIpushChanges with ${this.device.connectionType}`
693
+ + ` Connection, Error Message: ${superStringify(e.message)}`,
694
+ );
695
+ }
696
+ }
697
+
698
+ /**
699
+ * Handle requests to set the value of the "Target Position" characteristic
700
+ */
701
+ async TargetPositionSet(value: CharacteristicValue): Promise<void> {
702
+ if (this.TargetPosition === this.accessory.context.TargetPosition) {
703
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} No Changes, Set TargetPosition: ${value}`);
704
+ } else {
705
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Set TargetPosition: ${value}`);
706
+ }
707
+
708
+ this.TargetPosition = value;
709
+ if (this.device.mqttURL) {
710
+ this.mqttPublish('TargetPosition', this.TargetPosition);
711
+ }
712
+
713
+ await this.setMinMax();
714
+ if (value > this.CurrentPosition) {
715
+ this.PositionState = this.platform.Characteristic.PositionState.INCREASING;
716
+ this.setNewTarget = true;
717
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} value: ${value}, CurrentPosition: ${this.CurrentPosition}`);
718
+ } else if (value < this.CurrentPosition) {
719
+ this.PositionState = this.platform.Characteristic.PositionState.DECREASING;
720
+ this.setNewTarget = true;
721
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} value: ${value}, CurrentPosition: ${this.CurrentPosition}`);
722
+ } else {
723
+ this.PositionState = this.platform.Characteristic.PositionState.STOPPED;
724
+ this.setNewTarget = false;
725
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} value: ${value}, CurrentPosition: ${this.CurrentPosition}`);
726
+ }
727
+ this.windowCoveringService.setCharacteristic(this.platform.Characteristic.PositionState, this.PositionState);
728
+ this.windowCoveringService.getCharacteristic(this.platform.Characteristic.PositionState).updateValue(this.PositionState);
729
+
730
+ /**
731
+ * If Blind Tilt movement time is short, the moving flag from backend is always false.
732
+ * The minimum time depends on the network control latency.
733
+ */
734
+ clearTimeout(this.setNewTargetTimer);
735
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateRate: ${this.updateRate}`);
736
+ if (this.setNewTarget) {
737
+ this.setNewTargetTimer = setTimeout(() => {
738
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} setNewTarget ${this.setNewTarget} timeout`);
739
+ this.setNewTarget = false;
740
+ }, this.updateRate * 1000);
741
+ }
742
+ this.doBlindTiltUpdate.next();
743
+ }
744
+
745
+ async updateHomeKitCharacteristics(): Promise<void> {
746
+ await this.setMinMax();
747
+ if (this.CurrentPosition === undefined || Number.isNaN(this.CurrentPosition)) {
748
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} CurrentPosition: ${this.CurrentPosition}`);
749
+ } else {
750
+ if (this.device.mqttURL) {
751
+ this.mqttPublish('CurrentPosition', this.CurrentPosition);
752
+ }
753
+ this.accessory.context.CurrentPosition = this.CurrentPosition;
754
+ this.windowCoveringService.updateCharacteristic(this.platform.Characteristic.CurrentPosition, Number(this.CurrentPosition));
755
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic CurrentPosition: ${this.CurrentPosition}`);
756
+ }
757
+ if (this.PositionState === undefined) {
758
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} PositionState: ${this.PositionState}`);
759
+ } else {
760
+ if (this.device.mqttURL) {
761
+ this.mqttPublish('PositionState', this.PositionState);
762
+ }
763
+ this.accessory.context.PositionState = this.PositionState;
764
+ this.windowCoveringService.updateCharacteristic(this.platform.Characteristic.PositionState, Number(this.PositionState));
765
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic PositionState: ${this.PositionState}`);
766
+ }
767
+ if (this.TargetPosition === undefined || Number.isNaN(this.TargetPosition)) {
768
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} TargetPosition: ${this.TargetPosition}`);
769
+ } else {
770
+ if (this.device.mqttURL) {
771
+ this.mqttPublish('TargetPosition', this.TargetPosition);
772
+ }
773
+ this.accessory.context.TargetPosition = this.TargetPosition;
774
+ this.windowCoveringService.updateCharacteristic(this.platform.Characteristic.TargetPosition, Number(this.TargetPosition));
775
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic TargetPosition: ${this.TargetPosition}`);
776
+ }
777
+ if (!this.device.curtain?.hide_lightsensor) {
778
+ if (this.CurrentAmbientLightLevel === undefined || Number.isNaN(this.CurrentAmbientLightLevel)) {
779
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} CurrentAmbientLightLevel: ${this.CurrentAmbientLightLevel}`);
780
+ } else {
781
+ if (this.device.mqttURL) {
782
+ this.mqttPublish('CurrentAmbientLightLevel', this.CurrentAmbientLightLevel);
783
+ }
784
+ this.accessory.context.CurrentAmbientLightLevel = this.CurrentAmbientLightLevel;
785
+ this.lightSensorService?.updateCharacteristic(this.platform.Characteristic.CurrentAmbientLightLevel, this.CurrentAmbientLightLevel);
786
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName}`
787
+ + ` updateCharacteristic CurrentAmbientLightLevel: ${this.CurrentAmbientLightLevel}`);
788
+ }
789
+ }
790
+ if (this.BLE) {
791
+ if (this.BatteryLevel === undefined) {
792
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} BatteryLevel: ${this.BatteryLevel}`);
793
+ } else {
794
+ if (this.device.mqttURL) {
795
+ this.mqttPublish('BatteryLevel', this.BatteryLevel);
796
+ }
797
+ this.accessory.context.BatteryLevel = this.BatteryLevel;
798
+ this.batteryService?.updateCharacteristic(this.platform.Characteristic.BatteryLevel, this.BatteryLevel);
799
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic BatteryLevel: ${this.BatteryLevel}`);
800
+ }
801
+ if (this.StatusLowBattery === undefined) {
802
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} StatusLowBattery: ${this.StatusLowBattery}`);
803
+ } else {
804
+ if (this.device.mqttURL) {
805
+ this.mqttPublish('StatusLowBattery', this.StatusLowBattery);
806
+ }
807
+ this.accessory.context.StatusLowBattery = this.StatusLowBattery;
808
+ this.batteryService?.updateCharacteristic(this.platform.Characteristic.StatusLowBattery, this.StatusLowBattery);
809
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} updateCharacteristic StatusLowBattery: ${this.StatusLowBattery}`);
810
+ }
811
+ }
812
+ }
813
+
814
+ /*
815
+ * Publish MQTT message for topics of
816
+ * 'homebridge-switchbot/blindtilt/xx:xx:xx:xx:xx:xx'
817
+ */
818
+ mqttPublish(topic: string, message: any) {
819
+ const mac = this.device.deviceId
820
+ ?.toLowerCase()
821
+ .match(/[\s\S]{1,2}/g)
822
+ ?.join(':');
823
+ const options = this.device.mqttPubOptions || {};
824
+ this.mqttClient?.publish(`homebridge-switchbot/blindtilt/${mac}/${topic}`, `${message}`, options);
825
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} MQTT message: ${topic}/${message} options:${superStringify(options)}`);
826
+ }
827
+
828
+ /*
829
+ * Setup MQTT hadler if URL is specifed.
830
+ */
831
+ async setupMqtt(device: device & devicesConfig): Promise<void> {
832
+ if (device.mqttURL) {
833
+ try {
834
+ this.mqttClient = await connectAsync(device.mqttURL, device.mqttOptions || {});
835
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} MQTT connection has been established successfully.`);
836
+ this.mqttClient.on('error', (e: Error) => {
837
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Failed to publish MQTT messages. ${e}`);
838
+ });
839
+ } catch (e) {
840
+ this.mqttClient = null;
841
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Failed to establish MQTT connection. ${e}`);
842
+ }
843
+ }
844
+ }
845
+
846
+ async stopScanning(switchbot: any) {
847
+ await switchbot.stopScan();
848
+ if (this.connected) {
849
+ await this.BLEparseStatus();
850
+ await this.updateHomeKitCharacteristics();
851
+ } else {
852
+ await this.BLERefreshConnection(switchbot);
853
+ }
854
+ }
855
+
856
+ async getCustomBLEAddress(switchbot: any) {
857
+ if (this.device.customBLEaddress && this.deviceLogging.includes('debug')) {
858
+ (async () => {
859
+ // Start to monitor advertisement packets
860
+ await switchbot.startScan({
861
+ model: 'c',
862
+ });
863
+ // Set an event handler
864
+ switchbot.onadvertisement = (ad: any) => {
865
+ this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} ad: ${superStringify(ad, null, ' ')}`);
866
+ };
867
+ await switchbot.wait(10000);
868
+ // Stop to monitor
869
+ switchbot.stopScan();
870
+ })();
871
+ }
872
+ }
873
+
874
+ async BLEPushConnection() {
875
+ if (this.platform.config.credentials?.token && this.device.connectionType === 'BLE/OpenAPI') {
876
+ this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} Using OpenAPI Connection to Push Changes`);
877
+ await this.openAPIpushChanges();
878
+ }
879
+ }
880
+
881
+ async BLERefreshConnection(switchbot: any): Promise<void> {
882
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} wasn't able to establish BLE Connection, node-switchbot: ${switchbot}`);
883
+ if (this.platform.config.credentials?.token && this.device.connectionType === 'BLE/OpenAPI') {
884
+ this.warnLog(`${this.device.deviceType}: ${this.accessory.displayName} Using OpenAPI Connection to Refresh Status`);
885
+ await this.openAPIRefreshStatus();
886
+ }
887
+ }
888
+
889
+ async SilentPerformance() {
890
+ if (this.TargetPosition > 50) {
891
+ if (this.device.curtain?.setOpenMode === '1') {
892
+ this.setPositionMode = 1;
893
+ this.Mode = 'Silent Mode';
894
+ } else {
895
+ this.setPositionMode = 0;
896
+ this.Mode = 'Performance Mode';
897
+ }
898
+ } else {
899
+ if (this.device.curtain?.setCloseMode === '1') {
900
+ this.setPositionMode = 1;
901
+ this.Mode = 'Silent Mode';
902
+ } else {
903
+ this.setPositionMode = 0;
904
+ this.Mode = 'Performance Mode';
905
+ }
906
+ }
907
+ }
908
+
909
+ async setMinMax(): Promise<void> {
910
+ if (this.device.curtain?.set_min) {
911
+ if (this.CurrentPosition <= this.device.curtain?.set_min) {
912
+ this.CurrentPosition = 0;
913
+ }
914
+ }
915
+ if (this.device.curtain?.set_max) {
916
+ if (this.CurrentPosition >= this.device.curtain?.set_max) {
917
+ this.CurrentPosition = 100;
918
+ }
919
+ }
920
+ }
921
+
922
+ minStep(device: device & devicesConfig): number {
923
+ if (device.curtain?.set_minStep) {
924
+ this.set_minStep = device.curtain?.set_minStep;
925
+ } else {
926
+ this.set_minStep = 1;
927
+ }
928
+ return this.set_minStep;
929
+ }
930
+
931
+ minLux(): number {
932
+ if (this.device.curtain?.set_minLux) {
933
+ this.set_minLux = this.device.curtain?.set_minLux;
934
+ } else {
935
+ this.set_minLux = 1;
936
+ }
937
+ return this.set_minLux;
938
+ }
939
+
940
+ maxLux(): number {
941
+ if (this.device.curtain?.set_maxLux) {
942
+ this.set_maxLux = this.device.curtain?.set_maxLux;
943
+ } else {
944
+ this.set_maxLux = 6001;
945
+ }
946
+ return this.set_maxLux;
947
+ }
948
+
949
+ async scan(device: device & devicesConfig): Promise<void> {
950
+ if (device.scanDuration) {
951
+ if (this.updateRate > device.scanDuration) {
952
+ this.scanDuration = this.updateRate;
953
+ if (this.BLE) {
954
+ this.warnLog(`${this.device.deviceType}: `
955
+ + `${this.accessory.displayName} scanDuration is less then updateRate, overriding scanDuration with updateRate`);
956
+ }
957
+ } else {
958
+ this.scanDuration = this.accessory.context.scanDuration = device.scanDuration;
959
+ }
960
+ if (this.BLE) {
961
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config scanDuration: ${this.scanDuration}`);
962
+ }
963
+ } else {
964
+ if (this.updateRate > 1) {
965
+ this.scanDuration = this.updateRate;
966
+ if (this.BLE) {
967
+ this.warnLog(`${this.device.deviceType}: `
968
+ + `${this.accessory.displayName} scanDuration is less then updateRate, overriding scanDuration with updateRate`);
969
+ }
970
+ } else {
971
+ this.scanDuration = this.accessory.context.scanDuration = 1;
972
+ }
973
+ if (this.BLE) {
974
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Default scanDuration: ${this.scanDuration}`);
975
+ }
976
+ }
977
+ }
978
+
979
+ async statusCode({ res }: { res: IncomingMessage }): Promise<void> {
980
+ switch (res.statusCode) {
981
+ case 151:
982
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Command not supported by this device type.`);
983
+ break;
984
+ case 152:
985
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Device not found.`);
986
+ break;
987
+ case 160:
988
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Command is not supported.`);
989
+ break;
990
+ case 161:
991
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Device is offline.`);
992
+ this.offlineOff();
993
+ break;
994
+ case 171:
995
+ this.errorLog(`${this.device.deviceType}: ${this.accessory.displayName} Hub Device is offline. Hub: ${this.device.hubDeviceId}`);
996
+ this.offlineOff();
997
+ break;
998
+ case 190:
999
+ this.errorLog(
1000
+ `${this.device.deviceType}: ${this.accessory.displayName} Device internal error due to device states not synchronized with server,` +
1001
+ ` Or command: ${superStringify(res)} format is invalid`,
1002
+ );
1003
+ break;
1004
+ case 100:
1005
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Command successfully sent.`);
1006
+ break;
1007
+ default:
1008
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Unknown statusCode.`);
1009
+ }
1010
+ }
1011
+
1012
+ async offlineOff(): Promise<void> {
1013
+ if (this.device.offline) {
1014
+ await this.context();
1015
+ await this.updateHomeKitCharacteristics();
1016
+ }
1017
+ }
1018
+
1019
+ async apiError(e: any): Promise<void> {
1020
+ this.windowCoveringService.updateCharacteristic(this.platform.Characteristic.CurrentPosition, e);
1021
+ this.windowCoveringService.updateCharacteristic(this.platform.Characteristic.PositionState, e);
1022
+ this.windowCoveringService.updateCharacteristic(this.platform.Characteristic.TargetPosition, e);
1023
+ if (!this.device.curtain?.hide_lightsensor) {
1024
+ this.lightSensorService?.updateCharacteristic(this.platform.Characteristic.CurrentAmbientLightLevel, e);
1025
+ }
1026
+ if (this.BLE) {
1027
+ this.batteryService?.updateCharacteristic(this.platform.Characteristic.BatteryLevel, e);
1028
+ this.batteryService?.updateCharacteristic(this.platform.Characteristic.StatusLowBattery, e);
1029
+ }
1030
+ //throw new this.platform.api.hap.HapStatusError(HAPStatus.SERVICE_COMMUNICATION_FAILURE);
1031
+ }
1032
+
1033
+ FirmwareRevision(accessory: PlatformAccessory<Context>, device: device & devicesConfig): CharacteristicValue {
1034
+ let FirmwareRevision: string;
1035
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName}`
1036
+ + ` accessory.context.FirmwareRevision: ${accessory.context.FirmwareRevision}`);
1037
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} device.firmware: ${device.firmware}`);
1038
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} this.platform.version: ${this.platform.version}`);
1039
+ if (accessory.context.FirmwareRevision) {
1040
+ FirmwareRevision = accessory.context.FirmwareRevision;
1041
+ } else if (device.firmware) {
1042
+ FirmwareRevision = device.firmware;
1043
+ } else {
1044
+ FirmwareRevision = this.platform.version;
1045
+ }
1046
+ return FirmwareRevision;
1047
+ }
1048
+
1049
+ async context() {
1050
+ if (this.CurrentPosition === undefined) {
1051
+ this.CurrentPosition = 0;
1052
+ } else {
1053
+ this.CurrentPosition = this.accessory.context.CurrentPosition;
1054
+ }
1055
+
1056
+ if (this.TargetPosition === undefined) {
1057
+ this.TargetPosition = 0;
1058
+ } else {
1059
+ this.TargetPosition = this.accessory.context.TargetPosition;
1060
+ }
1061
+
1062
+ if (this.PositionState === undefined) {
1063
+ this.PositionState = this.platform.Characteristic.PositionState.STOPPED;
1064
+ } else {
1065
+ this.PositionState = this.accessory.context.PositionState;
1066
+ }
1067
+ }
1068
+
1069
+ async refreshRate(device: device & devicesConfig): Promise<void> {
1070
+ // refreshRate
1071
+ if (device.refreshRate) {
1072
+ this.deviceRefreshRate = this.accessory.context.refreshRate = device.refreshRate;
1073
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config refreshRate: ${this.deviceRefreshRate}`);
1074
+ } else if (this.platform.config.options!.refreshRate) {
1075
+ this.deviceRefreshRate = this.accessory.context.refreshRate = this.platform.config.options!.refreshRate;
1076
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Platform Config refreshRate: ${this.deviceRefreshRate}`);
1077
+ }
1078
+ // updateRate
1079
+ if (device?.curtain?.updateRate) {
1080
+ this.updateRate = device?.curtain?.updateRate;
1081
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config Blind Tilt updateRate: ${this.updateRate}`);
1082
+ } else {
1083
+ this.updateRate = 7;
1084
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Default Blind Tilt updateRate: ${this.updateRate}`);
1085
+ }
1086
+ }
1087
+
1088
+ async config(device: device & devicesConfig): Promise<void> {
1089
+ let config = {};
1090
+ if (device.curtain) {
1091
+ config = device.curtain;
1092
+ }
1093
+ if (device.connectionType !== undefined) {
1094
+ config['connectionType'] = device.connectionType;
1095
+ }
1096
+ if (device.external !== undefined) {
1097
+ config['external'] = device.external;
1098
+ }
1099
+ if (device.mqttURL !== undefined) {
1100
+ config['mqttURL'] = device.mqttURL;
1101
+ }
1102
+ if (device.logging !== undefined) {
1103
+ config['logging'] = device.logging;
1104
+ }
1105
+ if (device.refreshRate !== undefined) {
1106
+ config['refreshRate'] = device.refreshRate;
1107
+ }
1108
+ if (device.scanDuration !== undefined) {
1109
+ config['scanDuration'] = device.scanDuration;
1110
+ }
1111
+ if (device.maxRetry !== undefined) {
1112
+ config['maxRetry'] = device.maxRetry;
1113
+ }
1114
+ if (Object.entries(config).length !== 0) {
1115
+ this.infoLog(`${this.device.deviceType}: ${this.accessory.displayName} Config: ${superStringify(config)}`);
1116
+ }
1117
+ }
1118
+
1119
+ async logs(device: device & devicesConfig): Promise<void> {
1120
+ if (this.platform.debugMode) {
1121
+ this.deviceLogging = this.accessory.context.logging = 'debugMode';
1122
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Debug Mode Logging: ${this.deviceLogging}`);
1123
+ } else if (device.logging) {
1124
+ this.deviceLogging = this.accessory.context.logging = device.logging;
1125
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Device Config Logging: ${this.deviceLogging}`);
1126
+ } else if (this.platform.config.options?.logging) {
1127
+ this.deviceLogging = this.accessory.context.logging = this.platform.config.options?.logging;
1128
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Using Platform Config Logging: ${this.deviceLogging}`);
1129
+ } else {
1130
+ this.deviceLogging = this.accessory.context.logging = 'standard';
1131
+ this.debugLog(`${this.device.deviceType}: ${this.accessory.displayName} Logging Not Set, Using: ${this.deviceLogging}`);
1132
+ }
1133
+ }
1134
+
1135
+ /**
1136
+ * Logging for Device
1137
+ */
1138
+ infoLog(...log: any[]): void {
1139
+ if (this.enablingDeviceLogging()) {
1140
+ this.platform.log.info(String(...log));
1141
+ }
1142
+ }
1143
+
1144
+ warnLog(...log: any[]): void {
1145
+ if (this.enablingDeviceLogging()) {
1146
+ this.platform.log.warn(String(...log));
1147
+ }
1148
+ }
1149
+
1150
+ debugWarnLog(...log: any[]): void {
1151
+ if (this.enablingDeviceLogging()) {
1152
+ if (this.deviceLogging?.includes('debug')) {
1153
+ this.platform.log.warn('[DEBUG]', String(...log));
1154
+ }
1155
+ }
1156
+ }
1157
+
1158
+ errorLog(...log: any[]): void {
1159
+ if (this.enablingDeviceLogging()) {
1160
+ this.platform.log.error(String(...log));
1161
+ }
1162
+ }
1163
+
1164
+ debugErrorLog(...log: any[]): void {
1165
+ if (this.enablingDeviceLogging()) {
1166
+ if (this.deviceLogging?.includes('debug')) {
1167
+ this.platform.log.error('[DEBUG]', String(...log));
1168
+ }
1169
+ }
1170
+ }
1171
+
1172
+ debugLog(...log: any[]): void {
1173
+ if (this.enablingDeviceLogging()) {
1174
+ if (this.deviceLogging === 'debug') {
1175
+ this.platform.log.info('[DEBUG]', String(...log));
1176
+ } else {
1177
+ this.platform.log.debug(String(...log));
1178
+ }
1179
+ }
1180
+ }
1181
+
1182
+ enablingDeviceLogging(): boolean {
1183
+ return this.deviceLogging.includes('debug') || this.deviceLogging === 'standard';
1184
+ }
1185
+ }