generated from homebridge/homebridge-plugin-template
/
dingzAccessory.ts
1547 lines (1427 loc) · 47.8 KB
/
dingzAccessory.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
CharacteristicEventTypes,
CharacteristicGetCallback,
CharacteristicSetCallback,
CharacteristicValue,
PlatformAccessory,
Service,
} from 'homebridge';
import { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios';
import simpleColorConverter from 'simple-color-converter';
import qs from 'qs';
import semver from 'semver';
// Internal types
import { RETRY_TIMEOUT } from './settings';
import {
ButtonId,
ButtonState,
DimmerId,
DimmerIndex,
DimmerState,
DimmerTimer,
DingzDeviceInfo,
DingzDevices,
DingzDeviceSystemConfig,
DingzDeviceDimmerConfig,
DingzDeviceInputConfig,
DingzDimmerConfigValue,
DingzLEDState,
DingzMotionData,
DingzState,
WindowCoveringIndex,
WindowCoveringTimer,
WindowCoveringStates,
DingzDeviceWindowCoveringConfig,
DingzWindowCoveringConfigItem,
} from './lib/dingzTypes';
import { ButtonAction, AccessoryActionUrl } from './lib/commonTypes';
import { DeviceNotReachableError } from './lib/errors';
import { DingzDaHomebridgePlatform } from './platform';
import { PlatformEvent } from './lib/platformEventBus';
import { DingzDaBaseAccessory } from './lib/dingzDaBaseAccessory';
import { AccessoryEvent } from './lib/accessoryEventBus';
/**
* Platform Accessory
* An instance of this class is created for each accessory your platform registers
* Each accessory may expose multiple services of different service types.
*/
export class DingzAccessory extends DingzDaBaseAccessory {
private motionService?: Service;
private dingzDeviceInfo: DingzDeviceInfo;
// Todo: Make proper internal representation
private dingzStates = {
// Outputs
Dimmers: [] as DimmerState[],
WindowCovers: [] as WindowCoveringStates[],
LED: {
on: false,
hsv: '0;0;100',
rgb: 'FFFFFF',
mode: 'hsv',
} as DingzLEDState,
// Inputs
Buttons: {
'1': { event: ButtonAction.SINGLE_PRESS, state: ButtonState.OFF },
'2': { event: ButtonAction.SINGLE_PRESS, state: ButtonState.OFF },
'3': { event: ButtonAction.SINGLE_PRESS, state: ButtonState.OFF },
'4': { event: ButtonAction.SINGLE_PRESS, state: ButtonState.OFF },
},
// Sensors
Temperature: 0 as number,
Motion: false as boolean,
Brightness: 0 as number,
};
private motionTimer?: NodeJS.Timer;
private dimmerTimers = {} as DimmerTimer;
private windowCoveringTimers = {} as WindowCoveringTimer;
/**
* DingzAccessory constructor
* @param _platform platform pointer
* @param _accessory accessory pointer
*/
constructor(
private readonly _platform: DingzDaHomebridgePlatform,
private readonly _accessory: PlatformAccessory,
) {
super(_platform, _accessory);
// Set base info
this.dingzDeviceInfo = this.device.hwInfo as DingzDeviceInfo;
// Remove Reachability service if still present
const bridgingService: Service | undefined = this.accessory.getService(
this.platform.Service.BridgingState,
);
if (bridgingService) {
this.accessory.removeService(bridgingService);
}
// Add Dimmers, Blinds etc.
this.log.info(
'Adding output devices for ',
this.device.address,
' -> [...]',
);
DingzAccessory.getConfigs({
address: this.device.address,
token: this.device.token,
})
.then(
({
dingzDevices,
inputConfig,
systemConfig,
dimmerConfig,
blindConfig,
}) => {
if (
inputConfig?.inputs &&
dimmerConfig?.dimmers &&
dimmerConfig?.dimmers.length === 4
) {
this.device.dingzInputInfo = inputConfig.inputs;
this.device.systemConfig = systemConfig;
this.device.dimmerConfig = dimmerConfig;
this.device.windowCoveringConfig = blindConfig.blinds;
if (dingzDevices[this.device.mac]) {
this.log.debug(
'Updated device info received -> update accessory',
dingzDevices[this.device.mac],
);
const dip_config = dingzDevices[this.device.mac].dip_config;
if (this.dingzDeviceInfo.dip_config !== dip_config) {
// DIP config has changes, invalidate config
this.device.configTimestamp = undefined;
}
// Persist updated info
this.device.hwInfo = dingzDevices[this.device.mac];
this.accessory.context.device = this.device;
this.dingzDeviceInfo = this.device.hwInfo as DingzDeviceInfo;
this.baseUrl = `http://${this.device.address}`;
}
this.setAccessoryInformation();
this.setButtonCallbacks();
// Now we have what we need and can create the services …
this.configureOutputs(true);
this.configureBlinds(true);
// Add auxiliary services (Motion, Temperature)
if (this.dingzDeviceInfo.has_pir) {
// dingz has a Motion sensor -- let's create it
this.addMotionService();
} else {
this.log.info('This dingz has no Motion sensor.');
this.removeMotionService();
}
// dingz has a temperature sensor and an LED,
// make these available here
this.addTemperatureService();
this.addLEDService();
this.addLightSensorService();
this.addButtonServices();
}
},
)
.catch(this.handleRequestErrors.bind(this));
}
private setOutputHandlers(outputService: Service, index: number) {
outputService
.getCharacteristic(this.platform.Characteristic.On)
.on(
CharacteristicEventTypes.SET,
this.setOn.bind(this, index as DimmerIndex),
) // SET - bind to the `setOn` method below
.on(
CharacteristicEventTypes.GET,
this.getOn.bind(this, index as DimmerIndex),
);
this.eb.on(
AccessoryEvent.PUSH_STATE_UPDATE,
this.updateDimmerState.bind(this, outputService, index as DimmerIndex),
);
}
/**
* Set the accessory information
* - Firmware
* - Manufacturer
* - S/N etc.
*/
protected setAccessoryInformation(): void {
// Sanity check for "empty" SerialNumber
this.log.debug(
`Attempting to set SerialNumber (which can not be empty) -> front_sn: <${this.dingzDeviceInfo.front_sn}>`,
);
const serialNumber: string =
this.dingzDeviceInfo.front_sn === ''
? this.device.mac // MAC will always be defined for a correct device
: this.dingzDeviceInfo.front_sn;
this.accessory
.getService(this.platform.Service.AccessoryInformation)!
.setCharacteristic(this.platform.Characteristic.Manufacturer, 'iolo AG')
.setCharacteristic(
this.platform.Characteristic.AppMatchingIdentifier,
'ch.iolo.dingz.consumer',
)
// Update info from deviceInfo
.setCharacteristic(
this.platform.Characteristic.ConfiguredName,
this.accessory.displayName,
)
.setCharacteristic(
this.platform.Characteristic.Name,
this.accessory.displayName,
)
.setCharacteristic(
this.platform.Characteristic.Model,
this.device.model as string,
)
.setCharacteristic(
this.platform.Characteristic.FirmwareRevision,
this.dingzDeviceInfo.fw_version ?? 'Unknown',
)
.setCharacteristic(
this.platform.Characteristic.HardwareRevision,
this.dingzDeviceInfo.hw_version_puck ?? 'Unknown',
)
.setCharacteristic(
this.platform.Characteristic.SerialNumber,
serialNumber,
);
}
private setButtonCallbacks() {
// Only necessary for firmware version < 1.2.x
if (semver.lt(this.dingzDeviceInfo.fw_version, '1.2.0')) {
this.log.debug('Enable PIR callback for older firmware revisions');
this.enablePIRCallback();
}
this.getButtonCallbackUrl()
.then((callBackUrl) => {
if (!callBackUrl?.url.includes(this.platform.getCallbackUrl())) {
this.log.warn('Update existing callback URL ->', callBackUrl);
// Set the callback URL (Override!)
const endpoints = this.dingzDeviceInfo.has_pir
? ['generic', 'pir/single']
: ['generic'];
this.platform.setButtonCallbackUrl({
baseUrl: this.baseUrl,
token: this.device.token,
oldUrl: callBackUrl.url,
endpoints: endpoints,
});
} else {
this.log.debug('Callback URL already set ->', callBackUrl?.url);
}
})
.catch(this.handleRequestErrors.bind(this));
}
// Get updated device info and update the corresponding values
// TODO: #103, #116, #120, #123 -- fetch state for all device elements
protected getDeviceStateUpdate(): Promise<void> {
return this.getDeviceState()
.then((state) => {
if (typeof state !== 'undefined') {
// Outputs
this.dingzStates.Dimmers = state.dimmers;
this.dingzStates.LED = state.led;
// Sensors
this.dingzStates.Temperature = state.sensors.room_temperature;
this.dingzStates.Brightness = state.sensors.brightness;
// Lamellas
// TODO: assign right values
this.dingzStates.WindowCovers = state.blinds;
if (this.device.configTimestamp !== state.config.timestamp) {
// Push config change
this.device.configTimestamp = state.config.timestamp;
this.log.debug('Config changes, update accessories');
this.updateAccessory();
}
// Push the Update to HomeBridge
this.eb.emit(AccessoryEvent.PUSH_STATE_UPDATE);
return Promise.resolve();
} else {
return Promise.reject(new DeviceNotReachableError());
}
})
.catch((e: Error) => {
return Promise.reject(e);
});
}
private addTemperatureService() {
const temperatureService: Service =
this.accessory.getService(this.platform.Service.TemperatureSensor) ??
this.accessory.addService(this.platform.Service.TemperatureSensor);
temperatureService.setCharacteristic(
this.platform.Characteristic.Name,
'Temperature',
);
// create handlers for required characteristics
temperatureService
.getCharacteristic(this.platform.Characteristic.CurrentTemperature)
.on(CharacteristicEventTypes.GET, this.getTemperature.bind(this));
this.eb.on(
AccessoryEvent.PUSH_STATE_UPDATE,
this.updateTemperature.bind(this, temperatureService),
);
}
private updateTemperature(temperatureService: Service) {
const currentTemperature: number = this.dingzStates.Temperature;
temperatureService
.getCharacteristic(this.platform.Characteristic.CurrentTemperature)
.updateValue(currentTemperature);
}
/**
* Handle the "GET" requests from HomeKit
* to get the current value of the "Current Temperature" characteristic
*/
private getTemperature(callback: CharacteristicSetCallback) {
// set this to a valid value for CurrentTemperature
const currentTemperature: number = this.dingzStates.Temperature;
callback(this.reachabilityState, currentTemperature);
}
private addLightSensorService() {
// Add the LightSensor that's integrated in the dingz
// API: /api/v1/light
const lightService =
this.accessory.getService(this.platform.Service.LightSensor) ??
this.accessory.addService(this.platform.Service.LightSensor);
lightService.setCharacteristic(this.platform.Characteristic.Name, 'Light');
this.eb.on(
AccessoryEvent.PUSH_STATE_UPDATE,
this.updateLightSensor.bind(this, lightService),
);
}
private updateLightSensor(lightService: Service) {
const intensity: number = this.dingzStates.Brightness;
lightService
.getCharacteristic(this.platform.Characteristic.CurrentAmbientLightLevel)
.updateValue(intensity);
}
private configureBlinds(initHandlers = false): void {
// This is the block for the multiple services (Dimmers 1-4 / Blinds 1-2 / Buttons 1-4)
// If "Input" is set, Dimmer 1 won't work. We have to take this into account
if (!this.device.windowCoveringConfig) {
return;
}
const w: DingzWindowCoveringConfigItem[] | undefined = this.device
.windowCoveringConfig;
/** DIP Switch
* 0 M1& M2 (2 blinds)
* 1 1/2L & M2 (1 blind (M2) and 2 lights)
* 2 3/4L & M1 (1 blind (M1) and 2 lights)
* 3 1/2/3/4L (4 lights)
*/
switch (this.dingzDeviceInfo.dip_config) {
case 3:
// DIP = 0: D0, D1, D2, D3; (Subtypes) (Unless Input, then D1, D2, D3)
// D1, D2, D3
this.reconfigureWindowCovering({
id: 'M1',
connected: false,
});
this.reconfigureWindowCovering({
id: 'M2',
connected: false,
});
break;
case 2:
// DIP = 1: M1, D2, D3;
if (w && w[0]) {
this.reconfigureWindowCovering({
name: w[0].name,
id: 'M1',
index: 0,
connected: true,
initHandlers: initHandlers,
});
}
this.reconfigureWindowCovering({
id: 'M2',
connected: false,
});
// Dimmers are always 0 based
// i.e. if outputs 1 / 2 are for blinds, outputs 3/4 will be dimmer 0/1
// We use the "index" value of the dingz to determine what to use
break;
case 1:
// DIP = 2: D0, D1, M2; (Unless Input, then D1, M2);
this.reconfigureWindowCovering({
id: 'M1',
connected: false,
});
if (w && w[1]) {
// in this configuration, the second motor has the name we need
this.reconfigureWindowCovering({
name: w[1].name,
id: 'M2',
index: 1,
connected: true,
initHandlers: initHandlers,
});
}
break;
case 0:
// DIP = 3: M1, M2;
if (w && w[0] && w[1]) {
this.reconfigureWindowCovering({
name: w[0].name,
id: 'M1',
index: 0,
connected: true,
initHandlers: initHandlers,
});
this.reconfigureWindowCovering({
name: w[1].name,
id: 'M2',
index: 1,
connected: true,
initHandlers: initHandlers,
});
}
break;
default:
break;
}
}
private addButtonServices() {
// Create Buttons
this.addButtonService('dingz Button 1', '1');
this.addButtonService('dingz Button 2', '2');
this.addButtonService('dingz Button 3', '3');
this.addButtonService('dingz Button 4', '4');
// Add Event Listeners
this.platform.eb.on(
PlatformEvent.ACTION,
(mac, action: ButtonAction, button: ButtonId | '5') => {
if (mac === this.device.mac && button) {
this.log.debug(
`Button ${button} pressed -> ${action}, MAC: ${mac} (This: ${this.device.mac})`,
);
if (button === '5') {
// PUSH MOTION
if (!(this.platform.config.motionPoller ?? true)) {
this.log.debug(`Button ${button} Motion -> ${action}`);
this.log.debug('Motion Update from CALLBACK');
this.motionService
?.getCharacteristic(this.platform.Characteristic.MotionDetected)
.setValue(
action === ButtonAction.PIR_MOTION_START ? true : false,
);
}
} else {
this.dingzStates.Buttons[button].event = action ?? 1;
this.dingzStates.Buttons[button].state =
this.dingzStates.Buttons[button].state === ButtonState.OFF
? ButtonState.ON
: ButtonState.OFF;
const service = this.accessory.getServiceById(
this.platform.Service.StatelessProgrammableSwitch,
button,
);
const ProgrammableSwitchEvent = this.platform.Characteristic
.ProgrammableSwitchEvent;
service
?.getCharacteristic(
this.platform.Characteristic.ProgrammableSwitchOutputState,
)
.updateValue(this.dingzStates.Buttons[button].state);
this.log.info(
`Button ${button} (${service?.displayName}) pressed -> ${action}`,
);
switch (action) {
case ButtonAction.SINGLE_PRESS:
service
?.getCharacteristic(ProgrammableSwitchEvent)
.setValue(ProgrammableSwitchEvent.SINGLE_PRESS);
break;
case ButtonAction.DOUBLE_PRESS:
service
?.getCharacteristic(ProgrammableSwitchEvent)
.setValue(ProgrammableSwitchEvent.DOUBLE_PRESS);
break;
case ButtonAction.LONG_PRESS:
service
?.getCharacteristic(ProgrammableSwitchEvent)
.setValue(ProgrammableSwitchEvent.LONG_PRESS);
break;
}
// Immediately update states after button pressed
this.getDeviceStateUpdate();
}
}
},
);
}
private addButtonService(name: string, button: ButtonId): Service {
this.log.debug('Adding Button Service ->', name, ' -> ', button);
const buttonService =
this.accessory.getServiceById(
this.platform.Service.StatelessProgrammableSwitch,
button,
) ??
this.accessory.addService(
this.platform.Service.StatelessProgrammableSwitch,
name ?? `Button ${button}`, // Name Dimmers according to WebUI, not API info
button,
);
buttonService.setCharacteristic(
this.platform.Characteristic.Name,
name ?? `Button ${button}`,
);
buttonService.setCharacteristic(
this.platform.Characteristic.ServiceLabelIndex,
button,
);
// Stateful Programmable Switches are not anymore exposed in HomeKit. However,
// the "ProgrammableSwitchOutputState" Characteristic added to a
// StatelessProgrammableSwitch (i.e., a button), can be read out -- and used --
// by third-party apps for HomeKite, allowing users to create automations
// not only based on the button events, but also based on a state that's toggled
buttonService
.getCharacteristic(
this.platform.Characteristic.ProgrammableSwitchOutputState,
)
.on(
CharacteristicEventTypes.GET,
this.getSwitchButtonState.bind(this, button),
);
buttonService
.getCharacteristic(this.platform.Characteristic.ProgrammableSwitchEvent)
.on(CharacteristicEventTypes.GET, this.getButtonState.bind(this, button));
return buttonService;
}
private getButtonState(
button: ButtonId,
callback: CharacteristicGetCallback,
) {
const currentState = this.dingzStates.Buttons[button].event;
callback(this.reachabilityState, currentState);
}
private getSwitchButtonState(
button: ButtonId,
callback: CharacteristicGetCallback,
) {
const currentState = this.dingzStates.Buttons[button].state;
this.log.info('Get Switch State of ->', button, '-> state:', currentState);
callback(this.reachabilityState, currentState);
}
private setSwitchButtonState(
button: ButtonId,
value: CharacteristicValue,
callback: CharacteristicSetCallback,
) {
this.dingzStates.Buttons[button].state = value as ButtonState;
this.log.info('Set Switch State of ->', button, '-> state:', value);
callback(this.reachabilityState);
}
private reconfigureOutput({
name,
output,
id,
index,
initHandlers,
}: {
name: string;
output: DingzDimmerConfigValue;
id: DimmerId;
index: DimmerIndex;
initHandlers: boolean;
}): Service | undefined {
if (output === 'not_connected') {
this.removeOutput(id);
return;
}
this.log.info(
`setDimmerConfig() -> Configuring output '${name}' as '${output}' (${id}/${index})`,
);
const existing = this.accessory.getServiceById(
this.platform.Service.Lightbulb,
id,
);
const service: Service =
existing ??
this.accessory.addService(
this.platform.Service.Lightbulb,
name, // Name Dimmers according to WebUI, not API info
id,
);
// Update name
service.getCharacteristic(this.platform.Characteristic.Name).setValue(name);
// add / configure Brightness
if (
output === 'non_dimmable' &&
service.testCharacteristic(this.platform.Characteristic.Brightness)
) {
service.removeCharacteristic(
service.getCharacteristic(this.platform.Characteristic.Brightness),
);
} else if (
output !== 'non_dimmable' &&
!service.testCharacteristic(this.platform.Characteristic.Brightness)
) {
// Only add listeners if needed, i.e. if Characteristic is not yet defined
service.addCharacteristic(this.platform.Characteristic.Brightness);
service
.getCharacteristic(this.platform.Characteristic.Brightness)
.on(CharacteristicEventTypes.SET, this.setBrightness.bind(this, index)); // SET - bind to the 'setBrightness` method below
}
if (initHandlers || !existing) {
this.setOutputHandlers(service, index);
}
return service;
}
private updateDimmerState(service: Service, index: DimmerIndex): void {
if (service && index !== null) {
// index set
const state = this.dingzStates.Dimmers[index];
// Check that "state" is valid
if (state) {
if (
service.testCharacteristic(this.platform.Characteristic.Brightness)
) {
service
.getCharacteristic(this.platform.Characteristic.Brightness)
.updateValue(state.output);
}
service
.getCharacteristic(this.platform.Characteristic.On)
.updateValue(state.on);
}
}
}
private setOn(
index: DimmerIndex,
value: CharacteristicValue,
callback: CharacteristicSetCallback,
) {
this.dingzStates.Dimmers[index].on = value as boolean;
this.setDeviceDimmer(index, callback, value as boolean);
}
/**
* Handle the "GET" requests from HomeKit
*/
private getOn(index: DimmerIndex, callback: CharacteristicGetCallback) {
const isOn: boolean = this.dingzStates.Dimmers[index]?.on ?? false;
callback(this.reachabilityState, isOn);
}
private async setBrightness(
index: DimmerIndex,
value: CharacteristicValue,
callback: CharacteristicSetCallback,
) {
const isOn: boolean = value > 0 ? true : false;
this.dingzStates.Dimmers[index].output = value as number;
this.dingzStates.Dimmers[index].on = isOn;
this.setDeviceDimmer(index, callback, isOn, value as number);
}
/**
* Configure a WindowCovering
*/
private reconfigureWindowCovering({
name,
id,
index,
connected,
initHandlers = false,
}: {
name?: string;
id: string;
index?: WindowCoveringIndex;
connected: boolean;
initHandlers?: boolean;
}): void {
const existing = this.accessory.getServiceById(
this.platform.Service.WindowCovering,
id,
);
if (connected && name && index !== undefined) {
this.log.info(
`configureWindowCoveringService() -> add Blind ${name} (${id}/${index})`,
);
const service: Service =
existing ??
this.accessory.addService(
this.platform.Service.WindowCovering,
name,
id,
);
// each service must implement at-minimum the "required characteristics" for the given service type
// see https://developers.homebridge.io/#/service/Lightbulb
service
.getCharacteristic(this.platform.Characteristic.Name)
.setValue(name);
if (initHandlers || !existing) {
this.initWindowCoveringService(service, index);
}
} else if (!connected && existing) {
this.log.info(
`configureWindowCoveringService() -> remove Blind (${id}/${index})`,
);
this.accessory.removeService(existing);
}
}
// Add WindowCovering (Blinds)
private initWindowCoveringService(
service: Service,
index: WindowCoveringIndex,
): void {
// register handlers for the WindoCovering TargetPosition
service
.getCharacteristic(this.platform.Characteristic.TargetPosition)
.on(CharacteristicEventTypes.SET, this.setPosition.bind(this, index));
// Set min/max Values
// FIXME: Implement different lamella/blind modes #24
const maxTiltValue = semver.lt(this.dingzDeviceInfo.fw_version, '1.2.0')
? 90
: 100;
service
.getCharacteristic(this.platform.Characteristic.TargetHorizontalTiltAngle)
.setProps({ minValue: 0, maxValue: maxTiltValue }) // dingz Maximum values
.on(CharacteristicEventTypes.SET, this.setTiltAngle.bind(this, index));
service
.getCharacteristic(this.platform.Characteristic.CurrentPosition)
.on(CharacteristicEventTypes.GET, this.getPosition.bind(this, index));
service
.getCharacteristic(
this.platform.Characteristic.CurrentHorizontalTiltAngle,
)
.on(CharacteristicEventTypes.GET, this.getTiltAngle.bind(this, index));
service
.getCharacteristic(this.platform.Characteristic.PositionState)
.on(
CharacteristicEventTypes.GET,
this.getPositionState.bind(this, index),
);
// Subscribe to the update event
this.eb.on(
AccessoryEvent.PUSH_STATE_UPDATE,
this.updateWindowCoveringState.bind(this, index, service),
);
}
// Window Covering functions
// TODO: Use available information to more accurately set WindowCovering State
private updateWindowCoveringState(
index: WindowCoveringIndex,
service: Service,
) {
const id = this.getWindowCoveringId(index);
const state: WindowCoveringStates = this.dingzStates.WindowCovers[id];
if (state) {
/**
* TODO: Fix Hardware Buttons and UI buttons
* It can be complicated:
* - We're moving by setting new positions in the UI [x]
* - We're moving by pressing the "up/down" buttons in the UI or Hardware [x]
*/
const maxTiltValue = semver.lt(this.dingzDeviceInfo.fw_version, '1.2.0')
? 90
: 100;
service
.getCharacteristic(this.platform.Characteristic.TargetPosition)
.updateValue(state.position);
service
.getCharacteristic(
this.platform.Characteristic.TargetHorizontalTiltAngle,
)
.updateValue((state.lamella / 100) * maxTiltValue); // Old FW: Set in °, Get in % (...)
let positionState: number;
switch (state.moving) {
case 'up':
positionState = this.platform.Characteristic.PositionState.INCREASING;
break;
case 'down':
positionState = this.platform.Characteristic.PositionState.DECREASING;
break;
case 'stop':
positionState = this.platform.Characteristic.PositionState.STOPPED;
service
.getCharacteristic(this.platform.Characteristic.CurrentPosition)
.updateValue(state.position);
service
.getCharacteristic(
this.platform.Characteristic.CurrentHorizontalTiltAngle,
)
.updateValue((state.lamella / 100) * maxTiltValue); // Set in °, Get in % (...)
break;
}
service
.getCharacteristic(this.platform.Characteristic.PositionState)
.updateValue(positionState);
}
}
private async setPosition(
index: WindowCoveringIndex,
position: CharacteristicValue,
callback: CharacteristicSetCallback,
) {
const id = this.getWindowCoveringId(index);
const windowCovering = this.dingzStates.WindowCovers[id];
if (windowCovering) {
// Make sure we're setting motion when changing the position
if (position > windowCovering.position) {
windowCovering.moving = 'up';
} else if (position < windowCovering.position) {
windowCovering.moving = 'down';
} else {
windowCovering.moving = 'stop';
}
this.log.warn('Blinds moving: ', windowCovering.moving, '-->', position);
await this.setWindowCovering({
id: id,
blind: position as number,
lamella: windowCovering.lamella,
callback: callback,
});
}
}
private getPosition(
index: WindowCoveringIndex,
callback: CharacteristicGetCallback,
) {
this.log.debug(
'WindowCoverings: ',
JSON.stringify(this.dingzStates.WindowCovers),
);
const id = this.getWindowCoveringId(index);
const blind: number = this.dingzStates.WindowCovers[id]?.position;
this.log.debug(
'Get Characteristic for WindowCovering',
index,
'Current Position ->',
blind,
);
callback(this.reachabilityState, blind);
}
private async setTiltAngle(
index: WindowCoveringIndex,
angle: CharacteristicValue,
callback: CharacteristicSetCallback,
) {
this.log.debug(
'Set Characteristic TargetHorizontalTiltAngle on ',
index,
'->',
angle,
);
const id = this.getWindowCoveringId(index);
if (this.dingzStates.WindowCovers[id]) {
await this.setWindowCovering({
id: id,
blind: this.dingzStates.WindowCovers[id].position,
lamella: angle as number,
callback: callback,
});
}
}
/**
* Handle the "GET" requests from HomeKit
*/
private getTiltAngle(
index: WindowCoveringIndex,
callback: CharacteristicGetCallback,
) {
this.log.debug(
'WindowCoverings: ',
JSON.stringify(this.dingzStates.WindowCovers),
);
const id = this.getWindowCoveringId(index);
const tiltAngle: number = this.dingzStates.WindowCovers[id]?.lamella;
this.log.debug(
'Get Characteristic for WindowCovering',
index,
'Current TiltAngle ->',
tiltAngle,
);
callback(this.reachabilityState, tiltAngle);
}
private getPositionState(
index: WindowCoveringIndex,
callback: CharacteristicGetCallback,
) {
this.log.debug(
'WindowCoverings: ',
JSON.stringify(this.dingzStates.WindowCovers),
);
let positionState = this.platform.Characteristic.PositionState.STOPPED;
const id = this.getWindowCoveringId(index);
const moving = this.dingzStates.WindowCovers[id]?.moving;
if (moving) {
switch (moving) {
case 'down':
positionState = this.platform.Characteristic.PositionState.DECREASING;
break;
case 'up':
positionState = this.platform.Characteristic.PositionState.INCREASING;
break;
case 'stop':
positionState = this.platform.Characteristic.PositionState.STOPPED;
break;
}
this.log.debug(
'Get Characteristic for WindowCovering',
index,
'Current Position State ->',
positionState,
);
}
callback(this.reachabilityState, positionState);
}
/**
* Motion Service Methods
*/
private addMotionService() {
this.motionService =
this.accessory.getService(this.platform.Service.MotionSensor) ??
this.accessory.addService(this.platform.Service.MotionSensor);
this.motionService.setCharacteristic(
this.platform.Characteristic.Name,
'Motion',
);
// Only check for motion if we have a PIR and set the Interval