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