@switchbot/homebridge-switchbot 2.4.1-beta.6 → 2.5.0-beta.0

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