This repository has been archived by the owner on Oct 18, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
HomeKitHistory.js
2278 lines (2040 loc) · 120 KB
/
HomeKitHistory.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
// HomeKit history service
// Simple history service for HomeKit developed accessories with HAP-NodeJS
//
// todo (EveHome integration)
// -- get history to show for motion when attached to a smoke sensor
// -- get history to show for smoke when attached to a smoke sensor
// -- thermo schedules/additonal characteris
// -- Eve Degree/Weather2 history
//
// done
// -- initial support for importing our history into EveHome
// -- developed simple history service for HomeKit HAP-NodeJS accessories
// -- import history for sprinkler/irrigation systems to EveHome (Aqua)
// -- fixed door history bug with inverted status
// -- notify Eve when new history entries added
// -- get humidity recordings for EveHome thermo
// -- Eve Room2 history returns
// -- internally check if specified minimun time between entries and if so, ignore logging it
// -- small correction to number formatting when retreving history for EveHome
//
// Version 13/10/2021
// Mark Hulskamp
const MAX_HISTORY_SIZE = 16384; // 16k entries
var Service = require("../").Service;
var Characteristic = require("../").Characteristic;
var util = require("util");
var fs = require("fs");
var storage = require("node-persist");
class HomeKitHistory {
constructor(HomeKitAccessory, optionalParams) {
if (typeof (optionalParams) === "object") {
this.maxEntries = optionalParams.maxEntries || MAX_HISTORY_SIZE; // used for rolling history. if 0, means no rollover
this.location = optionalParams.location || "";
}
else {
this.maxEntries = MAX_HISTORY_SIZE; // used for rolling history. if 0, means no rollover
this.location = "";
}
// Setup HomeKitHistory storage using HAP-NodeJS persist location
// can be overridden by passing in location optional parameter
this.storageKey = util.format("History.%s.json", HomeKitAccessory.username.replace(/:/g, "").toUpperCase());
if (this.location != "" && typeof this.location == "string") storage.init({dir: this.location});
this.historyData = storage.getItem(this.storageKey);
if (typeof this.historyData != "object") {
// Getting storage key didnt return an object, we'll assume no history present, so start new history for this accessory
this.resetHistory(); // Start with blank history
}
this.restart = Math.floor(new Date() / 1000); // time we restarted
// perform rollover if needed when starting service
if (this.maxEntries != 0 && this.historyData.next >= this.maxEntries) {
this.rolloverHistory();
}
return this; // Return object to our service
}
}
HomeKitHistory.prototype.addHistory = function(service, entry, timegap) {
// we'll use the service or characteristic UUID to determine the history entry time and data we'll add
// reformat the entry object to order the fields consistantly in the output
// Add new history types in the switch statement
var historyEntry = {};
if (this.restart != null && typeof entry.restart == "undefined") {
// Object recently created, so log the time restarted our history service
entry.restart = this.restart;
this.restart = null;
}
if (typeof entry.time == "undefined") {
// No logging time was passed in, so set
entry.time = Math.floor(new Date() / 1000);
}
if (typeof service.subtype == "undefined") {
service.subtype = 0;
}
if (typeof timegap == "undefined") {
timegap = 0; // Zero minimum time gap between entries
}
switch (service.UUID) {
case Service.GarageDoorOpener.UUID : {
// Garage door history
// entry.time => unix time in seconds
// entry.status => 0 = closed, 1 = open
historyEntry.status = entry.status;
if (typeof entry.restart != "undefined") historyEntry.restart = entry.restart;
this.__addEntry(service.UUID, service.subtype, entry.time, timegap, historyEntry);
break;
}
case Service.MotionSensor.UUID : {
// Motion sensor history
// entry.time => unix time in seconds
// entry.status => 0 = motion cleared, 1 = motion detected
historyEntry.status = entry.status;
if (typeof entry.restart != "undefined") historyEntry.restart = entry.restart;
this.__addEntry(service.UUID, service.subtype, entry.time, timegap, historyEntry);
break;
}
case Service.Window.UUID :
case Service.WindowCovering.UUID : {
// Window and Window Covering history
// entry.time => unix time in seconds
// entry.status => 0 = closed, 1 = open
// entry.position => position in % 0% = closed 100% fully open
historyEntry.status = entry.status;
historyEntry.position = entry.position;
if (typeof entry.restart != "undefined") historyEntry.restart = entry.restart;
this.__addEntry(service.UUID, service.subtype, entry.time, timegap, historyEntry);
break;
}
case Service.HeaterCooler.UUID :
case Service.Thermostat.UUID : {
// Thermostat and Heater/Cooler history
// entry.time => unix time in seconds
// entry.status => 0 = off, 1 = fan, 2 = heating, 3 = cooling
// entry.temperature => current temperature in degress C
// entry.target => {low, high} = cooling limit, heating limit
// entry.humidity => current humidity
historyEntry.status = entry.status;
historyEntry.temperature = entry.temperature;
historyEntry.target = entry.target;
historyEntry.humidity = entry.humidity;
if (typeof entry.restart != "undefined") historyEntry.restart = entry.restart;
this.__addEntry(service.UUID, service.subtype, entry.time, timegap, historyEntry);
break;
}
case Service.EveAirPressureSensor.UUID :
case Service.AirQualitySensor.UUID :
case Service.TemperatureSensor.UUID : {
// Temperature sensor history
// entry.time => unix time in seconds
// entry.temperature => current temperature in degress C
// entry.humidity => current humidity
// optional (entry.ppm)
// optional (entry.voc => current VOC measurement in ppb)\
// optional (entry.pressure -> in hpa)
historyEntry.temperature = entry.temperature;
if (typeof entry.humidity == "undefined") {
// fill out humidity if missing
entry.humidity = 0;
}
if (typeof entry.ppm == "undefined") {
// fill out ppm if missing
entry.ppm = 0;
}
if (typeof entry.voc == "undefined") {
// fill out voc if missing
entry.voc = 0;
}
if (typeof entry.pressure == "undefined") {
// fill out pressure if missing
entry.pressure = 0;
}
historyEntry.temperature = entry.temperature;
historyEntry.humidity = entry.humidity;
historyEntry.ppm = entry.ppm;
historyEntry.voc = entry.voc;
historyEntry.pressure = entry.pressure;
if (typeof entry.restart != "undefined") historyEntry.restart = entry.restart;
this.__addEntry(service.UUID, service.subtype, entry.time, timegap, historyEntry);
break;
}
case Service.Valve.UUID : {
// Water valve history
// entry.time => unix time in seconds
// entry.status => 0 = valve closed, 1 = valve opened
// entry.water => amount of water in L's
// entry.duration => time for water amount
historyEntry.status = entry.status;
historyEntry.water = entry.water;
historyEntry.duration = entry.duration;
if (typeof entry.restart != "undefined") historyEntry.restart = entry.restart;
this.__addEntry(service.UUID, service.subtype, entry.time, timegap, historyEntry);
break;
}
case Characteristic.WaterLevel.UUID : {
// Water level history
// entry.time => unix time in seconds
// entry.level => water level as percentage
historyEntry.level = entry.level;
if (typeof entry.restart != "undefined") historyEntry.restart = entry.restart;
this.__addEntry(service.UUID, 0, entry.time, timegap, historyEntry); // Characteristics dont have sub type, so we'll use 0 for it
break;
}
case Service.Outlet.UUID : {
// Power outlet
// entry.time => unix time in seconds
// entry.status => 0 = off, 1 = on
// entry.volts => current voltage in Vs
// entry.watts => current consumption in W's
historyEntry.status = entry.status;
historyEntry.volts = entry.volts;
historyEntry.watts = entry.watts;
if (typeof entry.restart != "undefined") historyEntry.restart = entry.restart;
this.__addEntry(service.UUID, service.subtype, entry.time, timegap, historyEntry);
break;
}
case Service.Doorbell.UUID : {
// Doorbell press history
// entry.time => unix time in seconds
// entry.status => 0 = not pressed, 1 = doorbell pressed
historyEntry.status = entry.status;
if (typeof entry.restart != "undefined") historyEntry.restart = entry.restart;
this.__addEntry(service.UUID, service.subtype, entry.time, timegap, historyEntry);
break;
}
case Service.SmokeSensor.UUID : {
// Smoke sensor history
// entry.time => unix time in seconds
// entry.status => 0 = smoke cleared, 1 = smoke detected
historyEntry.status = entry.status;
if (typeof historyEntry.restart != "undefined") historyEntry.restart = entry.restart;
this.__addEntry(service.UUID, service.subtype, entry.time, timegap, historyEntry);
break;
}
}
}
HomeKitHistory.prototype.resetHistory = function() {
// Reset history to nothing
this.historyData = {};
this.historyData.reset = Math.floor(new Date() / 1000); // time history was reset
this.historyData.rollover = 0; // no last rollover time
this.historyData.next = 0; // next entry for history is at start
this.historyData.types = []; // no service types in history
this.historyData.data = []; // no history data
storage.setItem(this.storageKey, this.historyData);
}
HomeKitHistory.prototype.rolloverHistory = function() {
// Roll history over and start from zero.
// We'll include an entry as to when the rollover took place
// remove all history data after the rollover entry
this.historyData.data.splice(this.maxEntries, this.historyData.data.length);
this.historyData.rollover = Math.floor(new Date() / 1000);
this.historyData.next = 0;
this.__updateHistoryTypes();
storage.setItem(this.storageKey, this.historyData);
}
HomeKitHistory.prototype.__addEntry = function(type, sub, time, timegap, entry) {
var historyEntry = {};
var recordEntry = true; // always record entry unless we dont need to
historyEntry.time = time;
historyEntry.type = type;
historyEntry.sub = sub;
Object.entries(entry).forEach(([key, value]) => {
if (key != "time" || key != "type" || key != "sub") {
// Filer out events we want to control
historyEntry[key] = value;
}
});
// If we have a minimum time gap specified, find the last time entry for this type and if less than min gap, ignore
if (timegap != 0) {
var typeIndex = this.historyData.types.findIndex(type => (type.type == historyEntry.type && type.sub == historyEntry.sub));
if (typeIndex >= 0 && (time - this.historyData.data[this.historyData.types[typeIndex].lastEntry].time < timegap) && typeof historyEntry.restart == "undefined") {
// time between last recorded entry and this new entry is less than minimum gap specified and its not a "restart" entry, so don't log it
recordEntry = false;
}
}
if (recordEntry == true) {
// Work out where this goes in the history data array
if (this.maxEntries != 0 && this.historyData.next >= this.maxEntries) {
// roll over history data as we've reached the defined max entry size
this.rolloverHistory();
}
this.historyData.data[this.historyData.next] = historyEntry;
this.historyData.next++;
// Update types we have in history. This will just be the main type and its latest location in history
var typeIndex = this.historyData.types.findIndex(type => (type.type == historyEntry.type && type.sub == historyEntry.sub));
if (typeIndex == -1) {
this.historyData.types.push({type: historyEntry.type, sub: historyEntry.sub, lastEntry: (this.historyData.next - 1)});
} else {
this.historyData.types[typeIndex].lastEntry = (this.historyData.next - 1);
}
// Validate types last entries. Helps with rolled over data etc. If we cannot find the type anymore, remove from known types
this.historyData.types.forEach((typeEntry, index) => {
if (this.historyData.data[typeEntry.lastEntry].type !== typeEntry.type) {
// not found, so remove from known types
this.historyData.types.splice(index, 1);
}
});
storage.setItem(this.storageKey, this.historyData); // Save to persistent storage
}
}
HomeKitHistory.prototype.getHistory = function(service, subtype, specifickey) {
// returns a JSON object of all history for this service and subtype
// handles if we've rolled over history also
var tempHistory = [];
var findUUID = null;
var findSub = null;
if (typeof subtype != "undefined" && subtype != null) {
findSub = subtype;
}
if (typeof service != "object") {
// passed in UUID byself, rather than service object
findUUID = service;
}
if (typeof service == "object" && service.hasOwnProperty("UUID") == true) {
findUUID = service.UUID;
}
if (typeof service.subtype == "undefined" && typeof subtype == "undefined") {
findSub = 0;
}
tempHistory = tempHistory.concat(this.historyData.data.slice(this.historyData.next, this.historyData.data.length), this.historyData.data.slice(0, this.historyData.next));
tempHistory = tempHistory.filter(historyEntry => {
if (specifickey && typeof specifickey == "object" && Object.keys(specifickey).length == 1) {
// limit entry to a specifc key type value if specified
if ((findSub == null && historyEntry.type == findUUID && historyEntry[Object.keys(specifickey)] == Object.values(specifickey)) || (findSub != null && historyEntry.type == findUUID && historyEntry.sub == findSub && historyEntry[Object.keys(specifickey)] == Object.values(specifickey))) {
return historyEntry;
}
} else if ((findSub == null && historyEntry.type == findUUID) || (findSub != null && historyEntry.type == findUUID && historyEntry.sub == findSub)) {
return historyEntry;
}
});
return tempHistory;
}
HomeKitHistory.prototype.generateCSV = function(service, csvfile) {
// Generates a CSV file for use in applications such as Numbers/Excel for graphing
// we get all the data for the service, ignoring the specific subtypes
var tempHistory = this.getHistory(service, null); // all history
if (tempHistory.length != 0) {
var writer = fs.createWriteStream(csvfile, {flags: "w", autoClose: "true"});
if (writer != null) {
// write header, we'll use the first record keys for the header keys
var header = "time,subtype";
Object.keys(tempHistory[0]).forEach(key => {
if (key != "time" && key != "type" && key != "sub" && key != "restart") {
header = header + "," + key;
}
});
writer.write(header + "\n");
// write data
// Date/Time converted into local timezone
tempHistory.forEach(historyEntry => {
var csvline = new Date(historyEntry.time * 1000).toLocaleString().replace(",", "") + "," + historyEntry.sub;
Object.entries(historyEntry).forEach(([key, value]) => {
if (key != "time" && key != "type" && key != "sub" && key != "restart") {
csvline = csvline + "," + value;
}
});
writer.write(csvline + "\n");
});
writer.end();
}
}
}
HomeKitHistory.prototype.lastHistory = function(service, subtype) {
// returns the last history event for this service type and subtype
var findUUID = null;
var findSub = null;
if (typeof subtype != "undefined") {
findSub = subtype;
}
if (typeof service != "object") {
// passed in UUID byself, rather than service object
findUUID = service;
}
if (typeof service == "object" && service.hasOwnProperty("UUID") == true) {
findUUID = service.UUID;
}
if (typeof service.subtype == "undefined" && typeof subtype == "undefined") {
findSub = 0;
}
// If subtype is "null" find newest event based on time
var typeIndex = this.historyData.types.findIndex(type => ((type.type == findUUID && type.sub == findSub && subtype != null) || (type.type == findUUID && subtype == null)));
return (typeIndex != -1 ? this.historyData.data[this.historyData.types[typeIndex].lastEntry] : null);
}
HomeKitHistory.prototype.entryCount = function(service, subtype, specifickey) {
// returns the number of history entries for this service type and subtype
// can can also be limited to a specific key value
var tempHistory = this.getHistory(service, subtype, specifickey);
return tempHistory.length;
}
HomeKitHistory.prototype.__updateHistoryTypes = function() {
// Builds the known history types and last entry in current history data
// Might be time consuming.....
this.historyData.types = [];
for (var index = (this.historyData.data.length - 1); index > 0; index--) {
if (this.historyData.types.findIndex(type => ((typeof type.sub != "undefined" && type.type == this.historyData.data[index].type && type.sub == this.historyData.data[index].sub) || (typeof type.sub == "undefined" && type.type == this.historyData.data[index].type))) == -1) {
this.historyData.types.push({type: this.historyData.data[index].type, sub: this.historyData.data[index].sub, lastEntry: index});
}
}
}
// Overlay EveHome service, characteristics and functions
// Alot of code taken from fakegato https://github.com/simont77/fakegato-history
// references from https://github.com/ebaauw/homebridge-lib/blob/master/lib/EveHomeKitTypes.js
//
const EPOCH_OFFSET = 978307200; // Seconds since 1/1/1970 to 1/1/2001
const EVEHOME_MAX_STREAM = 11; // Maximum number of history events we can stream to EveHome at once
var encodeEveData = function (string) {
return Buffer.from(("" + string).replace(/[^a-fA-F0-9]/ig, ""), "hex").toString("base64");
}
var decodeEveData = function (data) {
if (typeof data != "string") return data;
return Buffer.from(data, "base64").toString("hex");
}
// Converts a integer number into a string for EveHome, including formatting to byte width and reverse byte order
// handles upto 64bit values
var numberToEveHexString = function (number, bytes) {
if (typeof number != "number") return number;
var tempString = "0000000000000000" + Math.floor(number).toString(16);
tempString = tempString.slice(-1 * bytes).match(/[a-fA-F0-9]{2}/g).reverse().join('');
return tempString;
}
// Converts a float number into a string for EveHome, including formatting to byte width and reverse byte order
// handles upto 64bit values
var floatToEveHexString = function (number, bytes) {
if (typeof number != "number") return number;
var buf = Buffer.allocUnsafe(4);
buf.writeFloatBE(number, 0);
var tempString = "0000000000000000" + buf.toString("hex");
tempString = tempString.slice(-1 * bytes).match(/[a-fA-F0-9]{2}/g).reverse().join('');
return tempString;
}
// Converts Eve encoded hex string to number
var EveHexStringToNumber = function (string) {
if (typeof string != "string") return string;
var tempString = string.match(/[a-fA-F0-9]{2}/g).reverse().join('');
return Number(`0x${tempString}`); // convert to number on return
}
// Converts Eve encoded hex string to floating number with optional precision for result
var EveHexStringToFloat = function (string, precision) {
if (typeof string != "string") return string;
var tempString = string.match(/[a-fA-F0-9]{2}/g).reverse().join('');
var float = Buffer(tempString, "hex").readFloatBE(0);
return (precision != 0) ? float.toFixed(precision) : float;
}
// Overlay our history into EveHome. Can only have one service history exposed to EveHome (ATM... see if can work around)
// Returns object created for our EveHome accessory if successfull
HomeKitHistory.prototype.linkToEveHome = function(HomeKitAccessory, service, optionalParams) {
var allowReset = false;
var SetCommand = null;
var GetCommand = null;
if (typeof (optionalParams) === "object") {
allowReset = optionalParams.allowReset || false; // Allow EveHome to reset our history (clear it)
SetCommand = optionalParams.SetCommand || null; // function for set data for commands outside of this library
GetCommand = optionalParams.GetCommand || null; // function for get data for commands outside of this library
}
if (typeof this.EveHome == "undefined" || (this.EveHome && this.EveHome.hasOwnProperty("service") == false)) {
switch (service.UUID) {
case Service.Door.UUID :
case Service.Window.UUID :
case Service.GarageDoorOpener.UUID : {
// treat these as EveHome Door but with inverse status for open/closed
var historyService = HomeKitAccessory.addService(Service.EveHomeHistory, "", 1);
var tempHistory = this.getHistory(service.UUID, service.subtype);
var historyreftime = (tempHistory.length == 0 ? (this.historyData.reset - EPOCH_OFFSET) : (tempHistory[0].time - EPOCH_OFFSET));
this.EveHome = {service: historyService, linkedservice: service, type: service.UUID, sub: service.subtype, evetype: "door", signature1: "01 0601", signature2: "01", entry: 0, count: tempHistory.length, reftime: historyreftime, send: 0};
service.addCharacteristic(Characteristic.EveLastActivation);
service.addCharacteristic(Characteristic.EveOpenDuration);
service.addCharacteristic(Characteristic.EveClosedDuration);
service.addCharacteristic(Characteristic.EveTimesOpened);
// Setup initial values and callbacks for charateristics we are using
service.getCharacteristic(Characteristic.EveTimesOpened).updateValue(this.entryCount(this.EveHome.type, this.EveHome.sub, {status: 1})); // Count of entries based upon status = 1, opened
service.getCharacteristic(Characteristic.EveLastActivation).updateValue(this.__EveLastEventTime()); // time of last event in seconds since first event
service.getCharacteristic(Characteristic.EveTimesOpened).on("get", (callback) => {
callback(null, this.entryCount(this.EveHome.type, this.EveHome.sub, {status: 1})); // Count of entries based upon status = 1, opened
});
service.getCharacteristic(Characteristic.EveLastActivation).on("get", (callback) => {
callback(null, this.__EveLastEventTime()); // time of last event in seconds since first event
});
break;
}
case Service.ContactSensor.UUID : {
// treat these as EveHome Door
var historyService = HomeKitAccessory.addService(Service.EveHomeHistory, "", 1);
var tempHistory = this.getHistory(service.UUID, service.subtype);
var historyreftime = (tempHistory.length == 0 ? (this.historyData.reset - EPOCH_OFFSET) : (tempHistory[0].time - EPOCH_OFFSET));
this.EveHome = {service: historyService, linkedservice: service, type: service.UUID, sub: service.subtype, evetype: "contact", signature1: "01 0601", signature2: "01", entry: 0, count: tempHistory.length, reftime: historyreftime, send: 0};
service.addCharacteristic(Characteristic.EveLastActivation);
service.addCharacteristic(Characteristic.EveOpenDuration);
service.addCharacteristic(Characteristic.EveClosedDuration);
service.addCharacteristic(Characteristic.EveTimesOpened);
// Setup initial values and callbacks for charateristics we are using
service.getCharacteristic(Characteristic.EveTimesOpened).updateValue(this.entryCount(this.EveHome.type, this.EveHome.sub, {status: 1})); // Count of entries based upon status = 1, opened
service.getCharacteristic(Characteristic.EveLastActivation).updateValue(this.__EveLastEventTime()); // time of last event in seconds since first event
service.getCharacteristic(Characteristic.EveTimesOpened).on("get", (callback) => {
callback(null, this.entryCount(this.EveHome.type, this.EveHome.sub, {status: 1})); // Count of entries based upon status = 1, opened
});
service.getCharacteristic(Characteristic.EveLastActivation).on("get", (callback) => {
callback(null, this.__EveLastEventTime()); // time of last event in seconds since first event
});
break;
}
case Service.WindowCovering.UUID :
{
// Treat as Eve MotionBlinds
var historyService = HomeKitAccessory.addService(Service.EveHomeHistory, "", 1);
var tempHistory = this.getHistory(service.UUID, service.subtype);
var historyreftime = (tempHistory.length == 0 ? (this.historyData.reset - EPOCH_OFFSET) : (tempHistory[0].time - EPOCH_OFFSET));
this.EveHome = {service: historyService, linkedservice: service, type: service.UUID, sub: service.subtype, evetype: "blind", signature1: "01 0601", signature2: "01", entry: 0, count: tempHistory.length, reftime: historyreftime, send: 0};
service.addCharacteristic(Characteristic.EveGetConfiguration);
service.addCharacteristic(Characteristic.EveSetConfiguration);
//17 CurrentPosition
//18 TargetPosition
//19 PositionState
/* for (var index = 30; index < 115; index++) {
uuid = "E863F1" + numberToEveHexString(index, 2) + "-079E-48FF-8F27-9C2605A29F52";
eval(`Characteristic.EveTest`+ index + ` = function () {Characteristic.call(this, "Eve Test "+ index, uuid); this.setProps({format: Characteristic.Formats.DATA,perms: [Characteristic.Perms.READ, Characteristic.Perms.NOTIFY]});this.value = this.getDefaultValue();}`);
util.inherits(eval(`Characteristic.EveTest`+ index), Characteristic);
eval(`Characteristic.EveTest`+ index + `.UUID = uuid`);
service.addCharacteristic(eval(`Characteristic.EveTest`+ index));
console.log(uuid)
} */
this.productid = 00;
service.getCharacteristic(Characteristic.EveGetConfiguration).on("get", (callback) => {
var value = util.format(
"0002 %s 0302 %s 9b04 %s 1e02 %s 0c",
numberToEveHexString(this.productid, 4),
numberToEveHexString(1300, 4), // firmware version (build xxxx)
numberToEveHexString(Math.floor(new Date() / 1000), 8), // "now" time
numberToEveHexString(this.productid, 4));
console.log("EveGetConfiguration", value);
this.productid = this.productid + 1;
callback(null, encodeEveData(value));
});
service.getCharacteristic(Characteristic.EveSetConfiguration).on("set", (value, callback) => {
var processedData = {};
var valHex = decodeEveData(value);
var index = 0;
console.log("EveSetConfiguration", valHex);
while (index < valHex.length) {
// first byte is command in this data stream
// second byte is size of data for command
command = valHex.substr(index, 2);
size = parseInt(valHex.substr(index + 2, 2), 16) * 2;
data = valHex.substr(index + 4, parseInt(valHex.substr(index + 2, 2), 16) * 2);
switch(command) {
case "00" : {
// end of command?
break;
}
case "f0" : {
// set limits
// data
// 02 bottom position set
// 01 top position set
// 04 favourite position set
break;
}
case "f1" : {
// orientation set??
break;
}
case "f3" : {
// move window covering to set limits
// data
// 01c800 move up single press
// 02c800 move down single press
// 01d007 move up hold press
// 02d007 move down hold press
// 030000 stop from hold press
break;
}
default : {
console.log("DEBUG: Unknown Eve MotionBlinds command '%s' with data '%s'", command, data);
break;
}
}
index += (4 + size); // Move to next command accounting for header size of 4 bytes
}
callback();
});
break;
}
case Service.HeaterCooler.UUID :
case Service.Thermostat.UUID : {
// treat these as EveHome Thermo
var historyService = HomeKitAccessory.addService(Service.EveHomeHistory, "", 1);
var tempHistory = this.getHistory(service.UUID, service.subtype);
var historyreftime = (tempHistory.length == 0 ? (this.historyData.reset - EPOCH_OFFSET) : (tempHistory[0].time - EPOCH_OFFSET));
this.EveHome = {service: historyService, linkedservice: service, type: service.UUID, sub: service.subtype, evetype: "thermo", signature1: "06 0102 0202 1102 1001 1201 1d01", signature2: "3f", entry: 0, count: tempHistory.length, reftime: historyreftime, send: 0};
// Need some internal storage to track Eve Thermo configuration from EveHome app
this.__EveThermoPersist = {};
this.__EveThermoPersist.firmware = optionalParams.hasOwnProperty("EveThermo_firmware") ? optionalParams.EveThermo_firmware : 1251; // Firmware version 1251 2015 thermo, 2834 2020 thermo
this.__EveThermoPersist.attached = optionalParams.hasOwnProperty("EveThermo_attached") ? optionalParams.EveThermo_attached : false; // attached to base?
this.__EveThermoPersist.tempoffset = optionalParams.hasOwnProperty("EveThermo_tempoffset") ? optionalParams.EveThermo_tempoffset: -2.5; // Temperature offset. default -2.5
this.__EveThermoPersist.enableschedule = optionalParams.hasOwnProperty("EveThermo_enableschedule") ? optionalParams.EveThermo_enableschedule : false; // Schedules on/off
this.__EveThermoPersist.pause = optionalParams.hasOwnProperty("EveThermo_pause") ? optionalParams.EveThermo_pause : false; // Paused on/off
this.__EveThermoPersist.away = optionalParams.hasOwnProperty("EveThermo_away") ? optionalParams.EveThermo_away : false; // Vacation status - disabled ie: Home
this.__EveThermoPersist.awaytemp = optionalParams.hasOwnProperty("EveThermo_awaytemp") ? optionalParams.EveThermo_awaytemp : 0xff; // Vacation temp disabled
this.__EveThermoPersist.command1a = optionalParams.hasOwnProperty("EveThermo_command1a") ? optionalParams.EveThermo_command1a : "";
this.__EveThermoPersist.commandf4 = optionalParams.hasOwnProperty("EveThermo_commandf4") ? optionalParams.EveThermo_commandf4 : "";
this.__EveThermoPersist.commandfa = optionalParams.hasOwnProperty("EveThermo_commandfa") ? optionalParams.EveThermo_commandfa : "";
service.addCharacteristic(Characteristic.EveValvePosition); // Needed to show history for thermostat heating modes (valve position)
service.addCharacteristic(Characteristic.EveFirmware);
service.addCharacteristic(Characteristic.EveProgramData);
service.addCharacteristic(Characteristic.EveProgramCommand);
if (service.testCharacteristic(Characteristic.CurrentTemperature) === false) service.addCharacteristic(Characteristic.CurrentTemperature);
if (service.testCharacteristic(Characteristic.TemperatureDisplayUnits) === false) service.addCharacteristic(Characteristic.TemperatureDisplayUnits);
if (service.testCharacteristic(Characteristic.LockPhysicalControls) == false) service.addCharacteristic(Characteristic.LockPhysicalControls); // Allows childlock toggle to be displayed in Eve App
service.getCharacteristic(Characteristic.EveFirmware).updateValue(encodeEveData(util.format("2c %s be", numberToEveHexString(this.__EveThermoPersist.firmware, 4)))); // firmware version (build xxxx)));
// TODO - before enabling below need to workout:
// - mode graph to show
// - temperature unit setting
// - thermo 2020??
service.getCharacteristic(Characteristic.EveProgramData).on("get", (callback) => {
// commands
// 11 - valve protection on/off - TODO
// 12 - temp offset
// 13 - schedules enabled/disabled
// 16 - Window/Door open status
// 100000 - open
// 000000 - close
// 14 - installation status
// c0,c8 = ok
// c1,c6,c9 = in-progress
// c2,c3,c4,c5 = error on removal
// c7 = not attached
// 19 - vacation mode
// 00ff - off
// 01 + "away temp" - enabled with vacation temp
// f4 - temperatures
// fa - programs for week
// 1a - default day program
if (typeof optionalParams.GetCommand == "function") this.__EveThermo = optionGetFunction(this.__EveThermoPersist); // Fill in details we might want to be dynamic
// Encode the temperature offset into an unsigned value
var tempOffset = this.__EveThermoPersist.tempoffset * 10;
if (tempOffset < 127) tempOffset = tempOffset + 256;
var value = util.format(
"12%s 13%s 14%s 19%s %s %s",
numberToEveHexString(tempOffset, 2),
this.__EveThermoPersist.enableschedule == true ? "01" : "00",
service.getCharacteristic(Characteristic.StatusActive).value == true || optionalParams.EveThermo_attached == true ? "c0" : "c7",
this.__EveThermoPersist.away == true ? "01" + numberToEveHexString(this.__EveThermoPersist.awaytemp * 2, 2) : "00ff", // away status and temp
this.__EveThermoPersist.commandf4,
this.__EveThermoPersist.command1a,
this.__EveThermoPersist.commandfa);
callback(null, encodeEveData(value));
});
service.getCharacteristic(Characteristic.EveProgramCommand).on("set", (value, callback) => {
var programs = [];
var scheduleTemps = [];
var processedData = {};
var valHex = decodeEveData(value);
var index = 0;
console.log(valHex)
while (index < valHex.length) {
command = valHex.substr(index, 2);
index += 2; // skip over command value, and this is where data starts.
switch(command) {
case "00" : {
// start of command string ??
break;
}
case "06" : {
// end of command string ??
break;
}
case "7f" : {
// end of command string ??
break;
}
case "11" : {
// valve calibration/protection??
//0011ff00f22076
// 00f22076 - 111100100010000001110110
// 15868022
// 7620f2 - 011101100010000011110010
// 7741682
console.log(Math.floor(new Date() / 1000));
index += 10;
break;
}
case "10" : {
// OK to remove
break;
}
case "12" : {
// temperature offset
var tempOffset = parseInt(valHex.substr(index, 2), 16);
if (tempOffset > 127) tempOffset = tempOffset - 256;
tempOffset = tempOffset / 10;
this.__EveThermoPersist.tempoffset = tempOffset;
processedData.tempoffset = this.__EveThermoPersist.tempoffset;
index += 2;
break;
}
case "13" : {
// schedules enabled/disable
this.__EveThermoPersist.enableschedule = valHex.substr(index, 2) == "01" ? true : false;
processedData.enableschedule = this.__EveThermoPersist.enableschedule;
index += 2;
break;
}
case "14" : {
// Installed status
index += 2;
break;
}
case "18" : {
// Pause/resume via HomeKit automation/scene
// 20 - pause thermostat operation
// 10 - resume thermostat operation
this.__EveThermoPersist.pause = valHex.substr(index, 2) == "20" ? true : false;
processedData.pause = this.__EveThermoPersist.pause;
index += 2;
break;
}
case "19" : {
// Vacation on/off, vacation temperature via HomeKit automation/scene
var awayStatus = valHex.substr(index, 2) == "01" ? true : false;
var awayTemp = parseInt(valHex.substr(index + 2, 2), 16) * 0.5;
this.__EveThermoPersist.away = awayStatus;
this.__EveThermoPersist.awaytemp = awayTemp;
processedData.away = {"status": this.__EveThermoPersist.away, "temp": this.__EveThermoPersist.awaytemp};
index += 4;
break;
}
case "f4" : {
// Temperature Levels for schedule
this.__EveThermoPersist.commandf4 = "f400" + valHex.substr(index, 6); // save the command string
var currentTemp = valHex.substr(index, 2) == "80" ? null : parseInt(valHex.substr(index, 2), 16) * 0.5;
var ecoTemp = valHex.substr(index + 2, 2) == "80" ? null : parseInt(valHex.substr(index + 2, 2), 16) * 0.5;
var comfortTemp = valHex.substr(index + 4, 2) == "80" ? null : parseInt(valHex.substr(index + 4, 2), 16) * 0.5;
scheduleTemps = [ecoTemp, comfortTemp];
index += 6;
break;
}
case "fc" : {
// Date/Time
index += 10;
break;
}
case "fa" : {
// Programs (week - mon, tue, wed, thu, fri, sat, sun)
// index += 112;
this.__EveThermoPersist.commandfa = command + valHex.substr(index, 112); // save the command string
var daysofweek = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
for (index2 = 0; index2 < 7; index2++) {
var times = [];
for (index3 = 0; index3 < 4; index3++) {
// decode start time
var start = parseInt(valHex.substr(index, 2), 16);
var start_min = null;
var start_hr = null;
var start_offset = null;
if (start != 0xff) {
start_min = (start * 10) % 60; // Start minute
start_hr = ((start * 10) - start_min) / 60; // Start hour
start_offset = ((start * 10) * 60); // Seconds since 00:00
}
// decode end time
var end = parseInt(valHex.substr(index + 2, 2), 16);
var end_min = null;
var end_hr = null;
var end_offset = null;
if (end != 0xff) {
end_min = (end * 10) % 60; // End minute
end_hr = ((end * 10) - end_min) / 60; // End hour
end_offset = ((end * 10) * 60); // Seconds since 00:00
}
if (start_offset != null && end_offset != null) {
times.push({"type" : "time", "offset": start_offset, "duration" : (end_offset - start_offset)});
}
index += 4;
}
programs.push({"id": index2 + 1, "days": daysofweek[index2], "schedule": times, "temperature" : scheduleTemps});
}
processedData.programs = programs;
break;
}
case "1a" : {
// Program (day)
index += 16;
break;
}
case "f2" : {
// ??
index += 2;
break;
}
case "f6" : {
//??
index += 6;
break;
}
case "ff" : {
// ??
index += 4;
break;
}
default : {
console.log("DEBUG: Unknown Eve Thermo command '%s'", command);
break
}
}
};
// Send complete processed command data if configured to our callback
if (typeof optionalParams.SetCommand == "function" && Object.keys(processedData).length != 0) optionalParams.SetCommand(processedData);
callback();
});
break;
}
case Service.EveAirPressureSensor.UUID : {
// treat these as EveHome Weather (2015)
var historyService = HomeKitAccessory.addService(Service.EveHomeHistory, "", 1);
var tempHistory = this.getHistory(service.UUID, service.subtype);
var historyreftime = (tempHistory.length == 0 ? (this.historyData.reset - EPOCH_OFFSET) : (tempHistory[0].time - EPOCH_OFFSET));
service.addCharacteristic(Characteristic.EveFirmware);
service.getCharacteristic(Characteristic.EveFirmware).updateValue(encodeEveData(util.format("01 %s be", numberToEveHexString(809, 4)))); // firmware version (build xxxx)));
this.EveHome = {service: historyService, linkedservice: service, type: service.UUID, sub: service.subtype, evetype: "weather", signature1: "03 0102 0202 0302", signature2: "07", entry: 0, count: tempHistory.length, reftime: historyreftime, send: 0};
break;
}
case Service.AirQualitySensor.UUID :
case Service.TemperatureSensor.UUID : {
// treat these as EveHome Room(s)
var historyService = HomeKitAccessory.addService(Service.EveHomeHistory, "", 1);
var tempHistory = this.getHistory(service.UUID, service.subtype);
var historyreftime = (tempHistory.length == 0 ? (this.historyData.reset - EPOCH_OFFSET) : (tempHistory[0].time - EPOCH_OFFSET));
service.addCharacteristic(Characteristic.EveFirmware);
if (service.UUID == Service.AirQualitySensor.UUID) {
// Eve Room 2 (2018)
service.getCharacteristic(Characteristic.EveFirmware).updateValue(encodeEveData(util.format("27 %s be", numberToEveHexString(1416, 4)))); // firmware version (build xxxx)));
this.EveHome = {service: historyService, linkedservice: service, type: service.UUID, sub: service.subtype, evetype: "room2", signature1: "07 0102 0202 2202 2901 2501 2302 2801", signature2: "7f", entry: 0, count: tempHistory.length, reftime: historyreftime, send: 0};
if (service.testCharacteristic(Characteristic.VOCDensity) == false) service.addCharacteristic(Characteristic.VOCDensity);
// Need to ensure HomeKit accessory which has Air Quality service also has temperature & humidity services.
// Temperature service needs characteristic Characteristic.TemperatureDisplayUnits set to Characteristic.TemperatureDisplayUnits.CELSIUS
}
if (service.UUID == Service.TemperatureSensor.UUID) {
// Eve Room (2015)
service.getCharacteristic(Characteristic.EveFirmware).updateValue(encodeEveData(util.format("02 %s be", numberToEveHexString(1151, 4)))); // firmware version (build xxxx)));
this.EveHome = {service: historyService, linkedservice: service, type: service.UUID, sub: service.subtype, evetype: "room", signature1: "04 0102 0202 0402 0f03", signature2: "1f", entry: 0, count: tempHistory.length, reftime: historyreftime, send: 0};
if (service.testCharacteristic(Characteristic.TemperatureDisplayUnits) == false) service.addCharacteristic(Characteristic.TemperatureDisplayUnits); // Needed to show history for temperature
service.getCharacteristic(Characteristic.TemperatureDisplayUnits).updateValue(Characteristic.TemperatureDisplayUnits.CELSIUS); // Temperature needs to be in Celsius
}
break;
}
case Service.MotionSensor.UUID : {
// treat these as EveHome Motion
var historyService = HomeKitAccessory.addService(Service.EveHomeHistory, "", 1);
var tempHistory = this.getHistory(service.UUID, service.subtype);
var historyreftime = (tempHistory.length == 0 ? (this.historyData.reset - EPOCH_OFFSET) : (tempHistory[0].time - EPOCH_OFFSET));
// Need some internal storage to track Eve Motion configuration from EveHome app
this.__EveMotionPersist = {};
this.__EveMotionPersist.duration = optionalParams.hasOwnProperty("EveMotion_duration") ? optionalParams.EveMotion_duration : 5; // default 5 seconds
this.__EveMotionPersist.sensitivity = optionalParams.hasOwnProperty("EveMotion_sensitivity") ? optionalParams.EveMotion_sensivity : Characteristic.EveSensitivity.HIGH; // default sensitivity
this.__EveMotionPersist.ledmotion = optionalParams.hasOwnProperty("EveMotion_ledmotion") ? optionalParams.EveMotion_ledmotion: false; // off
this.EveHome = {service: historyService, linkedservice: service, type: service.UUID, sub: service.subtype, evetype: "motion", signature1:"02 1301 1c01", signature2: "02", entry: 0, count: tempHistory.length, reftime: historyreftime, send: 0};
service.addCharacteristic(Characteristic.EveSensitivity);
service.addCharacteristic(Characteristic.EveDuration);
service.addCharacteristic(Characteristic.EveLastActivation);
//service.addCharacteristic(Characteristic.EveGetConfiguration);
//service.addCharacteristic(Characteristic.EveSetConfiguration);
// Setup initial values and callbacks for charateristics we are using
service.getCharacteristic(Characteristic.EveLastActivation).updateValue(this.__EveLastEventTime()); // time of last event in seconds since first event
service.getCharacteristic(Characteristic.EveLastActivation).on("get", (callback) => {
callback(null, this.__EveLastEventTime()); // time of last event in seconds since first event
});
service.getCharacteristic(Characteristic.EveSensitivity).updateValue(this.__EveMotionPersist.sensitivity);
service.getCharacteristic(Characteristic.EveSensitivity).on("get", (callback) => {
callback(null, this.__EveMotionPersist.sensitivity);
});
service.getCharacteristic(Characteristic.EveSensitivity).on("set", (value, callback) => {
this.__EveMotionPersist.sensitivity = value;
callback();
});
service.getCharacteristic(Characteristic.EveDuration).updateValue(this.__EveMotionPersist.duration);
service.getCharacteristic(Characteristic.EveDuration).on("get", (callback) => {
callback(null, this.__EveMotionPersist.duration);
});
service.getCharacteristic(Characteristic.EveDuration).on("set", (value, callback) => {
this.__EveMotionPersist.duration = value;
callback();
});
/*service.getCharacteristic(Characteristic.EveGetConfiguration).updateValue(encodeEveData("300100"));
service.getCharacteristic(Characteristic.EveGetConfiguration).on("get", (callback) => {
var value = util.format(
"0002 2500 0302 %s 9b04 %s 8002 ffff 1e02 2500 0c",
numberToEveHexString(1144, 4), // firmware version (build xxxx)
numberToEveHexString(Math.floor(new Date() / 1000), 8), // "now" time
); // Not sure why 64bit value???
console.log("Motion set", value)
callback(null, encodeEveData(value));
});
service.getCharacteristic(Characteristic.EveSetConfiguration).on("set", (value, callback) => {
var valHex = decodeEveData(value);
var index = 0;
while (index < valHex.length) {
// first byte is command in this data stream
// second byte is size of data for command
command = valHex.substr(index, 2);
size = parseInt(valHex.substr(index + 2, 2), 16) * 2;
data = valHex.substr(index + 4, parseInt(valHex.substr(index + 2, 2), 16) * 2);
switch(command) {
case "30" : {
this.__EveMotionPersist.ledmotion = (data == "01" ? true : false);
break;
}