generated from homebridge/homebridge-plugin-template
/
platform.ts
1062 lines (961 loc) · 34.3 KB
/
platform.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 { APIEvent } from 'homebridge';
import type {
API,
DynamicPlatformPlugin,
Logger,
PlatformAccessory,
PlatformConfig,
} from 'homebridge';
import { Policy, ConsecutiveBreaker } from 'cockatiel';
import { createSocket, Socket, RemoteInfo } from 'dgram';
import axios, { AxiosError } from 'axios';
import axiosRetry from 'axios-retry';
import * as bodyParser from 'body-parser';
import i4h from 'intervals-for-humans';
import chalk from 'chalk';
import isValidHost from 'is-valid-host';
import * as os from 'os';
import e = require('express');
// Internal Types
import { ButtonId, DingzDeviceInfo } from './lib/dingzTypes';
import { MyStromDeviceInfo, MyStromSwitchTypes } from './lib/myStromTypes';
import {
DeviceInfo,
AccessoryTypes,
DeviceTypes,
AccessoryType,
ButtonAction,
} from './lib/commonTypes';
import {
InvalidTypeError,
DeviceNotImplementedError,
DeviceNotReachableError,
} from './lib/errors';
import {
PLATFORM_NAME,
PLUGIN_NAME,
DINGZ_DISCOVERY_PORT,
DINGZ_CALLBACK_PORT,
STATE_UPDATE_INTERVAL,
} from './settings';
// TODO: Some refactoring for better event handling, cleanup of the code and separation of concerns
import { PlatformEventBus, PlatformEvent } from './lib/platformEventBus';
// Accessory classes
import { DingzAccessory } from './dingzAccessory';
import { MyStromSwitchAccessory } from './myStromSwitchAccessory';
import { MyStromLightbulbAccessory } from './myStromLightbulbAccessory';
import { MyStromButtonAccessory } from './myStromButtonAccessory';
import { MyStromPIRAccessory } from './myStromPIRAccessory';
// Define a policy that will retry 20 times at most
const retry = Policy.handleAll()
.retry()
.attempts(20)
.exponential({
maxDelay: i4h('1h') as number,
initialDelay: i4h('2s') as number,
});
// Create a circuit breaker that'll stop calling the executed function for 10
// seconds if it fails 5 times in a row. This can give time for e.g. a database
// to recover without getting tons of traffic.
const circuitBreaker = Policy.handleAll().circuitBreaker(
10 * 1000,
new ConsecutiveBreaker(5),
);
const retryWithBreaker = Policy.wrap(retry, circuitBreaker);
/**
* HomebridgePlatform
* This class is the main constructor for the plugin, this is where you should
* parse the user config and discover/register accessories with Homebridge.
*/
export class DingzDaHomebridgePlatform implements DynamicPlatformPlugin {
public readonly Service = this.api.hap.Service;
public readonly Characteristic = this.api.hap.Characteristic;
public readonly eb = new PlatformEventBus();
// this is used to track restored cached accessories
public accessories: AccessoryTypes = {};
private discovered = new Map();
private readonly app: e.Application = e();
constructor(
public readonly log: Logger,
public readonly config: PlatformConfig,
public readonly api: API,
) {
axiosRetry(axios, { retries: 5, retryDelay: axiosRetry.exponentialDelay });
this.log.debug(
chalk.redBright('[Platform]'),
'Finished initializing platform:',
this.config.name,
);
// When this event is fired it means Homebridge has restored all cached accessories from disk.
// Dynamic Platform plugins should only register new accessories after this event was fired,
// in order to ensure they weren't added to homebridge already. This event can also be used
// to start discovery of new accessories.
this.api.on(APIEvent.DID_FINISH_LAUNCHING, () => {
this.log.debug('Executed didFinishLaunching callback');
// Adds decvices from Config
if (this.config.devices) {
this.addDevices();
}
// Discovers devices from UDP
if (this.config.autoDiscover) {
this.setupDeviceDiscovery();
}
// set-up the callback server ...
this.callbackServer();
this.eb.on(PlatformEvent.REQUEST_STATE_UPDATE, () => {
this.log.debug('Event -> PlatformEvent.REQUEST_STATE_UPDATE');
});
// Set the update interval in seconds
const updateInterval: number =
!this.config.pollerInterval ||
this.config.pollerInterval < STATE_UPDATE_INTERVAL
? STATE_UPDATE_INTERVAL
: this.config.pollerInterval;
this.log.debug(`Platform poll interval: ${updateInterval}s`);
setInterval(() => {
this.eb.emit(PlatformEvent.REQUEST_STATE_UPDATE);
}, updateInterval * 1000);
});
}
/**
* This function is invoked when homebridge restores cached accessories from disk at startup.
* It should be used to setup event handlers for characteristics and update respective values.
*/
configureAccessory(accessory: PlatformAccessory): void {
this.log.info(
'Restoring accessory from cache:',
accessory.displayName,
'->',
accessory.context.device.accessoryClass,
);
// TODO: Remove the device if it has vanished for too long (i.e. restore was not possible for a long time)
const context = accessory.context;
let platformAccessory: AccessoryType;
if (context.device && context.device.accessoryClass) {
this.log.debug(
'Restoring accessory of class ->',
context.device.accessoryClass,
);
switch (context.device.accessoryClass) {
case 'DingzDaAccessory':
// add the restored accessory to the accessories cache so we can track if it has already been registered
platformAccessory = new DingzAccessory(this, accessory);
break;
case 'MyStromSwitchAccessory':
// add the restored accessory to the accessories cache so we can track if it has already been registered
platformAccessory = new MyStromSwitchAccessory(this, accessory);
break;
case 'MyStromLightbulbAccessory':
// add the restored accessory to the accessories cache so we can track if it has already been registered
platformAccessory = new MyStromLightbulbAccessory(this, accessory);
break;
case 'MyStromButtonAccessory':
// add the restored accessory to the accessories cache so we can track if it has already been registered
platformAccessory = new MyStromButtonAccessory(this, accessory);
break;
case 'MyStromPIRAccessory':
// add the restored accessory to the accessories cache so we can track if it has already been registered
platformAccessory = new MyStromPIRAccessory(this, accessory);
break;
default:
this.log.warn(
'No Accessory type defined for Accessory',
accessory.displayName,
'can not restore',
);
return;
}
this.accessories[accessory.UUID] = platformAccessory;
} else {
this.log.warn(
'No Accessory device context for Accessory',
accessory.displayName,
'can not restore',
);
}
}
private addDevices() {
// loop over the discovered devices and register each one if it has not already been registered
for (const device of this.config.devices) {
// Call addDevice, retry until found
this.log.info('Add Device from config: ', device.type, '->', device.name);
switch (device.type) {
case 'dingz':
retryWithBreaker.execute(() =>
this.addDingzDevice({
address: device.address,
name: device.name,
token: device.token ?? this.config.globalToken,
}),
);
break;
case 'myStromSwitch':
retryWithBreaker.execute(() =>
this.addMyStromSwitchDevice({
address: device.address,
name: device.name,
token: device.token ?? this.config.globalToken,
}),
);
break;
case 'myStromBulb':
case 'myStromLED': // Share the same code
retryWithBreaker.execute(() =>
this.addMyStromLightbulbDevice({
address: device.address,
name: device.name,
token: device.token ?? this.config.globalToken,
}),
);
break;
case 'myStromPIR':
retryWithBreaker.execute(() =>
this.addMyStromPIRDevice({
address: device.address,
name: device.name,
token: device.token ?? this.config.globalToken,
}),
);
break;
default:
this.log.info(
'Device type',
device.deviceType,
'is currently unsupported. Will skip',
);
break;
}
}
}
// Add one device based on address and name
private async addDingzDevice({
address,
name = 'dingz',
token,
}: {
address: string;
name?: string;
token?: string;
}): Promise<boolean> {
// Run a diacovery of changed things every 10 seconds
this.log.debug(
`addDingzDevice() --> Add configured device -> ${name} (${address})`,
);
return await DingzAccessory.getConfigs({
address: address,
token: token,
})
.then(({ dingzDevices, systemConfig: dingzConfig }) => {
this.log.debug('Got Device ->', JSON.stringify(dingzDevices));
if (typeof dingzDevices !== 'undefined') {
const keys = Object.keys(dingzDevices);
const mac = keys[0]; // keys[0]
const info: DingzDeviceInfo = dingzDevices[mac];
if (info.type !== 'dingz') {
throw new InvalidTypeError(
`Device ${name} at ${address} is of the wrong type (${info.type} instead of "dingz")`,
);
}
// Fixme: Fetch more info about the Device (particularly Name)
const deviceInfo: DeviceInfo = {
name: dingzConfig.dingz_name,
address: address,
mac: mac.toUpperCase(),
token: token,
model: info.front_hw_model ?? 'dingz',
hwInfo: info,
accessoryClass: 'DingzDaAccessory',
};
const uuid = this.api.hap.uuid.generate(deviceInfo.mac);
// check that the device has not already been registered by checking the
// cached devices we stored in the `configureAccessory` method above
if (!this.accessories[uuid]) {
this.log.info('Registering new accessory:', deviceInfo.name);
// create a new accessory
const accessory = new this.api.platformAccessory(
deviceInfo.name,
uuid,
);
// store a copy of the device object in the `accessory.context`
// the `context` property can be used to store any data about the accessory you may need
accessory.context.device = deviceInfo;
// create the accessory handler (which will add services as needed)
// this is imported from `dingzDaAccessory.ts`
const dingzDaAccessory = new DingzAccessory(this, accessory);
// link the accessory to your platform
this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [
accessory,
]);
// push into accessory cache
this.accessories[uuid] = dingzDaAccessory;
return true;
} else {
this.log.warn('Accessory already initialized');
// Update Names et al. from new device info
// Might be needed e.g. when IP address changes
this.eb.emit(PlatformEvent.UPDATE_DEVICE_INFO, deviceInfo);
this.accessories[uuid].identify();
return true;
}
} else {
return false;
}
})
.catch((e) => {
if (e instanceof DeviceNotReachableError) {
this.log.error(
`addDingzDevice() --> Device not reachable -> ${name} (${address})`,
);
return false;
} else {
throw e;
}
});
}
// Add one device based on address and name
private addMyStromSwitchDevice({
address,
name = 'Switch',
token,
}: {
address: string;
name?: string;
token?: string;
}): boolean {
// Run a diacovery of changed things every 10 seconds
this.log.debug(`Add configured/discovered device -> ${name} (${address})`);
const success = this.getMyStromDeviceInfo({
address,
token,
endpoint: 'info', // We use the old endpoint
}).then((data) => {
if (typeof data !== 'undefined') {
const info = data as MyStromDeviceInfo;
if (
// FIXME: Fix the API Documentation
// The type info returned varies with Firmware versions.
// Newer Firmwares seem to have string-based types whereas
// older ones use the numbers from the API documentation
info.type !== 'WS2' &&
info.type !== 106 &&
info.type !== 'WSEU' &&
info.type !== 107 &&
info.type !== undefined // Switch V1 does not have a type
) {
throw new InvalidTypeError(
`Device ${name} at ${address} is of the wrong type (${info.type} instead of "myStrom Switch")`,
);
}
const deviceInfo: DeviceInfo = {
name: name,
address: address,
mac: info.mac.toUpperCase(),
token: token,
model: MyStromSwitchTypes[info.type] ?? 'CH v1',
hwInfo: info,
accessoryClass: 'MyStromSwitchAccessory',
};
const uuid = this.api.hap.uuid.generate(deviceInfo.mac);
// check that the device has not already been registered by checking the
// cached devices we stored in the `configureAccessory` method above
if (!this.accessories[uuid]) {
this.log.info('Registering new accessory:', deviceInfo.name);
// create a new accessory
const accessory = new this.api.platformAccessory(
deviceInfo.name,
uuid,
);
// store a copy of the device object in the `accessory.context`
// the `context` property can be used to store any data about the accessory you may need
accessory.context.device = deviceInfo;
// create the accessory handler (which will add services as needed)
// this is imported from `dingzDaAccessory.ts`
const myStromSwitchAccessory = new MyStromSwitchAccessory(
this,
accessory,
);
// link the accessory to your platform
this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [
accessory,
]);
// push into accessory cache
this.accessories[uuid] = myStromSwitchAccessory;
return true;
} else {
this.log.warn('Accessory already initialized');
this.eb.emit(PlatformEvent.UPDATE_DEVICE_INFO, deviceInfo);
this.accessories[uuid].identify();
return true;
}
}
});
// Nothing found, throw error
if (!success) {
throw new DeviceNotReachableError(
`Device not found -> ${name} (${address})`,
);
}
return true;
}
// Add one device based on address and name
private addMyStromLightbulbDevice({
address,
name = 'Lightbulb/LED',
token,
}: {
address: string;
name?: string;
token?: string;
}): boolean {
// Run a diacovery of changed things every 10 seconds
this.log.debug(`Add configured/discovered device -> ${name} (${address})`);
const success = this.getMyStromDeviceInfo({
address,
token,
}).then((data) => {
if (typeof data !== 'undefined') {
const info = data as MyStromDeviceInfo;
if (info.type !== 102 && info.type !== 105 && info.type !== 'WRS') {
throw new InvalidTypeError(
`Device ${name} at ${address} is of the wrong type (${info.type} instead of "myStrom Lightbulb")`,
);
}
const deviceInfo: DeviceInfo = {
name: info.name ?? name,
address: address,
mac: info.mac.toUpperCase(),
token: token,
model: '102',
hwInfo: info,
accessoryClass: 'MyStromLightbulbAccessory',
};
const uuid = this.api.hap.uuid.generate(deviceInfo.mac);
// check that the device has not already been registered by checking the
// cached devices we stored in the `configureAccessory` method above
if (!this.accessories[uuid]) {
this.log.info('Registering new accessory:', deviceInfo.name);
// create a new accessory
const accessory = new this.api.platformAccessory(
deviceInfo.name,
uuid,
);
// store a copy of the device object in the `accessory.context`
// the `context` property can be used to store any data about the accessory you may need
accessory.context.device = deviceInfo;
// create the accessory handler (which will add services as needed)
// this is imported from `dingzDaAccessory.ts`
const myStromLightbulbAccessory = new MyStromLightbulbAccessory(
this,
accessory,
);
// link the accessory to your platform
this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [
accessory,
]);
// push into accessory cache
this.accessories[uuid] = myStromLightbulbAccessory;
return true;
} else {
this.log.warn('Accessory already initialized');
this.eb.emit(PlatformEvent.UPDATE_DEVICE_INFO, deviceInfo);
this.accessories[uuid].identify();
return true;
}
}
});
// Nothing found, throw error
if (!success) {
throw new DeviceNotReachableError(
`Device not found -> ${name} (${address})`,
);
}
return true;
}
// Add one device based on address and name
private addMyStromPIRDevice({
address,
name,
token,
}: {
address: string;
name?: string;
token?: string;
}): boolean {
// Run a diacovery of changed things every 10 seconds
this.log.debug(
`Add configured/discovered myStrom PIR device -> (${address})`,
);
const success = this.getMyStromDeviceInfo({
address,
token,
}).then((data) => {
if (typeof data !== 'undefined') {
const info = data as MyStromDeviceInfo;
// Need this to identify the right type
if (info.type !== 110) {
throw new InvalidTypeError(
`Device ${name} at ${address} is of the wrong type (${info.type} instead of "myStrom Lightbulb")`,
);
}
const pirName: string =
name ?? 'my PIR ' + info.mac.toUpperCase().substr(6, 6);
const deviceInfo: DeviceInfo = {
name: pirName,
address: address,
mac: info.mac.toUpperCase(),
token: token,
model: '110',
hwInfo: info as MyStromDeviceInfo,
accessoryClass: 'MyStromPIRAccessory',
};
const uuid = this.api.hap.uuid.generate(deviceInfo.mac);
// check that the device has not already been registered by checking the
// cached devices we stored in the `configureAccessory` method above
if (!this.accessories[uuid]) {
this.log.info('Registering new accessory:', deviceInfo.name);
// create a new accessory
const accessory = new this.api.platformAccessory(
deviceInfo.name,
uuid,
);
// store a copy of the device object in the `accessory.context`
// the `context` property can be used to store any data about the accessory you may need
accessory.context.device = deviceInfo;
// create the accessory handler (which will add services as needed)
// this is imported from `dingzDaAccessory.ts`
const myStromPIRAccessory = new MyStromPIRAccessory(this, accessory);
// link the accessory to your platform
this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [
accessory,
]);
// push into accessory cache
this.accessories[uuid] = myStromPIRAccessory;
return true;
} else {
this.log.warn('Accessory already initialized');
this.eb.emit(PlatformEvent.UPDATE_DEVICE_INFO, deviceInfo);
this.accessories[uuid].identify();
return true;
}
}
});
// Nothing found, throw error
if (!success) {
throw new DeviceNotReachableError(
`Device not found -> ${name} (${address})`,
);
}
return true;
}
// Add one device based on address and name
private addMyStromButtonDevice({
address,
name = 'Button',
token,
mac,
}: {
address: string;
name?: string;
token?: string;
mac: string;
}): boolean {
// Run a diacovery of changed things every 10 seconds
this.log.debug(
`Add configured/discovered myStrom Button device -> ${name} (${address})`,
);
const deviceInfo: DeviceInfo = {
name: name,
address: address,
mac: mac?.toUpperCase(),
token: token,
model: '104',
accessoryClass: 'MyStromButtonAccessory',
};
const uuid = this.api.hap.uuid.generate(deviceInfo.mac);
// check that the device has not already been registered by checking the
// cached devices we stored in the `configureAccessory` method above
if (!this.accessories[uuid]) {
this.log.info('Registering new accessory:', name);
// create a new accessory
const accessory = new this.api.platformAccessory(name, uuid);
// store a copy of the device object in the `accessory.context`
// the `context` property can be used to store any data about the accessory you may need
accessory.context.device = deviceInfo;
// create the accessory handler (which will add services as needed)
// this is imported from `dingzDaAccessory.ts`
const myStromButtonAccessory = new MyStromButtonAccessory(
this,
accessory,
);
// link the accessory to your platform
this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [
accessory,
]);
// push into accessory cache
this.accessories[uuid] = myStromButtonAccessory;
// Buttons can be initialized without fetching all Info -- however it would be good to fetch it anyway
this.getMyStromDeviceInfo({
address,
token,
}).then((data) => {
if (typeof data !== 'undefined') {
const info = data as MyStromDeviceInfo;
if (info.type !== 104) {
throw new InvalidTypeError(
`Device ${name} at ${address} is of the wrong type (${info.type} instead of "myStrom Button")`,
);
}
accessory.context.device.hwInfo = info;
}
});
return true;
} else {
this.log.warn('Accessory already initialized');
this.eb.emit(PlatformEvent.UPDATE_DEVICE_INFO, deviceInfo);
this.accessories[uuid].identify();
return true;
}
return false;
// Won't work ...
const success = this.getMyStromDeviceInfo({
address,
token,
}).then((data) => {
if (typeof data !== 'undefined') {
const info = data as MyStromDeviceInfo;
if (info.type !== 104) {
throw new InvalidTypeError(
`Device ${name} at ${address} is of the wrong type (${info.type} instead of "myStrom Lightbulb")`,
);
}
const deviceInfo: DeviceInfo = {
name: info.name ?? name,
address: address,
mac: info.mac.toUpperCase(),
token: token,
model: '102',
hwInfo: info,
accessoryClass: 'MyStromLightbulbAccessory',
};
const uuid = this.api.hap.uuid.generate(deviceInfo.mac);
// check that the device has not already been registered by checking the
// cached devices we stored in the `configureAccessory` method above
if (!this.accessories[uuid]) {
this.log.info('Registering new accessory:', deviceInfo.name);
// create a new accessory
const accessory = new this.api.platformAccessory(
deviceInfo.name,
uuid,
);
// store a copy of the device object in the `accessory.context`
// the `context` property can be used to store any data about the accessory you may need
accessory.context.device = deviceInfo;
// create the accessory handler (which will add services as needed)
// this is imported from `dingzDaAccessory.ts`
const myStromLightbulbAccessory = new MyStromLightbulbAccessory(
this,
accessory,
);
// link the accessory to your platform
this.api.registerPlatformAccessories(PLUGIN_NAME, PLATFORM_NAME, [
accessory,
]);
// push into accessory cache
this.accessories[uuid] = myStromLightbulbAccessory;
return true;
} else {
this.log.warn('Accessory already initialized');
this.accessories[uuid].identify();
return true;
}
}
});
// Nothing found, throw error
if (!success) {
throw new DeviceNotReachableError(
`Device not found -> ${name} (${address})`,
);
}
return true;
}
private datagramMessageHandler(msg: Uint8Array, remoteInfo: RemoteInfo) {
// const mac: string = dataBuffer.toString('hex', 0, 6);
try {
if (msg.length !== 8) {
throw new DeviceNotImplementedError('Detected data can not be parsed.');
}
const t: DeviceTypes = msg[6];
const mac: string = this.byteToHexString(msg.subarray(0, 6));
const deviceSuffix: string = mac.substr(6, 6);
if (!this.discovered.has(mac)) {
switch (t) {
case DeviceTypes.MYSTROM_BUTTON_PLUS:
throw new DeviceNotImplementedError(
`Device discovered at ${remoteInfo.address} of unsupported type ${DeviceTypes[t]}`,
);
break;
case DeviceTypes.MYSTROM_BUTTON:
retryWithBreaker
.execute(() => {
this.addMyStromButtonDevice({
address: remoteInfo.address,
name: `Button ${deviceSuffix}`,
token: this.config.globalToken,
mac: mac,
});
})
.then(() => {
this.discovered.set(mac, remoteInfo);
});
break;
case DeviceTypes.MYSTROM_LEDSTRIP:
retryWithBreaker
.execute(() => {
this.addMyStromLightbulbDevice({
address: remoteInfo.address,
name: `LED Strip ${deviceSuffix}`,
token: this.config.globalToken,
});
})
.then(() => {
this.discovered.set(mac, remoteInfo);
});
break;
case DeviceTypes.MYSTROM_BULB:
retryWithBreaker
.execute(() => {
this.addMyStromLightbulbDevice({
address: remoteInfo.address,
name: `Lightbulb ${deviceSuffix}`,
token: this.config.globalToken,
});
})
.then(() => {
this.discovered.set(mac, remoteInfo);
});
break;
case DeviceTypes.MYSTROM_SWITCH_CHV1:
case DeviceTypes.MYSTROM_SWITCH_CHV2:
case DeviceTypes.MYSTROM_SWITCH_EU:
retryWithBreaker
.execute(() => {
this.addMyStromSwitchDevice({
address: remoteInfo.address,
name: `Switch ${deviceSuffix}`,
token: this.config.globalToken,
});
})
.then(() => {
this.discovered.set(mac, remoteInfo);
});
break;
case DeviceTypes.MYSTROM_PIR:
retryWithBreaker
.execute(() => {
this.addMyStromPIRDevice({
address: remoteInfo.address,
name: `Motion Sensor ${deviceSuffix}`,
token: this.config.globalToken,
});
})
.then(() => {
this.discovered.set(mac, remoteInfo);
});
break;
case DeviceTypes.DINGZ:
retryWithBreaker
.execute(() => {
this.addDingzDevice({
address: remoteInfo.address,
name: `DINGZ ${deviceSuffix}`,
token: this.config.globalToken,
});
})
.then(() => {
this.discovered.set(mac, remoteInfo);
});
break;
default:
this.log.warn(`Unknown device: ${t}`);
break;
}
} else {
this.log.debug('Stopping discovery of already known device:', mac);
}
} catch (e) {
if (e instanceof DeviceNotImplementedError) {
// Degrade gracefully if type not found
this.log.warn(e.message);
} else if (e instanceof DeviceNotReachableError) {
this.log.warn(e.message);
} else {
throw e;
}
}
}
// Steup device discovery. This will run for 10 minutes and then stop
// If you want tore-discover, just restart Homebridge
private setupDeviceDiscovery() {
const discoverySocket: Socket = createSocket({
type: 'udp4',
});
discoverySocket.on('message', this.datagramMessageHandler.bind(this));
this.log.info('Starting discovery');
discoverySocket.bind(DINGZ_DISCOVERY_PORT);
setTimeout(() => {
this.log.info('Stopping discovery');
discoverySocket.close();
}, 600000); // Discover for 10 min then stop
return true;
}
private getAccessoryByMac(mac: string): AccessoryType {
const uuid = this.api.hap.uuid.generate(mac.toUpperCase());
return this.accessories[uuid];
}
// Set the callback URL for the device
// FIXME: Move this to a platform accessory base class
public async setButtonCallbackUrl({
baseUrl,
token,
oldUrl,
endpoints,
}: {
baseUrl: string;
token?: string;
oldUrl?: string;
endpoints: string[];
}): Promise<void> {
const setActionUrl = `${baseUrl}/api/v1/action/`;
let callbackUrl: string = this.getCallbackUrl();
if (oldUrl?.endsWith('||')) {
callbackUrl = `${oldUrl}${callbackUrl}`;
} else if (oldUrl) {
callbackUrl = `${oldUrl}||${callbackUrl}`;
}
this.log.debug('Setting the callback URL -> ', callbackUrl);
endpoints.forEach((endpoint) => {
this.log.debug(setActionUrl, 'Endpoint -> ', endpoint);
axios
.post(`${setActionUrl}${endpoint}`, callbackUrl, {
headers: { Token: token ?? '' },
})
.catch(this.handleError.bind(this));
});
}
// Create a Service to listen for dingz Button events
private callbackServer() {
this.app.use(bodyParser.urlencoded());
this.app.post('/button', this.handleRequest.bind(this));
this.app.listen(this.config.callbackPort ?? DINGZ_CALLBACK_PORT, () =>
this.log.warn(
`Callback server listening for POST requests on ${
this.config.callbackPort ?? DINGZ_CALLBACK_PORT
}... use ${this.getCallbackUrl()} as URL for your dingz or MyStrom callbacks`,
),
);
}
private handleRequest(request: e.Request, response: e.Response) {
if (request.url) {
response.writeHead(204); // 204 No content
response.end(() => {
this.log.debug('Incoming request ->', request.body);
const b = request.body;
const mac: string = b.mac ?? '';
const button = b.index;
const action = b.action;
const battery = b.battery;
// Various types of callbacks
if (button) {
this.log.info(chalk.blueBright('[ACTION] dingz'), request.ip);
// attempt-auto add of either a dingz
if (
request.connection.remoteAddress &&
isValidHost(request.connection.remoteAddress)
) {
this.addDingzDevice({ address: request.connection.remoteAddress });
}
this.eb.emit(
PlatformEvent.ACTION,
mac,
action as ButtonAction,
button as ButtonId,
);
} else {
if (action) {
this.log.info(chalk.blueBright('[ACTION] Simple'), request.ip);
this.eb.emit(
PlatformEvent.ACTION,
mac,
action as ButtonAction,
battery as number,
);
} else {
this.log.info(chalk.blueBright('[HEARTBEAT]'), request.ip);
this.eb.emit(
PlatformEvent.ACTION,
mac,
action as ButtonAction,
battery,
);
}
}
});
}
}
public getCallbackUrl(): string {