-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathmain.js
1829 lines (1684 loc) · 91.3 KB
/
main.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
'use strict';
const utils = require('@iobroker/adapter-core');
const EXPIRATION_WINDOW_IN_SECONDS = 125; //bit more than 2 minutes
const EXPIRATION_LOGIN_WINDOW_IN_SECONDS = 10;
const tado_auth_url = 'https://auth.tado.com';
const tado_url = 'https://my.tado.com';
const tado_app_url = `https://app.tado.com/`;
const tadoX_url = `https://hops.tado.com`;
const tado_config = {
client: {
id: 'tado-web-app',
secret: 'wZaRN7rpjn3FoNyF5IFuxg9uMzYJcvOoQ8QWiIqS3hfk6gLhVlG57j5YNoZL2Rtc',
},
auth: {
tokenHost: tado_auth_url,
}
};
const { ResourceOwnerPassword } = require('simple-oauth2');
const jsonExplorer = require('iobroker-jsonexplorer');
const state_attr = require(`${__dirname}/lib/state_attr.js`); // Load attribute library
const isOnline = require('@esm2cjs/is-online').default;
const https = require('https');
const axios = require('axios');
const { version } = require('./package.json');
// @ts-ignore
let axiosInstance = axios.create({
timeout: 20000, //20000
baseURL: `${tado_url}/`,
httpsAgent: new https.Agent({ keepAlive: true }),
referer: tado_app_url,
origin: tado_app_url
});
const ONEHOUR = 60 * 60 * 1000;
let polling; // Polling timer
let pooltimer = [];
class Tado extends utils.Adapter {
/**
* @param {Partial<ioBroker.AdapterOptions>} [options={}]
*/
constructor(options) {
// @ts-ignore
super({
...options,
name: 'tado',
});
this.on('ready', this.onReady.bind(this));
this.on('stateChange', this.onStateChange.bind(this));
this.on('unload', this.onUnload.bind(this));
jsonExplorer.init(this, state_attr);
this.accessToken = null;
this.getMe_data = null;
this.home_data = null;
this.lastupdate = 0;
this.apiCallinExecution = false;
this.intervall_time = 60 * 1000;
this.roomCapabilities = {};
this.oldStatesVal = [];
this.isTadoX = false;
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
jsonExplorer.sendVersionInfo(version);
this.log.info('Started with JSON-Explorer version ' + jsonExplorer.version);
this.intervall_time = Math.max(30, this.config.intervall) * 1000;
// Reset the connection indicator during startup
await jsonExplorer.stateSetCreate('info.connection', 'connection', false);
await this.DoConnect();
}
/**
* Is called when adapter shuts down - callback has to be called under any circumstances!
* @param {() => void} callback
*/
onUnload(callback) {
try {
//this.resetTimer();
this.log.info('cleaned everything up...');
callback();
} catch {
callback();
}
}
//////////////////////////////////////////////////////////////////////
/* ON STATE CHANGE */
//////////////////////////////////////////////////////////////////////
/**
* @param {string} id
* @param {ioBroker.State} state
* @param {string} homeId
* @param {string} roomId
* @param {string} deviceId
* @param {string} statename
* @param {string} beforeStatename
*/
async onStateChangeTadoX(id, state, homeId, roomId, deviceId, statename, beforeStatename) {
this.log.debug(id + ' changed');
const temperature = await this.getStateAsync(homeId + '.Rooms.' + roomId + '.setting.temperature.value');
const mode = await this.getStateAsync(homeId + '.Rooms.' + roomId + '.manualControlTermination.controlType');
const power = await this.getStateAsync(homeId + '.Rooms.' + roomId + '.setting.power');
const remainingTimeInSeconds = await this.getStateAsync(homeId + '.Rooms.' + roomId + '.manualControlTermination.remainingTimeInSeconds');
const nextTimeBlockStart = await this.getStateAsync(homeId + '.Rooms.' + roomId + '.nextTimeBlock.start');
const boostMode = await this.getStateAsync(homeId + '.Rooms.' + roomId + '.boostMode');
const set_boostMode = (boostMode == null || boostMode == undefined || boostMode.val == null || boostMode.val == '') ? false : toBoolean(boostMode.val);
const set_remainingTimeInSeconds = (remainingTimeInSeconds == null || remainingTimeInSeconds == undefined || remainingTimeInSeconds.val == null) ? 1800 : parseInt(remainingTimeInSeconds.val.toString());
const set_temp = (temperature == null || temperature == undefined || temperature.val == null || temperature.val == '') ? 20 : parseFloat(temperature.val.toString());
const set_NextTimeBlockStartExists = (nextTimeBlockStart == null || nextTimeBlockStart == undefined || nextTimeBlockStart.val == null || nextTimeBlockStart.val == '') ? false : true;
let set_power = (power == null || power == undefined || power.val == null || power.val == '') ? 'OFF' : power.val.toString().toUpperCase();
let set_terminationMode = (mode == null || mode == undefined || mode.val == null || mode.val == '') ? 'NO_OVERLAY' : mode.val.toString().toUpperCase();
this.log.debug('boostMode is: ' + set_boostMode);
this.log.debug('Power is: ' + set_power);
this.log.debug(`Temperature is: ${set_temp}`);
this.log.debug('Termination mode is: ' + set_terminationMode);
this.log.debug('RemainingTimeInSeconds is: ' + set_remainingTimeInSeconds);
this.log.debug('NextTimeBlockStart exists: ' + set_NextTimeBlockStartExists);
this.log.debug('DevicId is: ' + deviceId);
switch (statename) {
case ('power'):
if (set_terminationMode == 'NO_OVERLAY') {
if (set_power == 'ON') {
this.log.debug(`Overlay cleared for room '${roomId}' in home '${homeId}'`);
await this.setResumeRoomScheduleTadoX(homeId, roomId);
break;
}
else {
set_terminationMode = 'MANUAL';
}
}
await this.setManualControlTadoX(homeId, roomId, set_power, set_temp, set_terminationMode, set_boostMode, set_remainingTimeInSeconds);
if (set_power == 'OFF') jsonExplorer.stateSetCreate(homeId + '.Rooms.' + roomId + '.setting.temperature.value', 'value', null);
break;
case ('value'):
if (beforeStatename != 'temperature') {
this.log.warn('Change of ' + id + ' ignored'); break;
}
if (set_terminationMode == 'NO_OVERLAY') {
if (set_NextTimeBlockStartExists) set_terminationMode = 'NEXT_TIME_BLOCK';
else set_terminationMode = 'MANUAL';
}
set_power = 'ON';
await this.setManualControlTadoX(homeId, roomId, set_power, set_temp, set_terminationMode, set_boostMode, set_remainingTimeInSeconds);
break;
case ('boost'):
if (state.val == true) {
await this.setBoostTadoX(homeId);
await jsonExplorer.sleep(1000);
this.create_state(id, 'boost', false);
}
break;
case ('resumeScheduleHome'):
if (state.val == true) {
await this.setResumeHomeScheduleTadoX(homeId);
await jsonExplorer.sleep(1000);
this.create_state(id, 'resumeScheduleHome', false);
}
break;
case ('resumeScheduleRoom'):
if (state.val == true) {
await this.setResumeRoomScheduleTadoX(homeId, roomId);
await jsonExplorer.sleep(1000);
this.create_state(id, 'resumeScheduleRoom', false);
}
break;
case ('allOff'):
if (state.val == true) {
await this.setAllOffTadoX(homeId);
await jsonExplorer.sleep(1000);
this.create_state(id, 'allOff', false);
}
break;
case ('remainingTimeInSeconds'):
set_terminationMode = 'TIMER';
await this.setManualControlTadoX(homeId, roomId, set_power, set_temp, set_terminationMode, set_boostMode, set_remainingTimeInSeconds);
break;
case ('controlType'):
if (beforeStatename != 'manualControlTermination') {
this.log.warn('Change of ' + id + ' ignored'); break;
}
await this.setManualControlTadoX(homeId, roomId, set_power, set_temp, set_terminationMode, set_boostMode, set_remainingTimeInSeconds);
break;
}
}
/**
* Is called if a subscribed state changes
* @param {string} id
* @param {ioBroker.State | null | undefined} state
*/
async onStateChange(id, state) {
if (state) {
// The state was changed
if (state.ack === false) {
if (this.oldStatesVal[id] === state.val) {
this.log.debug(`State ${id} did not change, value is ${state.val}. No further actions!`);
return;
}
try {
this.log.debug('GETS INTERESSTING!!!');
const idSplitted = id.split('.');
const homeId = idSplitted[2];
const zoneId = idSplitted[4];
const deviceId = idSplitted[6];
const statename = idSplitted[idSplitted.length - 1];
const beforeStatename = idSplitted[idSplitted.length - 2];
this.log.debug(`Attribute '${id}' changed. '${statename}' will be checked.`);
if (statename != 'meterReadings' && statename != 'presence') {
if (this.isTadoX) {
await this.onStateChangeTadoX(id, state, homeId, zoneId, deviceId, statename, beforeStatename);
return;
}
}
if (statename == 'meterReadings') {
let meterReadings = {};
try {
meterReadings = JSON.parse(String(state.val));
} catch (error) {
this.log.error(`'${state.val}' is not a valide JSON for meterReadings - ${error}`);
return;
}
if (meterReadings.date && meterReadings.reading) {
let date = String(meterReadings.date);
if (typeof meterReadings.reading != 'number') {
this.log.error('meterReadings.reading is not a number!');
return;
}
let regEx = /^\d{4}-\d{2}-\d{2}$/;
if (!date.match(regEx)) {
this.log.error('dmeterReadings.date hat other format thanYYYY-MM-DD');
return;
}
await this.setReading(homeId, meterReadings);
} else {
this.log.error('meterReadings does not contain date and reading');
return;
}
}
else if (statename == 'offsetCelsius') {
const offset = state;
let set_offset = (offset == null || offset == undefined || offset.val == null) ? 0 : parseFloat(offset.val.toString());
this.log.debug(`Offset changed for device '${deviceId}' in home '${homeId}' to value '${set_offset}'`);
this.setTemperatureOffset(homeId, zoneId, deviceId, set_offset);
} else if (statename == 'childLockEnabled') {
const childLockEnabled = state;
let set_childLockEnabled = (childLockEnabled == null || childLockEnabled == undefined || childLockEnabled.val == null || childLockEnabled.val == '') ? false : toBoolean(childLockEnabled.val);
this.log.debug(`ChildLockEnabled changed for device '${deviceId}' in home '${homeId}' to value '${set_childLockEnabled}'`);
this.setChildLock(homeId, zoneId, deviceId, set_childLockEnabled);
} else if (statename == 'tt_id') {
const tt_id = state;
let set_tt_id = (tt_id == null || tt_id == undefined || tt_id.val == null || tt_id.val == '') ? 0 : parseInt(tt_id.val.toString());
this.log.debug(`TimeTable changed for room '${zoneId}' in home '${homeId}' to value '${set_tt_id}'`);
this.setActiveTimeTable(homeId, zoneId, set_tt_id);
} else if (statename == 'presence') {
const presence = state;
let set_presence = (presence == null || presence == undefined || presence.val == null || presence.val == '') ? 'HOME' : presence.val.toString().toUpperCase();
this.log.debug(`Presence changed in home '${homeId}' to value '${set_presence}'`);
this.setPresenceLock(homeId, set_presence);
} else if (statename == 'masterswitch') {
const masterswitch = state;
let set_masterswitch = (masterswitch == null || masterswitch == undefined || masterswitch.val == null || masterswitch.val == '') ? 'unknown' : masterswitch.val.toString().toUpperCase();
this.log.debug(`Masterswitch changed in home '${homeId}' to value '${set_masterswitch}'`);
await this.setMasterSwitch(set_masterswitch);
await this.sleep(1000);
await this.setState(`${homeId}.Home.masterswitch`, '', true);
} else if (statename == 'activateOpenWindow') {
this.log.debug(`Activate Open Window for room '${zoneId}' in home '${homeId}'`);
await this.setActivateOpenWindow(homeId, zoneId);
} else if (idSplitted[idSplitted.length - 2] === 'openWindowDetection' && (statename == 'openWindowDetectionEnabled' || statename == 'timeoutInSeconds')) {
const openWindowDetectionEnabled = await this.getStateAsync(homeId + '.Rooms.' + zoneId + '.openWindowDetection.openWindowDetectionEnabled');
const openWindowDetectionTimeoutInSeconds = await this.getStateAsync(homeId + '.Rooms.' + zoneId + '.openWindowDetection.timeoutInSeconds');
let set_openWindowDetectionEnabled = (openWindowDetectionEnabled == null || openWindowDetectionEnabled == undefined || openWindowDetectionEnabled.val == null || openWindowDetectionEnabled.val == '') ? false : toBoolean(openWindowDetectionEnabled.val);
let set_openWindowDetectionTimeoutInSeconds = (openWindowDetectionTimeoutInSeconds == null || openWindowDetectionTimeoutInSeconds == undefined || openWindowDetectionTimeoutInSeconds.val == null || openWindowDetectionTimeoutInSeconds.val == '') ? 900 : Number(openWindowDetectionTimeoutInSeconds.val);
this.log.debug('Open Window Detection enabled: ' + set_openWindowDetectionEnabled);
this.log.debug('Open Window Detection Timeout is: ' + set_openWindowDetectionTimeoutInSeconds);
this.log.debug(`Changing open window detection for '${zoneId}' in home '${homeId}'`);
await this.setOpenWindowDetectionSettings(homeId, zoneId, {
enabled: set_openWindowDetectionEnabled,
timeoutInSeconds: set_openWindowDetectionTimeoutInSeconds
});
} else {
const type = await this.getStateAsync(homeId + '.Rooms.' + zoneId + '.setting.type');
const temperature = await this.getStateAsync(homeId + '.Rooms.' + zoneId + '.setting.temperature.celsius');
const mode = await this.getStateAsync(homeId + '.Rooms.' + zoneId + '.overlay.termination.typeSkillBasedApp');
const power = await this.getStateAsync(homeId + '.Rooms.' + zoneId + '.setting.power');
const durationInSeconds = await this.getStateAsync(homeId + '.Rooms.' + zoneId + '.overlay.termination.durationInSeconds');
const nextTimeBlockStart = await this.getStateAsync(homeId + '.Rooms.' + zoneId + '.nextTimeBlock.start');
let acMode, fanLevel, horizontalSwing, verticalSwing, fanSpeed, swing, light;
let set_type = (type == null || type == undefined || type.val == null || type.val == '') ? 'HEATING' : type.val.toString().toUpperCase();
let set_durationInSeconds = (durationInSeconds == null || durationInSeconds == undefined || durationInSeconds.val == null) ? 1800 : parseInt(durationInSeconds.val.toString());
let set_temp = (temperature == null || temperature == undefined || temperature.val == null || temperature.val == '') ? 20 : parseFloat(temperature.val.toString());
let set_power = (power == null || power == undefined || power.val == null || power.val == '') ? 'OFF' : power.val.toString().toUpperCase();
let set_mode = (mode == null || mode == undefined || mode.val == null || mode.val == '') ? 'NO_OVERLAY' : mode.val.toString().toUpperCase();
let set_NextTimeBlockStartExists = (nextTimeBlockStart == null || nextTimeBlockStart == undefined || nextTimeBlockStart.val == null || nextTimeBlockStart.val == '') ? false : true;
if (set_type == 'AIR_CONDITIONING') {
acMode = await this.getStateAsync(homeId + '.Rooms.' + zoneId + '.setting.mode');
fanSpeed = await this.getStateAsync(homeId + '.Rooms.' + zoneId + '.setting.fanSpeed');
fanLevel = await this.getStateAsync(homeId + '.Rooms.' + zoneId + '.setting.fanLevel');
horizontalSwing = await this.getStateAsync(homeId + '.Rooms.' + zoneId + '.setting.horizontalSwing');
verticalSwing = await this.getStateAsync(homeId + '.Rooms.' + zoneId + '.setting.verticalSwing');
swing = await this.getStateAsync(homeId + '.Rooms.' + zoneId + '.setting.swing');
light = await this.getStateAsync(homeId + '.Rooms.' + zoneId + '.setting.light');
}
let set_light = '', set_swing = '', set_horizontalSwing = '', set_verticalSwing = '', set_fanLevel = '', set_fanSpeed = '', set_acMode = '';
if (acMode == undefined) set_acMode = 'NOT_AVAILABLE';
else {
set_acMode = (acMode == null || acMode.val == null || acMode.val == '') ? 'COOL' : acMode.val.toString().toUpperCase();
}
if (fanSpeed == undefined) set_fanSpeed = 'NOT_AVAILABLE';
else {
set_fanSpeed = (fanSpeed == null || fanSpeed.val == null || fanSpeed.val == '') ? 'AUTO' : fanSpeed.val.toString().toUpperCase();
}
if (fanLevel == undefined) set_fanLevel = 'NOT_AVAILABLE';
else {
set_fanLevel = (fanLevel == null || fanLevel.val == null || fanLevel.val == '') ? 'AUTO' : fanLevel.val.toString().toUpperCase();
}
if (horizontalSwing == undefined) set_horizontalSwing = 'NOT_AVAILABLE';
else {
set_horizontalSwing = (horizontalSwing == null || horizontalSwing.val == null || horizontalSwing.val == '') ? 'OFF' : horizontalSwing.val.toString().toUpperCase();
}
if (verticalSwing == undefined) set_verticalSwing = 'NOT_AVAILABLE';
else {
set_verticalSwing = (verticalSwing == null || verticalSwing.val == null || verticalSwing.val == '') ? 'OFF' : verticalSwing.val.toString().toUpperCase();
}
if (swing == undefined) set_swing = 'NOT_AVAILABLE';
else {
set_swing = (swing == null || swing.val == null || swing.val == '') ? 'OFF' : swing.val.toString().toUpperCase();
}
if (light == undefined) set_light = 'NOT_AVAILABLE';
else {
set_light = (light == null || light.val == null || light.val == '') ? 'OFF' : light.val.toString().toUpperCase();
}
this.log.debug('Type is: ' + set_type);
this.log.debug('Power is: ' + set_power);
this.log.debug(`Temperature is: ${set_temp}`);
this.log.debug('Execution mode (typeSkillBasedApp) is: ' + set_mode);
this.log.debug('DurationInSeconds is: ' + set_durationInSeconds);
this.log.debug('NextTimeBlockStart exists: ' + set_NextTimeBlockStartExists);
this.log.debug('Mode is: ' + set_acMode);
this.log.debug('FanSpeed is: ' + set_fanSpeed);
this.log.debug('FanLevel is: ' + set_fanLevel);
this.log.debug('HorizontalSwing is: ' + set_horizontalSwing);
this.log.debug('VerticalSwing is: ' + set_verticalSwing);
this.log.debug('Swing is: ' + set_swing);
this.log.debug('Light is: ' + set_light);
switch (statename) {
case ('overlayClearZone'):
this.log.debug(`Overlay cleared for room '${zoneId}' in home '${homeId}'`);
await this.setClearZoneOverlay(homeId, zoneId);
break;
case ('fahrenheit'): //do the same as with celsius but just convert to celsius
case ('celsius'):
if (statename == 'fahrenheit') {
set_temp = Math.round((5 / 9) * (Number(state.val) - 32) * 10) / 10;
}
if (set_mode == 'NO_OVERLAY') {
if (set_NextTimeBlockStartExists) set_mode = 'NEXT_TIME_BLOCK';
else set_mode = 'MANUAL';
}
set_power = 'ON';
this.log.debug(`Temperature changed for room '${zoneId}' in home '${homeId}' to '${set_temp}'`);
await this.setZoneOverlay(homeId, zoneId, set_power, set_temp, set_mode, set_durationInSeconds, set_type, set_acMode, set_fanLevel, set_horizontalSwing, set_verticalSwing, set_fanSpeed, set_swing, set_light);
break;
case ('durationInSeconds'):
set_mode = 'TIMER';
this.log.debug(`DurationInSecond changed for room '${zoneId}' in home '${homeId}' to '${set_durationInSeconds}'`);
await this.setState(`${homeId}.Rooms.${zoneId}.overlay.termination.typeSkillBasedApp`, set_mode, true);
await this.setZoneOverlay(homeId, zoneId, set_power, set_temp, set_mode, set_durationInSeconds, set_type, set_acMode, set_fanLevel, set_horizontalSwing, set_verticalSwing, set_fanSpeed, set_swing, set_light);
break;
case ('fanSpeed'):
this.log.debug(`FanSpeed changed for room '${zoneId}' in home '${homeId}' to '${set_fanSpeed}'`);
await this.setZoneOverlay(homeId, zoneId, set_power, set_temp, set_mode, set_durationInSeconds, set_type, set_acMode, set_fanLevel, set_horizontalSwing, set_verticalSwing, set_fanSpeed, set_swing, set_light);
break;
case ('mode'):
this.log.debug(`Mode changed for room '${zoneId}' in home '${homeId}' to '${set_acMode}'`);
await this.setZoneOverlay(homeId, zoneId, set_power, set_temp, set_mode, set_durationInSeconds, set_type, set_acMode, set_fanLevel, set_horizontalSwing, set_verticalSwing, set_fanSpeed, set_swing, set_light);
break;
case ('fanLevel'):
this.log.debug(`fanLevel changed for room '${zoneId}' in home '${homeId}' to '${set_fanLevel}'`);
await this.setZoneOverlay(homeId, zoneId, set_power, set_temp, set_mode, set_durationInSeconds, set_type, set_acMode, set_fanLevel, set_horizontalSwing, set_verticalSwing, set_fanSpeed, set_swing, set_light);
break;
case ('swing'):
this.log.debug(`swing changed for room '${zoneId}' in home '${homeId}' to '${set_swing}'`);
await this.setZoneOverlay(homeId, zoneId, set_power, set_temp, set_mode, set_durationInSeconds, set_type, set_acMode, set_fanLevel, set_horizontalSwing, set_verticalSwing, set_fanSpeed, set_swing, set_light);
break;
case ('light'):
this.log.debug(`light changed for room '${zoneId}' in home '${homeId}' to '${set_light}'`);
await this.setZoneOverlay(homeId, zoneId, set_power, set_temp, set_mode, set_durationInSeconds, set_type, set_acMode, set_fanLevel, set_horizontalSwing, set_verticalSwing, set_fanSpeed, set_swing, set_light);
break;
case ('horizontalSwing'):
this.log.debug(`horizontalSwing changed for room '${zoneId}' in home '${homeId}' to '${set_horizontalSwing}'`);
await this.setZoneOverlay(homeId, zoneId, set_power, set_temp, set_mode, set_durationInSeconds, set_type, set_acMode, set_fanLevel, set_horizontalSwing, set_verticalSwing, set_fanSpeed, set_swing, set_light);
break;
case ('verticalSwing'):
this.log.debug(`verticalSwing changed for room '${zoneId}' in home '${homeId}' to '${set_verticalSwing}'`);
await this.setZoneOverlay(homeId, zoneId, set_power, set_temp, set_mode, set_durationInSeconds, set_type, set_acMode, set_fanLevel, set_horizontalSwing, set_verticalSwing, set_fanSpeed, set_swing, set_light);
break;
case ('typeSkillBasedApp'):
if (set_mode == 'NO_OVERLAY') { break; }
this.log.debug(`TypeSkillBasedApp changed for room '${zoneId}' in home '${homeId}' to '${set_mode}'`);
await this.setZoneOverlay(homeId, zoneId, set_power, set_temp, set_mode, set_durationInSeconds, set_type, set_acMode, set_fanLevel, set_horizontalSwing, set_verticalSwing, set_fanSpeed, set_swing, set_light);
if (set_mode == 'MANUAL') {
await this.setState(`${homeId}.Rooms.${zoneId}.overlay.termination.expiry`, null, true);
await this.setState(`${homeId}.Rooms.${zoneId}.overlay.termination.durationInSeconds`, null, true);
await this.setState(`${homeId}.Rooms.${zoneId}.overlay.termination.remainingTimeInSeconds`, null, true);
}
break;
case ('power'):
if (set_mode == 'NO_OVERLAY') {
if (set_power == 'ON') {
this.log.debug(`Overlay cleared for room '${zoneId}' in home '${homeId}'`);
await this.setClearZoneOverlay(homeId, zoneId);
}
else {
set_mode = 'MANUAL';
this.log.debug(`Power changed for room '${zoneId}' in home '${homeId}' to '${state.val}' and temperature '${set_temp}' and mode '${set_mode}'`);
await this.setZoneOverlay(homeId, zoneId, set_power, set_temp, set_mode, set_durationInSeconds, set_type, set_acMode, set_fanLevel, set_horizontalSwing, set_verticalSwing, set_fanSpeed, set_swing, set_light);
}
} else {
this.log.debug(`Power changed for room '${zoneId}' in home '${homeId}' to '${state.val}' and temperature '${set_temp}' and mode '${set_mode}'`);
await this.setZoneOverlay(homeId, zoneId, set_power, set_temp, set_mode, set_durationInSeconds, set_type, set_acMode, set_fanLevel, set_horizontalSwing, set_verticalSwing, set_fanSpeed, set_swing, set_light);
}
break;
default:
}
}
this.log.debug('State change detected from different source than adapter');
this.log.debug(`state ${id} changed: ${state.val} (ack = ${state.ack})`);
} catch (error) {
this.log.error(`Issue at state change: ${error}`);
console.error(`Issue at state change: ${error}`);
this.errorHandling(error);
}
} else {
this.oldStatesVal[id] = state.val;
this.log.debug(`Changed value ${state.val} for ID ${id} stored`);
this.log.debug(`state ${id} changed: ${state.val} (ack = ${state.ack})`);
}
} else {
// The state was deleted
this.log.debug(`state ${id} deleted`);
}
}
//////////////////////////////////////////////////////////////////////
/* SET API CALLS */
//////////////////////////////////////////////////////////////////////
/**
* @param {string} homeId
* @param {string} roomId
* @param {string} power
* @param {number} temperature
* @param {string} terminationMode
* @param {boolean} boostMode
* @param {number} durationInSeconds
*/
async setManualControlTadoX(homeId, roomId, power, temperature, terminationMode, boostMode, durationInSeconds) {
//{`"setting`":{`"power`":`"ON`",`"isBoost`":false,`"temperature`":{`"value`":18.5,`"valueRaw`":18.52,`"precision`":0.1}},`"termination`":{`"type`":`"NEXT_TIME_BLOCK`"}}
if (power != 'ON' && power != 'OFF') throw new Error(`Power has value ${power} but should have the value 'ON' or 'OFF'.`);
if (terminationMode != 'NEXT_TIME_BLOCK' && terminationMode != 'MANUAL' && terminationMode != 'TIMER') throw new Error(`TerminationMode has value ${terminationMode} but should have 'NEXT_TIMEBLOCK' or 'MANUAL' or 'TIMER'.`);
temperature = Math.round(temperature * 10) / 10;
let payload = {};
payload.termination = {};
payload.termination.type = terminationMode;
payload.setting = {};
payload.setting.power = power;
payload.setting.isBoost = toBoolean(boostMode);
if (power == 'OFF') payload.setting.temperature = null;
else {
payload.setting.temperature = {};
payload.setting.temperature.value = temperature;
}
if (terminationMode == 'TIMER') payload.termination.durationInSeconds = durationInSeconds;
this.log.debug('setManualControlTadoX() payload is ' + JSON.stringify(payload));
let apiResponse = await this.apiCall(`${tadoX_url}/homes/${homeId}/rooms/${roomId}/manualControl`, 'post', payload);
this.log.debug('setManualControlTadoX() response is ' + JSON.stringify(apiResponse));
await this.DoRoomsStateTadoX(homeId, roomId);
}
/**
* @param {string} homeId
* @param {string} roomId
*/
async setResumeRoomScheduleTadoX(homeId, roomId) {
let apiResponse = await this.apiCall(`${tadoX_url}/homes/${homeId}/rooms/${roomId}/resumeSchedule`, 'post');
this.log.debug('setResumeRoomScheduleTadoX() response is ' + JSON.stringify(apiResponse));
await this.DoRoomsStateTadoX(homeId, roomId);
}
/**
* @param {string} homeId
*/
async setResumeHomeScheduleTadoX(homeId) {
let apiResponse = await this.apiCall(`${tadoX_url}/homes/${homeId}/quickActions/resumeSchedule`, 'post');
this.log.debug('setResumeHomeScheduleTadoX() response is ' + JSON.stringify(apiResponse));
await this.DoRoomsTadoX(homeId);
}
/**
* @param {string} homeId
*/
async setBoostTadoX(homeId) {
let apiResponse = await this.apiCall(`${tadoX_url}/homes/${homeId}/quickActions/boost`, 'post');
this.log.debug('setBoostTadoX() response is ' + JSON.stringify(apiResponse));
await this.DoRoomsTadoX(homeId);
}
/**
* @param {string} homeId
*/
async setAllOffTadoX(homeId) {
let apiResponse = await this.apiCall(`${tadoX_url}/homes/${homeId}/quickActions/allOff`, 'post');
this.log.debug('setAllOffTadoX() response is ' + JSON.stringify(apiResponse));
await this.DoRoomsTadoX(homeId);
}
/**
* @param {string} homeId
* @param {string} zoneId
*/
async setClearZoneOverlay(homeId, zoneId) {
try {
let url = `/api/v2/homes/${homeId}/zones/${zoneId}/overlay`;
if (await isOnline() == false) {
throw new Error('No internet connection detected!');
}
await this.apiCall(url, 'delete');
this.log.debug(`Called 'DELETE ${url}'`);
await jsonExplorer.setLastStartTime();
await this.DoZoneStates(homeId, zoneId);
this.log.debug('CheckExpire() at clearZoneOverlay() started');
await jsonExplorer.checkExpire(homeId + '.Rooms.' + zoneId + '.overlay.*');
}
catch (error) {
this.log.error(`Issue at clearZoneOverlay(): '${error}'`);
console.error(`Issue at clearZoneOverlay(): '${error}'`);
this.errorHandling(error);
}
}
/**
* @param {string} homeId
* @param {string} zoneId
* @param {string} deviceId
* @param {number} set_offset
*/
async setTemperatureOffset(homeId, zoneId, deviceId, set_offset) {
if (!set_offset) set_offset = 0;
if (set_offset <= -10 || set_offset > 10) this.log.warn('Offset out of range +/-10°');
set_offset = Math.round(set_offset * 100) / 100;
const offset = {
celsius: Math.min(10, Math.max(-9.99, set_offset))
};
try {
if (await isOnline() == false) {
throw new Error('No internet connection detected!');
}
let apiResponse = await this.apiCall(`/api/v2/devices/${deviceId}/temperatureOffset`, 'put', offset);
this.log.debug(`API 'temperatureOffset' for home '${homeId}' and deviceID '${deviceId}' with body ${JSON.stringify(offset)} called.`);
this.log.debug(`Response from 'temperatureOffset' is ${JSON.stringify(apiResponse)}`);
if (apiResponse) await this.DoTemperatureOffset(homeId, zoneId, deviceId, apiResponse);
}
catch (error) {
let eMsg = `Issue at setTemperatureOffset: '${error}'. Based on body ${JSON.stringify(offset)}`;
this.log.error(eMsg);
console.error(eMsg);
this.errorHandling(error);
}
}
/**
* @param {string} homeId
* @param {string} zoneId
* @param {number} timetableId
*/
async setActiveTimeTable(homeId, zoneId, timetableId) {
if (!timetableId) timetableId = 0;
if (!(timetableId == 0 || timetableId == 1 || timetableId == 2)) {
this.log.error(`Invalid value '${timetableId}' for state 'timetable_id'. Allowed values are '0', '1' and '2'.`);
return;
}
const timeTable = {
id: timetableId
};
let apiResponse;
this.log.debug('setActiveTimeTable JSON ' + JSON.stringify(timeTable));
//this.log.info(`Call API 'activeTimetable' for home '${homeId}' and zone '${zoneId}' with body ${JSON.stringify(timeTable)}`);
try {
if (await isOnline() == false) {
throw new Error('No internet connection detected!');
}
apiResponse = await this.apiCall(`/api/v2/homes/${homeId}/zones/${zoneId}/schedule/activeTimetable`, 'put', timeTable);
if (apiResponse) await this.DoTimeTables(homeId, zoneId, apiResponse);
this.log.debug(`API 'activeTimetable' for home '${homeId}' and zone '${zoneId}' with body ${JSON.stringify(timeTable)} called.`);
this.log.debug(`Response from 'setActiveTimeTable' is ${JSON.stringify(apiResponse)}`);
}
catch (error) {
let eMsg = `Issue at setActiveTimeTable: '${error}'. Based on body ${JSON.stringify(timeTable)}`;
this.log.error(eMsg);
console.error(eMsg);
this.errorHandling(error);
}
}
/**
* @param {string} homeId
* @param {string} homePresence
*/
async setPresenceLock(homeId, homePresence) {
if (!homePresence) homePresence = 'HOME';
if (homePresence !== 'HOME' && homePresence !== 'AWAY' && homePresence !== 'AUTO') {
this.log.error(`Invalid value '${homePresence}' for state 'homePresence'. Allowed values are HOME, AWAY and AUTO.`);
return;
}
const homeState = {
homePresence: homePresence.toUpperCase()
};
let apiResponse;
this.log.debug('homePresence JSON ' + JSON.stringify(homeState));
//this.log.info(`Call API 'activeTimetable' for home '${homeId}' and zone '${zoneId}' with body ${JSON.stringify(timeTable)}`);
try {
if (await isOnline() == false) {
throw new Error('No internet connection detected!');
}
if (homePresence === 'AUTO') {
apiResponse = await this.apiCall(`/api/v2/homes/${homeId}/presenceLock`, 'delete');
} else {
apiResponse = await this.apiCall(`/api/v2/homes/${homeId}/presenceLock`, 'put', homeState);
}
await this.DoHomeState(homeId);
this.log.debug(`API 'state' for home '${homeId}' with body ${JSON.stringify(homeState)} called.`);
this.log.debug(`Response from 'presenceLock' is ${JSON.stringify(apiResponse)}`);
}
catch (error) {
let eMsg = `Issue at setPresenceLock: '${error}'. Based on body ${JSON.stringify(homeState)}`;
this.log.error(eMsg);
console.error(eMsg);
this.errorHandling(error);
}
}
/**
* @param {string} homeId
* @param {string} zoneId
* @param {string} power
* @param {number} temperature
* @param {string} typeSkillBasedApp
* @param {number} durationInSeconds
* @param {string} type
* @param {string} acMode
* @param {string} fanLevel
* @param {string} horizontalSwing
* @param {string} verticalSwing
* @param {string} fanSpeed
* @param {string} swing
* @param {string} light
*/
async setZoneOverlay(homeId, zoneId, power, temperature, typeSkillBasedApp, durationInSeconds, type, acMode, fanLevel, horizontalSwing, verticalSwing, fanSpeed, swing, light) {
power = power.toUpperCase();
typeSkillBasedApp = typeSkillBasedApp.toUpperCase();
durationInSeconds = Math.max(10, durationInSeconds);
type = type.toUpperCase();
fanSpeed = fanSpeed.toUpperCase();
acMode = acMode.toUpperCase();
fanLevel = fanLevel.toUpperCase();
horizontalSwing = horizontalSwing.toUpperCase();
verticalSwing = verticalSwing.toUpperCase();
swing = swing.toUpperCase();
light = light.toUpperCase();
if (!temperature) temperature = 21;
temperature = Math.round(temperature * 100) / 100;
let config = {
setting: {
type: type,
}
};
try {
config.setting.power = power;
if (typeSkillBasedApp != 'NO_OVERLAY') {
config.termination = {};
config.termination.typeSkillBasedApp = typeSkillBasedApp;
if (typeSkillBasedApp != 'TIMER') {
config.termination.durationInSeconds = null;
}
else {
config.termination.durationInSeconds = durationInSeconds;
}
}
if (type != 'HEATING' && type != 'AIR_CONDITIONING' && type != 'HOT_WATER') {
this.log.error(`Invalid value '${type}' for state 'type'. Supported values are HOT_WATER, AIR_CONDITIONING and HEATING`);
return;
}
if (power != 'ON' && power != 'OFF') {
this.log.error(`Invalid value '${power}' for state 'power'. Supported values are ON and OFF`);
return;
}
if (typeSkillBasedApp != 'TIMER' && typeSkillBasedApp != 'MANUAL' && typeSkillBasedApp != 'NEXT_TIME_BLOCK' && typeSkillBasedApp != 'NO_OVERLAY' && typeSkillBasedApp != 'TADO_MODE') {
this.log.error(`Invalid value '${typeSkillBasedApp}' for state 'typeSkillBasedApp'. Allowed values are TIMER, MANUAL and NEXT_TIME_BLOCK`);
return;
}
/* Capability Management
{"1":{"type":"HEATING","temperatures":{"celsius":{"min":5,"max":25,"step":0.1},"fahrenheit":{"min":41,"max":77,"step":0.1}}}}
{"0":{"type":"HOT_WATER","canSetTemperature":true,"temperatures":{"celsius":{"min":30,"max":65,"step":1},"fahrenheit":{"min":86,"max":149,"step":1}}}}
{"0":{"type":"HOT_WATER","canSetTemperature":false}}
{"1":{"type":"AIR_CONDITIONING","COOL":{"temperatures":{"celsius":{"min":16,"max":30,"step":1},"fahrenheit":{"min":61,"max":86,"step":1}},"fanSpeeds":["AUTO","HIGH","MIDDLE","LOW"],"swings":["OFF","ON"]},"DRY":{"fanSpeeds":["MIDDLE","LOW"],"swings":["OFF","ON"]},"FAN":{"fanSpeeds":["HIGH","MIDDLE","LOW"],"swings":["OFF","ON"]},"HEAT":{"temperatures":{"celsius":{"min":16,"max":30,"step":1},"fahrenheit":{"min":61,"max":86,"step":1}},"fanSpeeds":["AUTO","HIGH","MIDDLE","LOW"],"swings":["OFF","ON"]},"initialStates":{"mode":"COOL","modes":{"COOL":{"temperature":{"celsius":23,"fahrenheit":74},"fanSpeed":"LOW","swing":"OFF"},"DRY":{"fanSpeed":"LOW","swing":"OFF"},"FAN":{"fanSpeed":"LOW","swing":"OFF"},"HEAT":{"temperature":{"celsius":23,"fahrenheit":74},"fanSpeed":"LOW","swing":"OFF"}}}},"3":{"type":"AIR_CONDITIONING","COOL":{"temperatures":{"celsius":{"min":16,"max":30,"step":1},"fahrenheit":{"min":61,"max":86,"step":1}},"fanSpeeds":["AUTO","HIGH","MIDDLE","LOW"],"swings":["OFF","ON"]},"DRY":{"fanSpeeds":["MIDDLE","LOW"],"swings":["OFF","ON"]},"FAN":{"fanSpeeds":["HIGH","MIDDLE","LOW"],"swings":["OFF","ON"]},"HEAT":{"temperatures":{"celsius":{"min":16,"max":30,"step":1},"fahrenheit":{"min":61,"max":86,"step":1}},"fanSpeeds":["AUTO","HIGH","MIDDLE","LOW"],"swings":["OFF","ON"]},"initialStates":{"mode":"COOL","modes":{"COOL":{"temperature":{"celsius":23,"fahrenheit":74},"fanSpeed":"LOW","swing":"OFF"},"DRY":{"fanSpeed":"LOW","swing":"OFF"},"FAN":{"fanSpeed":"LOW","swing":"OFF"},"HEAT":{"temperature":{"celsius":23,"fahrenheit":74},"fanSpeed":"LOW","swing":"OFF"}}}}}
{"1":{"type":"AIR_CONDITIONING","HEAT":{"temperatures":{"celsius":{"min":16,"max":32,"step":1},"fahrenheit":{"min":61,"max":90,"step":1}},"fanLevel":["LEVEL2","LEVEL3","AUTO","LEVEL1"],"verticalSwing":["OFF","ON"],"horizontalSwing":["OFF","ON"],"light":["OFF","ON"]},"COOL":{"temperatures":{"celsius":{"min":16,"max":32,"step":1},"fahrenheit":{"min":61,"max":90,"step":1}},"fanLevel":["LEVEL2","LEVEL3","AUTO","LEVEL1"],"verticalSwing":["OFF","ON"],"horizontalSwing":["OFF","ON"],"light":["OFF","ON"]},"DRY":{"temperatures":{"celsius":{"min":16,"max":32,"step":1},"fahrenheit":{"min":61,"max":90,"step":1}},"fanLevel":["LEVEL2","LEVEL3","AUTO","LEVEL1"],"verticalSwing":["OFF","ON"],"horizontalSwing":["OFF","ON"],"light":["OFF","ON"]},"FAN":{"fanLevel":["LEVEL2","LEVEL3","LEVEL1"],"verticalSwing":["OFF","ON"],"horizontalSwing":["OFF","ON"],"light":["OFF","ON"]},"AUTO":{"fanLevel":["LEVEL2","LEVEL3","LEVEL1"],"verticalSwing":["OFF","ON"],"horizontalSwing":["OFF","ON"],"light":["OFF","ON"]},"initialStates":{"mode":"COOL","modes":{"COOL":{"temperature":{"celsius":24,"fahrenheit":76},"fanSpeed":null,"swing":null,"fanLevel":"LEVEL2","verticalSwing":"OFF","horizontalSwing":"OFF"},"HEAT":{"temperature":{"celsius":24,"fahrenheit":76},"fanSpeed":null,"swing":null,"fanLevel":"LEVEL2","verticalSwing":"OFF","horizontalSwing":"OFF"},"DRY":{"temperature":{"celsius":24,"fahrenheit":76},"fanSpeed":null,"swing":null,"fanLevel":"LEVEL2","verticalSwing":"OFF","horizontalSwing":"OFF"},"FAN":{"temperature":null,"fanSpeed":null,"swing":null,"fanLevel":"LEVEL2","verticalSwing":"OFF","horizontalSwing":"OFF"},"AUTO":{"temperature":null,"fanSpeed":null,"swing":null,"fanLevel":"LEVEL2","verticalSwing":"OFF","horizontalSwing":"OFF"}},"light":"ON"}}}
*/
console.log(JSON.stringify(this.roomCapabilities));
if (!this.roomCapabilities || !this.roomCapabilities[zoneId]) {
this.log.error(`No room capabilities found for room '${zoneId}'. Capabilities looks like '${JSON.stringify(this.roomCapabilities)}'`);
console.log(`No room capabilities found for room '${zoneId}'. Capabilities looks like '${JSON.stringify(this.roomCapabilities)}'`);
this.sendSentryWarn('Capabilities for zone not found');
return;
}
let capType = this.roomCapabilities[zoneId].type;
if (capType && capType != type) {
this.log.error(`Type ${type} not valid. Type ${capType} expected.`);
return;
}
if (type == 'HEATING' && power == 'ON') {
let capMinTemp, capMaxTemp;
if (this.roomCapabilities[zoneId].temperatures && this.roomCapabilities[zoneId].temperatures.celsius) {
capMinTemp = this.roomCapabilities[zoneId].temperatures.celsius.min; //valid for all heating devices
capMaxTemp = this.roomCapabilities[zoneId].temperatures.celsius.max; //valid for all heating devices
}
if (capMinTemp && capMaxTemp) {
if (temperature > capMaxTemp || temperature < capMinTemp) {
this.log.error(`Temperature of ${temperature}°C outside supported range of ${capMinTemp}°C to ${capMaxTemp}°C`);
return;
}
config.setting.temperature = {};
config.setting.temperature.celsius = temperature;
}
}
if (type == 'HOT_WATER' && power == 'ON') {
let capCanSetTemperature = this.roomCapabilities[zoneId].canSetTemperature; //valid for hotwater
let capMinTemp, capMaxTemp;
if (this.roomCapabilities[zoneId].temperatures && this.roomCapabilities[zoneId].temperatures.celsius) {
capMinTemp = this.roomCapabilities[zoneId].temperatures.celsius.min; //valid for hotwater if canSetTemperature == true
capMaxTemp = this.roomCapabilities[zoneId].temperatures.celsius.max; //valid for hotwater if canSetTemperature == true
}
if (capCanSetTemperature == true) {
if (capMinTemp && capMaxTemp) {
if (temperature > capMaxTemp || temperature < capMinTemp) {
this.log.error(`Temperature of ${temperature}°C outside supported range of ${capMinTemp}°C to ${capMaxTemp}°C`);
return;
}
}
config.setting.temperature = {};
config.setting.temperature.celsius = temperature;
}
}
if (type == 'AIR_CONDITIONING' && power == 'ON') {
if (!this.roomCapabilities[zoneId][acMode]) {
this.log.error(`AC-Mode ${acMode} not supported! Capailities looks like ${JSON.stringify(this.roomCapabilities)}`);
console.log(`AC-Mode ${acMode} in Room ${zoneId} not supported! Capailities looks like ${JSON.stringify(this.roomCapabilities)}`);
this.sendSentryWarn('Capabilities for acMode not found');
return;
}
config.setting.mode = acMode;
let capMinTemp, capMaxTemp;
if (this.roomCapabilities[zoneId][acMode].temperatures && this.roomCapabilities[zoneId][acMode].temperatures.celsius) {
capMinTemp = this.roomCapabilities[zoneId][acMode].temperatures.celsius.min; //valide v3 & v3+
capMaxTemp = this.roomCapabilities[zoneId][acMode].temperatures.celsius.max; //valide v3 & v3+
}
let capHorizontalSwing = this.roomCapabilities[zoneId][acMode].horizontalSwing; //valide v3+
let capVerticalSwing = this.roomCapabilities[zoneId][acMode].verticalSwing; //valide v3+
let capFanLevel = this.roomCapabilities[zoneId][acMode].fanLevel; //valide v3+
let capFanSpeeds = this.roomCapabilities[zoneId][acMode].fanSpeeds; //valide v3
let capSwings = this.roomCapabilities[zoneId][acMode].swings; //valide v3
let capLight = this.roomCapabilities[zoneId][acMode].light;
if (capMinTemp && capMaxTemp) {
if (temperature > capMaxTemp || temperature < capMinTemp) {
this.log.error(`Temperature of ${temperature}°C outside supported range of ${capMinTemp}°C to ${capMaxTemp}°C`);
return;
}
config.setting.temperature = {};
config.setting.temperature.celsius = temperature;
}
if (capHorizontalSwing) {
if (!capHorizontalSwing.includes(horizontalSwing)) {
this.log.error(`Invalid value '${horizontalSwing}' for state 'horizontalSwing'. Allowed values are ${JSON.stringify(capHorizontalSwing)}`);
return;
}
config.setting.horizontalSwing = horizontalSwing;
}
if (capVerticalSwing) {
if (!capVerticalSwing.includes(verticalSwing)) {
this.log.error(`Invalid value '${verticalSwing}' for state 'verticalSwing'. Allowed values are ${JSON.stringify(capVerticalSwing)}`);
return;
}
config.setting.verticalSwing = verticalSwing;
}
if (capFanSpeeds) {
if (!capFanSpeeds.includes(fanSpeed)) {
this.log.error(`Invalid value '${fanSpeed}' for state 'fanSpeed'. Allowed values are ${JSON.stringify(capFanSpeeds)}`);
return;
}
config.setting.fanSpeed = fanSpeed;
}
if (capFanLevel) {
if (!capFanLevel.includes(fanLevel)) {
this.log.error(`Invalid value '${fanLevel}' for state 'fanLevel'. Allowed values are ${JSON.stringify(capFanLevel)}`);
return;
}
config.setting.fanLevel = fanLevel;
}
if (capSwings) {
if (!capSwings.includes(swing)) {
this.log.error(`Invalid value '${swing}' for state 'swing'. Allowed values are ${JSON.stringify(capSwings)}`);
return;
}
config.setting.swing = swing;
}
if (capLight) {
if (!capLight.includes(light)) {
this.log.error(`Invalid value '${light}' for state 'light'. Allowed values are ${JSON.stringify(capLight)}`);
return;
}
config.setting.light = light;
}
}
let result = await this.setZoneOverlayPool(homeId, zoneId, config);
this.log.debug(`API 'ZoneOverlay' for home '${homeId}' and zone '${zoneId}' with body ${JSON.stringify(config)} called.`);
if (result == null) throw new Error('Result of setZoneOverlay is null');
if (result.setting.temperature == null) {
result.setting.temperature = {};
result.setting.temperature.celsius = null;
result.setting.temperature.fahrenheit = null;
}
await jsonExplorer.setLastStartTime();
await jsonExplorer.traverseJson(result, homeId + '.Rooms.' + zoneId + '.overlay', true, true, 2);
await jsonExplorer.traverseJson(result.setting, homeId + '.Rooms.' + zoneId + '.setting', true, true, 2);
this.log.debug('CheckExpire() at setZoneOverlay() started');
await jsonExplorer.checkExpire(homeId + '.Rooms.' + zoneId + '.overlay.*');
}
catch (error) {
console.log(`Body: ${JSON.stringify(config)}`);
this.log.error(`Issue at setZoneOverlay: '${error}'. Based on config ${JSON.stringify(config)}`);
console.error(`Issue at setZoneOverlay: '${error}'. Based on config ${JSON.stringify(config)}`);
this.errorHandling(error);
}
}
/**
* @param {string} homeId
* @param {string} zoneId
* @param {object} config
*/
async setZoneOverlayPool(homeId, zoneId, config) {
this.log.debug(`poolApiCall() entered for '${homeId}/${zoneId}'`);
let pooltimerid = homeId + zoneId;
if (await isOnline() == false) {
if (pooltimer[pooltimerid]) {
clearTimeout(pooltimer[pooltimerid]);
pooltimer[pooltimerid] = null;
}
throw new Error('No internet connection detected!');
}
if (pooltimer[pooltimerid]) { //Important, that there is no await function between clearTimeout() and setTimeout())
clearTimeout(pooltimer[pooltimerid]);
pooltimer[pooltimerid] = null;
}
let that = this;
return new Promise((resolve, reject) => {
pooltimer[pooltimerid] = setTimeout(async () => {
that.log.debug(`750ms queuing done [timer:'${pooltimerid}']. API will be caled.`);
await that.apiCall(`/api/v2/homes/${homeId}/zones/${zoneId}/overlay`, 'put', config).then(apiResponse => {
resolve(apiResponse);
that.log.debug(`API request finalized for '${homeId}/${zoneId}'`);
}).catch(error => {
reject(error);
});
that.log.debug(`API called with ${JSON.stringify(config)}`);
}, 750);
});
}
/**
* Calls the "Active Open Window" endpoint. If the tado thermostat did not detect an open window, the call does nothing.
* @param {string} homeId
* @param {string} zoneId
*/
async setActivateOpenWindow(homeId, zoneId) {
try {
let url = `/api/v2/homes/${homeId}/zones/${zoneId}/state/openWindow/activate`;
if (await isOnline() == false) {
throw new Error('No internet connection detected!');
}
await this.apiCall(url, 'post');
this.log.debug(`Called 'POST ${url}'`);
await jsonExplorer.setLastStartTime();
await this.DoZoneStates(homeId, zoneId);
await jsonExplorer.checkExpire(homeId + '.Rooms.' + zoneId + '.openWindow.*');
}
catch (error) {
this.log.error(`Issue at activateOpenWindow(): '${error}'`);
console.error(`Issue at activateOpenWindow(): '${error}'`);
this.errorHandling(error);
}
}
/**
* @param {string} homeId
* @param {string} zoneId
* @param {any} config Payload needs to be an object like this {"enabled":true,"timeoutInSeconds":960}
*/
async setOpenWindowDetectionSettings(homeId, zoneId, config) {
try {
let url = `/api/v2/homes/${homeId}/zones/${zoneId}/openWindowDetection`;
if (await isOnline() == false) {
throw new Error('No internet connection detected!');
}
await this.apiCall(url, 'put', config);
await jsonExplorer.setLastStartTime();
await this.DoZoneStates(homeId, zoneId);
await jsonExplorer.checkExpire(homeId + '.Rooms.' + zoneId + '.openWindowDetection.*');
}
catch (error) {
console.log(`Body: ${JSON.stringify(config)}`);
this.log.error(`Issue at setOpenWindowDetectionSettings(): '${error}'`);
console.error(`Issue at setOpenWindowDetectionSettings(): '${error}'`);
this.errorHandling(error);
}
}
/**
* @param {string} homeId
* @param {string} zoneId
* @param {string} deviceId
* @param {boolean} enabled
*/
async setChildLock(homeId, zoneId, deviceId, enabled) {
try {
let url = `/api/v2/devices/${deviceId}/childLock`;
if (await isOnline() == false) {
throw new Error('No internet connection detected!');
}
await this.apiCall(url, 'put', { childLockEnabled: enabled });