forked from MrTomAsh/homebridge-ewelink
-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathindex.js
2716 lines (2261 loc) · 116 KB
/
index.js
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
/* jshint -W030, -W069, esversion: 6 */
let WebSocket = require('ws');
let http = require('http');
let url = require('url');
const querystring = require('querystring');
let request = require('request-json');
let nonce = require('nonce')();
let crypto = require('crypto');
let LanClient = require('./lib/sonoffLanModeApi');
let wsc;
let isSocketOpen = false;
let sequence = 0;
let webClient = '';
let apiKey = 'UNCONFIGURED';
let authenticationToken = 'UNCONFIGURED';
let Accessory, Service, Characteristic, UUIDGen;
module.exports = function (homebridge) {
console.log("homebridge API version: " + homebridge.version);
// Accessory must be created from PlatformAccessory Constructor
Accessory = homebridge.platformAccessory;
// Service and Characteristic are from hap-nodejs
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
UUIDGen = homebridge.hap.uuid;
// For platform plugin to be considered as dynamic platform plugin,
// registerPlatform(pluginName, platformName, constructor, dynamic), dynamic must be true
homebridge.registerPlatform("homebridge-eWeLink", "eWeLink", eWeLink, true);
};
// Platform constructor
function eWeLink(log, config, api) {
let platform = this;
this.log = log;
this.config = config;
this.accessories = new Map();
this.authenticationToken = config['authenticationToken'];
this.devicesFromApi = new Map();
// platform.log(JSON.stringify(config, null, " "));
if (!config || (!config['authenticationToken'] && ((!config['phoneNumber'] && !config['email']) || !config['password'] || !config['imei']))) {
log("Initialization skipped. Missing configuration data.");
return;
}
if (!config['apiHost']) {
config['apiHost'] = 'eu-api.coolkit.cc:8080';
}
if (!config['webSocketApi']) {
config['webSocketApi'] = 'us-pconnect3.coolkit.cc';
}
platform.log("Initialising eWeLink");
// Groups configuration
this.groups = new Map();
let configGroups = config['groups'] || null;
if (configGroups) {
if (Object.keys(configGroups).length > 0) {
this.config.groups.forEach((group) => {
this.groups.set(group.deviceId, group);
});
}
}
platform.log("Found %s group(s)", this.groups.size);
if (api) {
// Save the API object as plugin needs to register new accessory via this object
this.api = api;
// Listen to event "didFinishLaunching", this means homebridge already finished loading cached accessories.
// Platform Plugin should only register new accessory that doesn't exist in homebridge after this event.
// Or start discover new accessories.
this.api.on('didFinishLaunching', function () {
platform.log("A total of [%s] accessories were loaded from the local cache", platform.accessories.size);
let afterLogin = function () {
// Get a list of all devices from the API, and compare it to the list of cached devices.
// New devices will be added, and devices that exist in the cache but not in the web list
// will be removed from Homebridge.
let url = 'https://' + this.config['apiHost'];
platform.log("Requesting a list of devices from eWeLink HTTPS API at [%s]", url);
this.webClient = request.createClient(url);
this.webClient.headers['Authorization'] = 'Bearer ' + this.authenticationToken;
this.webClient.get('/api/user/device?' + this.getArguments(), function (err, res, body) {
if (err) {
platform.log("An error was encountered while requesting a list of devices. Error was [%s]", err);
return;
} else if (!body) {
platform.log("An error was encountered while requesting a list of devices. No data in response.");
return;
} else if (body.hasOwnProperty('error') && body.error != 0) {
let response = JSON.stringify(body);
platform.log("An error was encountered while requesting a list of devices. Response was [%s]", response);
if (body.error === '401') {
platform.log("Verify that you have the correct authenticationToken specified in your configuration. The currently-configured token is [%s]", platform.authenticationToken);
}
return;
}
body = body.devicelist;
let size = Object.keys(body).length;
platform.log("eWeLink HTTPS API reports that there are a total of [%s] devices registered", size);
if (size === 0) {
platform.log("As there were no devices were found, all devices have been removed from the platform's cache. Please regiester your devices using the eWeLink app and restart HomeBridge");
platform.api.unregisterPlatformAccessories("homebridge-eWeLink", "eWeLink", Array.from(platform.accessories.values()));
platform.accessories.clear();
return;
}
body.forEach((device) => {
platform.apiKey = device.apikey;
// Skip Sonoff Bridge as it is not supported by this plugin
if (['RF_BRIDGE'].indexOf(platform.getDeviceTypeByUiid(device.uiid)) == -1) {
platform.devicesFromApi.set(device.deviceid, device);
}
});
// Now we compare the cached devices against the web list
platform.log("Evaluating if devices need to be removed...");
function checkIfDeviceIsStillRegistered(value, deviceId, map) {
let accessory = platform.accessories.get(deviceId);
// To handle grouped accessories
var realDeviceId = deviceId;
if (accessory.context.switches > 1) {
realDeviceId = deviceId.replace('CH' + accessory.context.channel, "");
}
if (platform.devicesFromApi.has(realDeviceId) && (accessory.context.switches <= 1 || accessory.context.channel <= accessory.context.switches)) {
if ((deviceId != realDeviceId) && platform.groups.has(realDeviceId)) {
platform.log('Device [%s], ID : [%s] is now grouped. It will be removed.', accessory.displayName, accessory.UUID);
platform.removeAccessory(accessory);
} else if ((deviceId == realDeviceId) && !platform.groups.has(realDeviceId)) {
platform.log('Device [%s], ID : [%s] is now splitted. It will be removed.', accessory.displayName, accessory.UUID);
platform.removeAccessory(accessory);
} else if (platform.getDeviceTypeByUiid(platform.devicesFromApi.get(realDeviceId).uiid) === 'FAN_LIGHT' && accessory.context.channel !== null) {
platform.log('Device [%s], ID : [%s] is now grouped as a fan. It will be removed.', accessory.displayName, accessory.UUID);
platform.removeAccessory(accessory);
} else {
platform.log('[%s] Device is registered with API. ID: (%s). Nothing to do.', accessory.displayName, accessory.UUID);
}
} else if (platform.devicesFromApi.has(realDeviceId) && platform.getDeviceTypeByUiid(platform.devicesFromApi.get(realDeviceId).uiid) === 'FAN_LIGHT') {
platform.log('[%s] Device is registered with API. ID: (%s). Nothing to do.', accessory.displayName, accessory.UUID);
} else {
platform.log('Device [%s], ID : [%s] was not present in the response from the API. It will be removed.', accessory.displayName, accessory.UUID);
platform.removeAccessory(accessory);
}
}
// If we have devices in our cache, check that they exist in the web response
if (platform.accessories.size > 0) {
platform.log("Verifying that all cached devices are still registered with the API. Devices that are no longer registered with the API will be removed.");
platform.accessories.forEach(checkIfDeviceIsStillRegistered);
}
platform.log("Evaluating if new devices need to be added...");
// Now we compare the cached devices against the web list
function checkIfDeviceIsAlreadyConfigured(value, deviceId, map) {
if (platform.accessories.has(deviceId)) {
platform.log('Device with ID [%s] is already configured. Ensuring that the configuration is current.', deviceId);
let accessory = platform.accessories.get(deviceId);
let deviceInformationFromWebApi = platform.devicesFromApi.get(deviceId);
let deviceType = platform.getDeviceTypeByUiid(deviceInformationFromWebApi.uiid);
let switchesAmount = platform.getDeviceChannelCount(deviceInformationFromWebApi);
accessory.getService(Service.AccessoryInformation).setCharacteristic(Characteristic.SerialNumber, deviceInformationFromWebApi.extra.extra.mac);
accessory.getService(Service.AccessoryInformation).setCharacteristic(Characteristic.Manufacturer, deviceInformationFromWebApi.productModel);
accessory.getService(Service.AccessoryInformation).setCharacteristic(Characteristic.Model, deviceInformationFromWebApi.extra.extra.model + ' (' + deviceInformationFromWebApi.uiid + ')');
accessory.getService(Service.AccessoryInformation).setCharacteristic(Characteristic.FirmwareRevision, deviceInformationFromWebApi.params.fwVersion);
/* Add a lan client and add it to the context, if the feature is enabled */
if (this.config['experimentalLanClient']) {
this.log.debug('Pre lan client config (checkIfDeviceIsAlreadyConfigured): %o', device);
const lanClient = new LanClient(deviceInformationFromWebApi, this.log);
lanClient.start();
accessory.context.lanClient = lanClient;
}
if (switchesAmount > 1) {
if (platform.groups.has(deviceInformationFromWebApi.deviceid)) {
let group = platform.groups.get(deviceInformationFromWebApi.deviceid);
switch (group.type) {
case 'blind':
platform.log("Blind device has been set: " + deviceInformationFromWebApi.extra.extra.model + ' uiid: ' + deviceInformationFromWebApi.uiid);
accessory.getService(Service.AccessoryInformation).setCharacteristic(Characteristic.Name, deviceInformationFromWebApi.name);
platform.updateBlindStateCharacteristic(deviceId, deviceInformationFromWebApi.params.switches);
// Ensuring switches device config
platform.initSwitchesConfig(accessory);
break;
default:
platform.log('Group type error ! Device [%s], ID : [%s] will not be set', deviceInformationFromWebApi.name, deviceInformationFromWebApi.deviceid);
break;
}
} else if (deviceType === 'FAN_LIGHT') {
platform.updateFanLightCharacteristic(deviceId, deviceInformationFromWebApi.params.switches[0].switch, platform.devicesFromApi.get(deviceId));
platform.updateFanSpeedCharacteristic(deviceId, deviceInformationFromWebApi.params.switches[1].switch, deviceInformationFromWebApi.params.switches[2].switch, deviceInformationFromWebApi.params.switches[3].switch, platform.devicesFromApi.get(deviceId));
} else {
platform.log(switchesAmount + " channels device has been set: " + deviceInformationFromWebApi.extra.extra.model + ' uiid: ' + deviceInformationFromWebApi.uiid);
for (let i = 0; i !== switchesAmount; i++) {
accessory.getService(Service.AccessoryInformation).setCharacteristic(Characteristic.Name, deviceInformationFromWebApi.name + ' CH ' + (i + 1));
platform.updatePowerStateCharacteristic(deviceId + 'CH' + (i + 1), deviceInformationFromWebApi.params.switches[i].switch, platform.devicesFromApi.get(deviceId));
}
}
} else {
platform.log("Single channel device has been set: " + deviceInformationFromWebApi.extra.extra.model + ' uiid: ' + deviceInformationFromWebApi.uiid);
accessory.getService(Service.AccessoryInformation).setCharacteristic(Characteristic.Name, deviceInformationFromWebApi.name);
platform.updatePowerStateCharacteristic(deviceId, deviceInformationFromWebApi.params.switch);
}
if (deviceInformationFromWebApi.extra.extra.model === "PSA-BHA-GL") {
platform.log("Thermostat device has been set: " + deviceInformationFromWebApi.extra.extra.model);
platform.updateCurrentTemperatureCharacteristic(deviceId, deviceInformationFromWebApi.params);
}
} else {
platform.log('Device with ID [%s] is not configured. Add accessory.', deviceId);
let deviceToAdd = platform.devicesFromApi.get(deviceId);
let switchesAmount = platform.getDeviceChannelCount(deviceToAdd);
let services = {};
services.switch = true;
if (deviceToAdd.extra.extra.model === "PSA-BHA-GL") {
services.thermostat = true;
services.temperature = true;
services.humidity = true;
} else {
services.switch = true;
}
if (switchesAmount > 1) {
if (platform.groups.has(deviceToAdd.deviceid)) {
let group = platform.groups.get(deviceToAdd.deviceid);
switch (group.type) {
case 'blind':
platform.log('Device [%s], ID : [%s] will be added as %s', deviceToAdd.name, deviceToAdd.deviceid, group.type);
services.blind = true;
services.switch = false;
services.group = group;
platform.addAccessory(deviceToAdd, null, services);
break;
default:
platform.log('Group type error ! Device [%s], ID : [%s] will not be added', deviceToAdd.name, deviceToAdd.deviceid);
break;
}
} else if (deviceToAdd.extra.extra.model === "PSF-BFB-GL") {
services.fan = true;
services.switch = false;
platform.log('Device [%s], ID : [%s] will be added as a fan', deviceToAdd.name, deviceToAdd.deviceid);
platform.addAccessory(deviceToAdd, deviceToAdd.deviceid, services);
} else {
for (let i = 0; i !== switchesAmount; i++) {
platform.log('Device [%s], ID : [%s] will be added', deviceToAdd.name, deviceToAdd.deviceid + 'CH' + (i + 1));
platform.addAccessory(deviceToAdd, deviceToAdd.deviceid + 'CH' + (i + 1), services);
}
}
} else {
platform.log('Device [%s], ID : [%s] will be added', deviceToAdd.name, deviceToAdd.deviceid);
platform.addAccessory(deviceToAdd, null, services);
}
}
}
// Go through the web response to make sure that all the devices that are in the response do exist in the accessories map
if (platform.devicesFromApi.size > 0) {
platform.devicesFromApi.forEach(checkIfDeviceIsAlreadyConfigured);
}
platform.log("API key retrieved from web service is [%s]", platform.apiKey);
// We have our devices, now open a connection to the WebSocket API
let url = 'wss://' + platform.config['webSocketApi'] + ':8080/api/ws';
platform.log("Connecting to the WebSocket API at [%s]", url);
platform.wsc = new WebSocketClient();
platform.wsc.open(url);
platform.wsc.onmessage = function (message) {
// Heartbeat response can be safely ignored
if (message == 'pong') {
return;
}
platform.log("WebSocket messge received: ", message);
let json;
try {
json = JSON.parse(message);
} catch (e) {
return;
}
if (json.hasOwnProperty("action")) {
if (json.action === 'update') {
platform.log("Update message received for device [%s]", json.deviceid);
platform.log(json);
if (json.hasOwnProperty("params") && json.params.hasOwnProperty("switch")) {
platform.updatePowerStateCharacteristic(json.deviceid, json.params.switch);
} else if (json.hasOwnProperty("params") && json.params.hasOwnProperty("switches") && Array.isArray(json.params.switches)) {
if (platform.groups.has(json.deviceid)) {
let group = platform.groups.get(json.deviceid);
platform.log('---------------' + group);
switch (group.type) {
case 'blind':
if (group.handle_api_changes) {
platform.updateBlindStateCharacteristic(json.deviceid, json.params.switches);
} else {
platform.log('Setup to not respond to API. Device ID : [%s] will not be updated.', json.deviceid);
}
break;
default:
platform.log('Group type error ! Device ID : [%s] will not be updated.', json.deviceid);
break;
}
} else if (platform.devicesFromApi.has(json.deviceid) && platform.getDeviceTypeByUiid(platform.devicesFromApi.get(json.deviceid).uiid) === 'FAN_LIGHT') {
platform.updateFanLightCharacteristic(json.deviceid, json.params.switches[0].switch, platform.devicesFromApi.get(json.deviceid));
platform.devicesFromApi.get(json.deviceid).params.switches = json.params.switches;
platform.updateFanSpeedCharacteristic(json.deviceid, json.params.switches[1].switch, json.params.switches[2].switch, json.params.switches[3].switch, platform.devicesFromApi.get(json.deviceid));
} else {
json.params.switches.forEach(function (entry) {
if (entry.hasOwnProperty('outlet') && entry.hasOwnProperty('switch')) {
platform.updatePowerStateCharacteristic(json.deviceid + 'CH' + (entry.outlet + 1), entry.switch, platform.devicesFromApi.get(json.deviceid));
}
});
}
}
if (json.hasOwnProperty("params") && (json.params.hasOwnProperty("currentTemperature") || json.params.hasOwnProperty("currentHumidity"))) {
platform.updateCurrentTemperatureCharacteristic(json.deviceid, json.params);
}
}
} else if (json.hasOwnProperty('config') && json.config.hb && json.config.hbInterval) {
if (!platform.hbInterval) {
platform.hbInterval = setInterval(function () {
platform.wsc.send('ping');
}, json.config.hbInterval * 1000);
}
}
};
platform.wsc.onopen = function (e) {
platform.isSocketOpen = true;
// We need to authenticate upon opening the connection
let time_stamp = new Date() / 1000;
let ts = Math.floor(time_stamp);
// Here's the eWeLink payload as discovered via Charles
let payload = {};
payload.action = "userOnline";
payload.userAgent = 'app';
payload.version = 6;
payload.nonce = '' + nonce();
payload.apkVesrion = "1.8";
payload.os = 'ios';
payload.at = config.authenticationToken;
payload.apikey = platform.apiKey;
payload.ts = '' + ts;
payload.model = 'iPhone10,6';
payload.romVersion = '11.1.2';
payload.sequence = platform.getSequence();
let string = JSON.stringify(payload);
platform.log('Sending login request [%s]', string);
platform.wsc.send(string);
};
platform.wsc.onclose = function (e) {
platform.log("WebSocket was closed. Reason [%s]", e);
platform.isSocketOpen = false;
if (platform.hbInterval) {
clearInterval(platform.hbInterval);
platform.hbInterval = null;
}
};
}); // End WebSocket
}; // End afterLogin
// Resolve region if countryCode is provided
if (this.config['countryCode']) {
this.getRegion(this.config['countryCode'], function () {
this.login(afterLogin.bind(this));
}.bind(this));
} else {
this.login(afterLogin.bind(this));
}
}.bind(this));
}
}
// Function invoked when homebridge tries to restore cached accessory.
// We update the existing devices as part of didFinishLaunching(), as to avoid an additional call to the the HTTPS API.
eWeLink.prototype.configureAccessory = function (accessory) {
let platform = this;
// To avoid crash if platform config change
if (!platform.log) {
return;
}
platform.log(accessory.displayName, "Configure Accessory");
let service;
if (accessory.getService(Service.WindowCovering)) {
service = accessory.getService(Service.WindowCovering);
service.getCharacteristic(Characteristic.CurrentPosition)
.on('get', function (callback) {
platform.getCurrentPosition(accessory, callback);
});
service.getCharacteristic(Characteristic.PositionState)
.on('get', function (callback) {
platform.getPositionState(accessory, callback);
});
service.getCharacteristic(Characteristic.TargetPosition)
.on('set', function (value, callback) {
platform.setTargetPosition(accessory, value, callback);
})
.on('get', function (callback) {
platform.getTargetPosition(accessory, callback);
});
// Restore previous state
let lastPosition = accessory.context.lastPosition;
platform.log("[%s] Previous last Position stored: %s", accessory.displayName, lastPosition);
if ((lastPosition === undefined) || (lastPosition < 0)) {
lastPosition = 0;
platform.log("[%s] No previous saved state. lastPosition set to default: %s", accessory.displayName, lastPosition);
} else {
platform.log("[%s] Previous saved state found. lastPosition set to: %s", accessory.displayName, lastPosition);
}
accessory.context.lastPosition = lastPosition;
accessory.context.currentTargetPosition = lastPosition;
accessory.context.currentPositionState = 2;
// Updating config
let group = platform.groups.get(accessory.context.deviceId);
if (group) {
accessory.context.switchUp = group.relay_up - 1;
accessory.context.switchDown = group.relay_down - 1;
accessory.context.durationUp = group.time_up;
accessory.context.durationDown = group.time_down;
accessory.context.durationBMU = group.time_botton_margin_up || 0;
accessory.context.durationBMD = group.time_botton_margin_down || 0;
accessory.context.fullOverdrive = group.full_overdrive || 0;
accessory.context.percentDurationDown = (accessory.context.durationDown / 100) * 1000;
accessory.context.percentDurationUp = (accessory.context.durationUp / 100) * 1000;
accessory.context.handleApiChanges = group.handle_api_changes || true;
}
}
if (accessory.getService(Service.Switch)) {
accessory.getService(Service.Switch)
.getCharacteristic(Characteristic.On)
.on('set', function (value, callback) {
let localDevice = undefined;
if (accessory.context.lanClient) {
/* Try to get the local device state if a lan client exists */
localDevice = accessory.context.lanClient.getLocalDevice();
}
if(localDevice && localDevice.data.type === 'plug') {
/* We can do a local device call for this */
accessory.context.lanClient.setSwitchStatus(
accessory, value, callback);
} else {
/* Do a web call */
platform.setPowerState(accessory, value, callback);
}
})
.on('get', function (callback) {
let localDevice = undefined;
if (accessory.context.lanClient &&
accessory.context.lanClient.getLocalDevice) {
/* Only get the local device state if there is a lan client and it
* has the expected function.
* This latter check seems to be required when a device is partially
* restored and homebridge tries to get the state before it is fully
* set up.
*/
localDevice = accessory.context.lanClient.getLocalDevice();
}
let status = undefined;
if (localDevice) {
if (localDevice.data.type === 'plug') {
status = accessory.context.lanClient.getSwitchStatus();
} else if (localDevice.data.type === 'strip') {
status = accessory.context.lanClient.getStripOutletStatus(
accessory.context.channel);
}
}
if (status !== undefined) {
/* Got a response from the lan client, call the callback */
callback(null, status);
} else {
/* Try the API */
platform.getPowerState(accessory, callback);
}
});
}
if (accessory.getService(Service.Thermostat)) {
service = accessory.getService(Service.Thermostat);
service.getCharacteristic(Characteristic.CurrentTemperature)
.on('set', function (value, callback) {
platform.setTemperatureState(accessory, value, callback);
})
.on('get', function (callback) {
platform.getCurrentTemperature(accessory, callback);
});
service.getCharacteristic(Characteristic.CurrentRelativeHumidity)
.on('set', function (value, callback) {
platform.setHumidityState(accessory, value, callback);
})
.on('get', function (callback) {
platform.getCurrentHumidity(accessory, callback);
});
}
if (accessory.getService(Service.TemperatureSensor)) {
accessory.getService(Service.TemperatureSensor)
.getCharacteristic(Characteristic.CurrentTemperature)
.on('set', function (value, callback) {
platform.setTemperatureState(accessory, value, callback);
})
.on('get', function (callback) {
platform.getCurrentTemperature(accessory, callback);
});
}
if (accessory.getService(Service.HumiditySensor)) {
accessory.getService(Service.HumiditySensor)
.getCharacteristic(Characteristic.CurrentRelativeHumidity)
.on('set', function (value, callback) {
platform.setHumidityState(accessory, value, callback);
})
.on('get', function (callback) {
platform.getCurrentHumidity(accessory, callback);
});
}
if (accessory.getService(Service.Fanv2)) {
accessory.getService(Service.Fanv2).getCharacteristic(Characteristic.On)
.on("get", function (callback) {
platform.getFanState(accessory, callback);
})
.on("set", function (value, callback) {
platform.setFanState(accessory, value, callback);
});
// This is actually the fan speed instead of rotation speed but homekit fan does not support this
accessory.getService(Service.Fanv2).getCharacteristic(Characteristic.RotationSpeed)
.setProps({
minStep: 3
})
.on("get", function (callback) {
platform.getFanSpeed(accessory, callback);
})
.on("set", function (value, callback) {
platform.setFanSpeed(accessory, value, callback);
});
}
if (accessory.getService(Service.Lightbulb)) {
accessory.getService(Service.Lightbulb).getCharacteristic(Characteristic.On)
.on("get", function (callback) {
platform.getFanLightState(accessory, callback);
})
.on("set", function (value, callback) {
platform.setFanLightState(accessory, value, callback);
});
}
this.accessories.set(accessory.context.deviceId, accessory);
};
// Sample function to show how developer can add accessory dynamically from outside event
eWeLink.prototype.addAccessory = function (device, deviceId = null, services = {"switch": true}) {
// Here we need to check if it is currently there
if (this.accessories.get(deviceId ? deviceId : device.deviceid)) {
this.log("Not adding [%s] as it already exists in the cache", deviceId ? deviceId : device.deviceid);
return;
}
let platform = this;
let channel = 0;
if (device.type != 10) {
this.log("A device with an unknown type was returned. It will be skipped.", device.type);
return;
}
if (deviceId) {
let id = deviceId.split("CH");
channel = id[1];
}
let deviceName = device.name + (channel ? ' CH ' + channel : '');
try {
if (channel && device.tags && device.tags.ck_channel_name && device.tags.ck_channel_name[channel-1]) {
deviceName = device.tags.ck_channel_name[channel-1];
}
} catch (e) {
this.log("Problem device name : [%s]", e);
}
try {
const status = channel && device.params.switches && device.params.switches[channel - 1] ? device.params.switches[channel - 1].switch : device.params.switch || "off";
this.log("Found Accessory with Name : [%s], Manufacturer : [%s], Status : [%s], Is Online : [%s], API Key: [%s] ", deviceName, device.productModel, status, device.online, device.apikey);
} catch (e) {
this.log("Problem accessory Accessory with Name : [%s], Manufacturer : [%s], Error : [%s], Is Online : [%s], API Key: [%s] ", deviceName, device.productModel, e, device.online, device.apikey);
}
let switchesCount = this.getDeviceChannelCount(device);
if (channel > switchesCount) {
this.log("Can't add [%s], because device [%s] has only [%s] switches.", deviceName, device.productModel, switchesCount);
return;
}
const accessory = new Accessory(deviceName, UUIDGen.generate((deviceId ? deviceId : device.deviceid).toString()));
accessory.context.deviceId = deviceId ? deviceId : device.deviceid;
accessory.context.apiKey = device.apikey;
accessory.context.switches = 1;
accessory.context.channel = channel;
accessory.reachable = device.online === 'true';
/* Add a lan client and add it to the context, if the feature is enabled */
if (this.config['experimentalLanClient']) {
this.log.debug('Pre lan client config (addAccessory): %o', device)
const lanClient = new LanClient(device, this.log);
lanClient.start();
accessory.context.lanClient = lanClient;
}
if (services.fan) {
var fan = accessory.addService(Service.Fanv2, device.name);
var light = accessory.addService(Service.Lightbulb, device.name + ' Light');
light.getCharacteristic(Characteristic.On)
.on("get", function (callback) {
platform.getFanLightState(accessory, callback);
})
.on('set', function (value, callback) {
platform.setFanLightState(accessory, value, callback);
});
fan.getCharacteristic(Characteristic.On)
.on("get", function (callback) {
platform.getFanState(accessory, callback);
})
.on("set", function (value, callback) {
platform.setFanState(accessory, value, callback);
});
// This is actually the fan speed instead of rotation speed but homekit fan does not support this
fan.getCharacteristic(Characteristic.RotationSpeed)
.setProps({
minStep: 3
})
.on("get", function (callback) {
platform.getFanSpeed(accessory, callback);
})
.on("set", function (value, callback) {
platform.setFanSpeed(accessory, value, callback);
});
}
if (services.blind) {
// platform.log("Services:", services);
accessory.context.switchUp = services.group.relay_up - 1;
accessory.context.switchDown = services.group.relay_down - 1;
accessory.context.durationUp = services.group.time_up;
accessory.context.durationDown = services.group.time_down;
accessory.context.durationBMU = services.group.time_botton_margin_up || 0;
accessory.context.durationBMD = services.group.time_botton_margin_down || 0;
accessory.context.fullOverdrive = services.group.full_overdrive || 0;
accessory.context.percentDurationDown = (accessory.context.durationDown / 100) * 1000;
accessory.context.percentDurationUp = (accessory.context.durationUp / 100) * 1000;
accessory.context.handleApiChanges = services.group.handle_api_changes || true;
accessory.context.lastPosition = 100; // Last know position, (0-100%)
accessory.context.currentPositionState = 2; // 2 = Stoped , 0=Moving Up , 1 Moving Down.
accessory.context.currentTargetPosition = 100; // Target Position, (0-100%)
// Ensuring switches device config
platform.initSwitchesConfig(accessory);
let service = accessory.addService(Service.WindowCovering, deviceName);
service.getCharacteristic(Characteristic.CurrentPosition)
.on('get', function (callback) {
platform.getCurrentPosition(accessory, callback);
});
service.getCharacteristic(Characteristic.PositionState)
.on('get', function (callback) {
platform.getPositionState(accessory, callback);
});
service.getCharacteristic(Characteristic.TargetPosition)
.on('get', function (callback) {
platform.getTargetPosition(accessory, callback);
})
.on('set', function (value, callback) {
platform.setTargetPosition(accessory, value, callback);
});
}
if (services.switch) {
accessory.addService(Service.Switch, deviceName)
.getCharacteristic(Characteristic.On)
.on('set', function (value, callback) {
let localDevice = undefined;
if (accessory.context.lanClient) {
/* Try to get the local device state if a lan client exists */
localDevice = accessory.context.lanClient.getLocalDevice();
}
if(localDevice && localDevice.data.type === 'plug') {
/* A local device state exists. We can do a local device call for this */
accessory.context.lanClient.setSwitchStatus(
accessory, value, callback);
} else {
/* Do a web call */
platform.setPowerState(accessory, value, callback);
}
})
.on('get', function (callback) {
let localDevice = undefined;
if (accessory.context.lanClient &&
accessory.context.lanClient.getLocalDevice) {
/* Only get the local device state if there is a lan client and it
* has the expected function.
* This latter check seems to be required when a device is partially
* restored and homebridge tries to get the state before it is fully
* set up.
*/
localDevice = accessory.context.lanClient.getLocalDevice();
}
let status = undefined;
if (localDevice) {
if (localDevice.data.type === 'plug') {
status = accessory.context.lanClient.getSwitchStatus();
} else if (localDevice.data.type === 'strip') {
status = accessory.context.lanClient.getStripOutletStatus(
accessory.context.channel);
}
}
if (status !== undefined) {
/* Got a response from the lan client, call the callback */
callback(null, status);
} else {
/* Try the API */
platform.getPowerState(accessory, callback);
}
});
}
if (services.thermostat) {
let service = accessory.addService(Service.Thermostat, deviceName);
service.getCharacteristic(Characteristic.CurrentTemperature)
.on('set', function (value, callback) {
platform.setTemperatureState(accessory, value, callback);
})
.on('get', function (callback) {
platform.getCurrentTemperature(accessory, callback);
});
service.getCharacteristic(Characteristic.CurrentRelativeHumidity)
.on('set', function (value, callback) {
platform.setHumidityState(accessory, value, callback);
})
.on('get', function (callback) {
platform.getCurrentHumidity(accessory, callback);
});
}
if (services.temperature) {
accessory.addService(Service.TemperatureSensor, deviceName)
.getCharacteristic(Characteristic.CurrentTemperature)
.on('set', function (value, callback) {
platform.setTemperatureState(accessory, value, callback);
})
.on('get', function (callback) {
platform.getCurrentTemperature(accessory, callback);
});
}
if (services.humidity) {
accessory.addService(Service.HumiditySensor, deviceName)
.getCharacteristic(Characteristic.CurrentRelativeHumidity)
.on('set', function (value, callback) {
platform.setHumidityState(accessory, value, callback);
})
.on('get', function (callback) {
platform.getCurrentHumidity(accessory, callback);
});
}
accessory.on('identify', function (paired, callback) {
platform.log(accessory.displayName, "Identify not supported");
try {
callback();
} catch (e) { }
});
accessory.getService(Service.AccessoryInformation).setCharacteristic(Characteristic.SerialNumber, device.extra.extra.mac);
accessory.getService(Service.AccessoryInformation).setCharacteristic(Characteristic.Manufacturer, device.productModel);
accessory.getService(Service.AccessoryInformation).setCharacteristic(Characteristic.Model, device.extra.extra.model);
accessory.getService(Service.AccessoryInformation).setCharacteristic(Characteristic.Identify, false);
// Exception when some device is not ready to register
try {
accessory.getService(Service.AccessoryInformation).setCharacteristic(Characteristic.FirmwareRevision, device.params.fwVersion);
} catch (e) {
this.log("Error : [%s]", e);
}
let switchesAmount = platform.getDeviceChannelCount(device);
if (switchesAmount > 1) {
accessory.context.switches = switchesAmount;
}
this.accessories.set(deviceId ? deviceId : device.deviceid, accessory);
this.api.registerPlatformAccessories("homebridge-eWeLink",
"eWeLink", [accessory]);
};
eWeLink.prototype.getSequence = function () {
let time_stamp = new Date() / 1000;
this.sequence = Math.floor(time_stamp * 1000);
return this.sequence;
};
eWeLink.prototype.updatePowerStateCharacteristic = function (deviceId, state, device = null, channel = null) {
// Used when we receive an update from an external source
let platform = this;
let isOn = false;
let accessory = platform.accessories.get(deviceId);
if (typeof accessory === 'undefined' && device) {
platform.log("Adding accessory for deviceId [%s].", deviceId);
platform.addAccessory(device, deviceId);
accessory = platform.accessories.get(deviceId);
}
if (!accessory) {
platform.log("Error updating non-exist accessory with deviceId [%s].", deviceId);
return;
}
if (state === 'on') {
isOn = true;
}
platform.log("Updating recorded Characteristic.On for [%s] to [%s]. No request will be sent to the device.", accessory.displayName, isOn);
let currentState = accessory.getService(Service.Switch).getCharacteristic(Characteristic.On).value;
if (currentState !== isOn) {
platform.log("Updating recorded Characteristic.On for [%s] from [%s] to [%s]. No request will be sent to the device.", accessory.displayName, currentState, isOn);
accessory.getService(Service.Switch)
.setCharacteristic(Characteristic.On, isOn);
}
};
eWeLink.prototype.updateCurrentTemperatureCharacteristic = function (deviceId, state, device = null, channel = null) {
// Used when we receive an update from an external source
let platform = this;
let accessory = platform.accessories.get(deviceId);
//platform.log("deviceID:", deviceId);
if (typeof accessory === 'undefined' && device) {
platform.addAccessory(device, deviceId);
accessory = platform.accessories.get(deviceId);
}
if (!accessory) {
platform.log("Error updating non-exist accessory with deviceId [%s].", deviceId);
return;
}
// platform.log(JSON.stringify(device,null,2));
let currentTemperature = state.currentTemperature;
let currentHumidity = state.currentHumidity;
platform.log("Updating recorded Characteristic.CurrentTemperature for [%s] to [%s]. No request will be sent to the device.", accessory.displayName, currentTemperature);
platform.log("Updating recorded Characteristic.CurrentRelativeHuniditgy for [%s] to [%s]. No request will be sent to the device.", accessory.displayName, currentHumidity);
if (accessory.getService(Service.Thermostat)) {
accessory.getService(Service.Thermostat)
.setCharacteristic(Characteristic.CurrentTemperature, currentTemperature);
accessory.getService(Service.Thermostat)
.setCharacteristic(Characteristic.CurrentRelativeHumidity, currentHumidity);
}
if (accessory.getService(Service.TemperatureSensor)) {
accessory.getService(Service.TemperatureSensor)
.setCharacteristic(Characteristic.CurrentTemperature, currentTemperature);
}
if (accessory.getService(Service.HumiditySensor)) {
accessory.getService(Service.HumiditySensor)
.setCharacteristic(Characteristic.CurrentRelativeHumidity, currentHumidity);
}
};
eWeLink.prototype.updateBlindStateCharacteristic = function (deviceId, switches, device = null) {
// Used when we receive an update from an external source
let platform = this;
let accessory = platform.accessories.get(deviceId);
if (typeof accessory === 'undefined' && device) {
platform.log("Adding accessory for deviceId [%s].", deviceId);
platform.addAccessory(device, deviceId);
accessory = platform.accessories.get(deviceId);
}
if (!accessory) {
platform.log("Error updating non-exist accessory with deviceId [%s].", deviceId);
return;
}
let state = platform.getBlindState(switches, accessory);
// platform.log("blindStae_debug:", state)
// [0,0] = 0 => 2 Stopped
// [0,1] = 1 => 1 Moving down
// [1,0] = 2 => 0 Moving up
// [1,1] = 3 => Error
let stateString = ["Moving up", "Moving down", "Stopped", "Error!"];
let service = accessory.getService(Service.WindowCovering);
let actualPosition;