-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathmain.js
4117 lines (4058 loc) · 133 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';
/*
* Created with @iobroker/create-adapter v1.31.0
*/
// The adapter-core module gives you access to the core ioBroker functions
// you need to create an adapter
const utils = require('@iobroker/adapter-core');
// Load your modules here, e.g.:
// const fs = require("fs");
const Fritz = require('fritzdect-aha-nodejs').Fritz;
/*
let Fritz;
(async () => {
let fb = await import('fritzdect-aha-nodejs');
Fritz = fb.Fritz;
})().catch((err) => console.error(err));
*/
const parser = require('./lib/xml2json.js');
let polling;
/* errorcodes hkr
0: kein Fehler
1: Keine Adaptierung möglich. Gerät korrekt am Heizkörper montiert?
2: Ventilhub zu kurz oder Batterieleistung zu schwach. Ventilstößel per Hand mehrmals öfnen und schließen oder neue Batterien einsetzen.
3: Keine Ventilbewegung möglich. Ventilstößel frei?
4: Die Installation wird gerade vorbereitet.
5: Der Heizkörperregler ist im Installationsmodus und kann auf das Heizungsventil montiert werden.
6: Der Heizkörperregler passt sich nun an den Hub des Heizungsventils an.
*/
/* errorcodes blind
alert state
Beim Rollladen als Bitmaske auszuwerten.
0000 0000 - Es liegt kein Fehler vor.
0000 0001 - Hindernisalarm, der Rollladen wird gestoppt und ein kleines Stück in entgegengesetzte Richtung bewegt.
0000 0010 - Temperaturalarm, Motor überhitzt.
*/
/*
functionbitmask
Bit 0: HAN-FUN Gerät
Bit 2: Licht/Lampe
Bit 4: Alarm-Sensor
Bit 5: AVM Button
Bit 6: AVM Heizkörperregler
Bit 7: AVM Energie Messgerät
Bit 8: Temperatursensor
Bit 9: AVM Schaltsteckdose
Bit 10: AVM DECT Repeater
Bit 11: AVM Mikrofon
Bit 13: HAN-FUN-Unit
Bit 15: an-/ausschaltbares Gerät/Steckdose/Lampe/Aktor
Bit 16: Gerät mit einstellbarem Dimm-, Höhen- bzw. Niveau-Level Bit 17: Lampe mit einstellbarer Farbe/Farbtemperatur
Bit 18: Rollladen(Blind) - hoch, runter, stop und level 0% bis 100 % Bit 20: Luftfeuchtigkeitssensor
Die Bits 5,6,7,9,10 und 11 werden nur von FRITZ!-Geräten verwendet und nicht von HANFUN- oder Zigbee-Geräten.
*/
/* HANFUN unittypes
256 = SIMPLE_ON_OFF_SWITCHABLE
257 = SIMPLE_ON_OFF_SWITCH
262 = AC_OUTLET
263 = AC_OUTLET_SIMPLE_POWER_METERING
264 = SIMPLE_LIGHT 265 = DIMMABLE_LIGHT
265 = DIMMABLE_LIGHT
266 = DIMMER_SWITCH
273 = SIMPLE_BUTTON
277 = COLOR_BULB
278 = DIMMABLE_COLOR_BULB
281 = BLIND
282 = LAMELLAR
512 = SIMPLE_DETECTOR
513 = DOOR_OPEN_CLOSE_DETECTOR
514 = WINDOW_OPEN_CLOSE_DETECTOR
515 = MOTION_DETECTOR
518 = FLOOD_DETECTOR
519 = GLAS_BREAK_DETECTOR
520 = VIBRATION_DETECTOR
640 = SIREN
*/
/* HANFUN interfaces
256 = ALERT
277 = KEEP_ALIVE
512 = ON_OFF
513 = LEVEL_CTRL
514 = COLOR_CTRL
516 = OPEN_CLOSE ? detected with blinds, different alert -> status bits?
517 = OPEN_CLOSE_CONFIG ? detected with blinds
768 = ?
772 = SIMPLE_BUTTON
1024 = SUOTA-Update
*/
/* modes of DECT500 supported/current_mode
0 = nothing, because OFF or not present
1 = HueSaturation-Mode
2 =
3 =
4 = Colortemperature-Mode
5 =
*/
const settings = {
Username: '',
Password: '',
Url: '',
options: {},
intervall: 300,
boosttime: 5,
windowtime: 5,
tsolldefault: 23,
exclude_templates: false,
exclude_routines: false
};
class Fritzdect extends utils.Adapter {
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
constructor(options) {
super({
...options,
name: 'fritzdect'
});
this.on('ready', this.onReady.bind(this));
this.on('stateChange', this.onStateChange.bind(this));
// this.on('objectChange', this.onObjectChange.bind(this));
this.on('message', this.onMessage.bind(this));
this.on('unload', this.onUnload.bind(this));
this.systemConfig = {};
this.fritz = null;
this.boosttime = 5;
this.windowtime = 5;
this.tsolldefault = 23;
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
// Initialize your adapter here
try {
// Load user settings
settings.Username = this.config.fritz_user;
settings.Password = this.config.fritz_pw;
settings.Url = this.config.fritz_ip;
//settings.options = this.config.fritz_options;
settings.intervall = this.config.fritz_interval;
settings.boosttime = this.boosttime = this.config.fritz_boosttime;
settings.windowtime = this.windowtime = this.config.fritz_windowtime;
settings.tsolldefault = this.tsolldefault = this.config.fritz_tsolldefault;
settings.fritz_writeonhyst = this.fritz_writeonhyst = this.config.fritz_writeonhyst;
settings.exclude_templates = this.exclude_templates = this.config.fritz_exclude_templates;
settings.exclude_routines = this.exclude_routines = this.config.fritz_exclude_routines;
settings.exclude_stats = this.exclude_stats = this.config.fritz_exclude_stats;
// The adapters config (in the instance object everything under the attribute "native") is accessible via
// this.config:
this.log.info('fritzdect entered ready');
const sysConf = await this.getForeignObjectAsync('system.config');
if (sysConf && sysConf.common) {
this.systemConfig = sysConf.common;
} else {
throw `ioBroker system configuration not found.`;
}
// jsonUI should transfer PW decrypted
if (settings.Username !== '' && settings.Password !== '') {
this.getForeignObject('system.config', async (err) => {
// Adapter is alive, make API call
// Make a call to fritzboxAPI and get a list devices/groups and templates
this.fritz = new Fritz(
settings.Username,
settings.Password,
settings.Url || '',
settings.options || {}
);
this.log.info('fritzdect uses USER: ' + settings.Username);
try {
const login = await this.fritz.login_SID().catch((e) => this.errorHandlerApi(e));
if (login) {
this.log.info('checking user permissions');
const resp = await this.fritz.check_SID().catch((e) => this.errorHandlerApi(e));
// wird zu try/catch error
if (resp) {
this.log.debug('raw perm =>' + JSON.stringify(resp));
try {
let rights = '';
if (resp.rights.indexOf('ights') == -1) {
rights = parser.xml2json(''.concat('<Rights>', resp.rights, '</Rights>'));
} else {
rights = parser.xml2json(resp.rights);
}
this.log.info('the rights are : ' + JSON.stringify(rights));
} catch (error) {
this.log.error('error in permission xml2json ' + error);
}
}
this.log.info('start creating global values ');
await this.createGlobal();
this.log.info('finished creating global values');
this.log.info('start creating devices/groups');
await this.createDevices(this.fritz).catch((e) => this.errorHandlerAdapter(e));
this.log.info('finished creating devices/groups (if any)');
const templinfo = settings.exclude_templates ? 'not used ' : 'used';
this.log.info('templates are ' + templinfo + '(' + settings.exclude_templates + ')');
if (!settings.exclude_templates) {
this.log.info('start creating templates ');
await this.createTemplates(this.fritz).catch((e) => this.errorHandlerAdapter(e));
this.log.info('finished creating templates (if any) ');
}
const routineinfo = settings.exclude_routines ? 'not used ' : 'used';
this.log.info('routines are ' + routineinfo + '(' + settings.exclude_routines + ')');
if (!settings.exclude_routines) {
this.log.info('start creating routines ');
await this.createRoutines(this.fritz).catch((e) => this.errorHandlerAdapter(e));
this.log.info('finished creating routines (if any) ');
}
this.log.info('start initial updating devices/groups');
await this.updateDevices(this.fritz).catch((e) => this.errorHandlerAdapter(e));
this.log.info('finished initial updating devices/groups');
this.log.info(
'going over to cyclic polling, messages to poll activity only in debug-mode '
);
if (!polling) {
polling = setInterval(async () => {
// poll fritzbox
try {
this.log.debug('polling! fritzdect is alive with ' + settings.intervall + ' s');
await this.updateDevices(this.fritz).catch((e) => this.errorHandlerAdapter(e));
if (!settings.exclude_routines) {
await this.updateRoutines(this.fritz).catch((e) =>
this.errorHandlerAdapter(e)
);
}
if (!settings.exclude_stats) {
const deviceswithstat = await this.getStateAsync(
'global.statdevices'
).catch((e) => {
this.log.warn('problem getting statdevices ' + e);
});
if (deviceswithstat && deviceswithstat.val) {
this.log.debug('glob state ' + deviceswithstat.val);
let devstat = [].concat([], JSON.parse(String(deviceswithstat.val)));
for (let i = 0; i < devstat.length; i++) {
this.log.debug('updating Stats of device ' + devstat[i]);
await this.updateStats(devstat[i], this.fritz);
}
}
}
} catch (e) {
this.log.warn(`[Polling] <== ${e}`);
}
}, (settings.intervall || 300) * 1000);
}
} else {
this.log.error('login not possible, check user and permissions');
}
} catch (error) {
//from login
this.log.warn(
'catched error in onReady (most likely no connection to FB or wrong credentials)' + error
);
}
if (err) {
this.log.error('error getting system.config ' + err);
}
});
} else {
this.log.error(
'*** Adapter running, but doing nothing, credentials missing in Adaptper Settings !!! ***'
);
}
// in this template all states changes inside the adapters namespace are subscribed
this.subscribeStates('*');
} catch (error) {
this.log.error('[asyncOnReady()]' + error);
return;
}
}
/**
* Is called when adapter shuts down - callback has to be called under any circumstances!
* @param {() => void} callback
*/
async onUnload(callback) {
try {
// Here you must clear all timeouts or intervals that may still be active
// clearTimeout(timeout1);
// clearTimeout(timeout2);
// ...
// clearInterval(interval1);
if (polling) clearInterval(polling);
// await this.fritz.logout_SID().catch((e) => this.errorHandlerApi(e));
this.log.info('cleaned everything up...');
callback();
} catch (e) {
this.log.error(e);
callback();
}
}
// If you need to react to object changes, uncomment the following block and the corresponding line in the constructor.
// You also need to subscribe to the objects with `this.subscribeObjects`, similar to `this.subscribeStates`.
// /**
// * Is called if a subscribed object changes
// * @param {string} id
// * @param {ioBroker.Object | null | undefined} obj
// */
// onObjectChange(id, obj) {
// if (obj) {
// // The object was changed
// this.log.info(`object ${id} changed: ${JSON.stringify(obj)}`);
// } else {
// // The object was deleted
// this.log.info(`object ${id} deleted`);
// }
// }
/**
* 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
this.log.debug(`onStateChange => state ${id} changed: ${state.val} (ack = ${state.ack})`);
if (!this.fritz) {
this.fritz = new Fritz(
settings.Username,
settings.Password,
settings.moreParam || '',
settings.strictSsl || true
);
try {
const login = await this.fritz.login_SID();
if (login) {
this.log.debug('login in stateChange success');
} else {
this.log.error('login not possible, check user and permissions');
}
} catch (error) {
this.errorHandlerApi(error);
}
}
//const fritz = new Fritz(settings.Username, settings.Password, settings.moreParam || '', settings.strictSsl || true);
// you can use the ack flag to detect if it is status (true) or command (false)
if (state && !state.ack && state.val !== null && id !== null) {
this.log.debug('ack is not set! -> command');
//hier noch eine Abfrage ob das Gerät present=false hat und Fehlermeldung das man Nichterreichbares Gerät bedienen wiil
const tmp = id.split('.');
const dp = tmp.pop();
const idx = tmp.pop(); //is the name after fritzdect.x.
// devices or groups
if (idx && idx !== null) {
if (idx.startsWith('DECT_')) {
// braucht man nicht wenn kein toggle in devices vorkommt
id = idx.replace(/DECT_/g, ''); //Thermostat
this.log.info('DECT ID: ' + id + ' identified for command (' + dp + ') : ' + state.val);
if (dp === 'tsoll') {
if (state.val < 8) {
//kann gelöscht werden, wenn Temperaturvorwahl nicht zur Moduswahl benutzt werden soll
await this.setStateAsync('DECT_' + id + '.hkrmode', { val: 1, ack: false }); //damit das Ventil auch regelt
await this.fritz
.setTempTarget(id, 'off')
.then(() => {
this.log.debug('Switched Mode' + id + ' to closed');
})
.catch((e) => this.errorHandlerApi(e));
} else if (state.val > 28) {
//kann gelöscht werden, wenn Temperaturvorwahl nicht zur Moduswahl benutzt werden soll
await this.setStateAsync('DECT_' + id + '.hkrmode', { val: 2, ack: false }); //damit das Ventil auch regelt (false= Befehl und nochmaliger Einsprung )
await this.fritz
.setTempTarget(id, 'on')
.then(() => {
this.log.debug('Switched Mode' + id + ' to opened permanently');
})
.catch((e) => this.errorHandlerApi(e));
} else {
await this.setStateAsync('DECT_' + id + '.hkrmode', { val: 0, ack: false }); //damit das Ventil auch regelt
await this.fritz
.setTempTarget(id, state.val)
.then(() => {
this.log.debug('Set target temp ' + id + state.val + ' °C');
this.setStateAsync('DECT_' + id + '.lasttarget', {
val: state.val,
ack: true
}); //iobroker Tempwahl wird zum letzten Wert gespeichert
this.setStateAsync('DECT_' + id + '.tsoll', {
val: state.val,
ack: true
}); //iobroker Tempwahl wird nochmal als Status geschrieben, da API-Aufruf erfolgreich
})
.catch((e) => this.errorHandlerApi(e));
}
} else if (dp === 'hkrmode') {
if (state.val === 0) {
const targettemp = await this.getStateAsync('DECT_' + id + '.tsoll').catch((e) => {
this.log.warn('problem getting the tsoll status ' + e);
});
// oder hier die Verwendung von lasttarget
if (targettemp && targettemp.val !== null) {
if (targettemp.val) {
let setTemp = targettemp.val;
if (setTemp < 8) {
await this.setStateAsync('DECT_' + id + '.tsoll', { val: 8, ack: true });
setTemp = 8;
} else if (setTemp > 28) {
await this.setStateAsync('DECT_' + id + '.tsoll', { val: 28, ack: true });
setTemp = 28;
}
await this.fritz
.setTempTarget(id, setTemp)
.then(() => {
this.log.debug('Set target temp ' + id + ' ' + setTemp + ' °C');
this.setStateAsync('DECT_' + id + '.tsoll', {
val: setTemp,
ack: true
}); //iobroker Tempwahl wird nochmal als Status geschrieben, da API-Aufruf erfolgreich
this.setStateAsync('DECT_' + id + '.operationmode', {
val: 'Auto',
ack: true
}); //iobroker setzen des operationmode, da API Aufruf erfolgreich
})
.catch((e) => this.errorHandlerApi(e));
} else {
this.log.error('no data in targettemp for setting mode');
}
} else {
throw { error: ' targettemp is NULL ' };
}
} else if (state.val === 1) {
await this.fritz
.setTempTarget(id, 'off')
.then(() => {
this.log.debug('Switched Mode' + id + ' to closed.');
this.setStateAsync('DECT_' + id + '.operationmode', {
val: 'Off',
ack: true
}); //iobroker setzen des operationmode, da API Aufruf erfolgreich
})
.catch((e) => this.errorHandlerApi(e));
} else if (state.val === 2) {
await this.fritz
.setTempTarget(id, 'on')
.then(() => {
this.log.debug('Switched Mode' + id + ' to opened permanently');
this.setStateAsync('DECT_' + id + '.operationmode', {
val: 'On',
ack: true
}); //iobroker setzen des operationmode, da API Aufruf erfolgreich
})
.catch((e) => this.errorHandlerApi(e));
}
}
//no need to check the state.val, it is a button
if (dp === 'setmodeauto') {
//zurücksetzen wegen toggle/button click
await this.setStateAsync('DECT_' + id + '.setmodeauto', {
val: false,
ack: true
});
const targettemp = await this.getStateAsync('DECT_' + id + '.tsoll').catch((e) => {
this.log.warn('problem getting the tsoll status ' + e);
});
// oder hier die Verwendung von lasttarget
if (targettemp && targettemp.val !== null) {
if (targettemp.val) {
let setTemp = targettemp.val;
if (setTemp < 8) {
await this.setStateAsync('DECT_' + id + '.tsoll', { val: 8, ack: true });
setTemp = 8;
} else if (setTemp > 28) {
await this.setStateAsync('DECT_' + id + '.tsoll', { val: 28, ack: true });
setTemp = 28;
}
this.fritz
.setTempTarget(id, setTemp)
.then(() => {
this.log.debug('Set target temp ' + id + ' ' + setTemp + ' °C');
this.setStateAsync('DECT_' + id + '.tsoll', {
val: setTemp,
ack: true
}); //iobroker Tempwahl wird nochmal als Status geschrieben, da API-Aufruf erfolgreich
this.setStateAsync('DECT_' + id + '.operationmode', {
val: 'Auto',
ack: true
}); //iobroker setzen des operationmode, da API Aufruf erfolgreich
this.setStateAsync('DECT_' + id + '.hkrmode', {
val: 0,
ack: true
}); //iobroker setzen des hkrmode, da API Aufruf erfolgreich
})
.catch((e) => this.errorHandlerApi(e));
} else {
this.log.error('no data in targettemp for setting mode');
}
} else {
throw { error: ' targettemp is NULL ' };
}
}
if (dp === 'setmodeoff') {
//zurücksetzen wegen toggle/button click
await this.setStateAsync('DECT_' + id + '.setmodeoff', {
val: false,
ack: true
});
await this.fritz
.setTempTarget(id, 'off')
.then(() => {
this.log.debug('Switched Mode' + id + ' to closed.');
this.setStateAsync('DECT_' + id + '.operationmode', {
val: 'Off',
ack: true
}); //iobroker setzen des operationmode, da API Aufruf erfolgreich
this.setStateAsync('DECT_' + id + '.hkrmode', {
val: 1,
ack: true
}); //iobroker setzen des hkrmode, da API Aufruf erfolgreich
})
.catch((e) => this.errorHandlerApi(e));
}
if (dp === 'setmodeon') {
//zurücksetzen wegen toggle/button click
await this.setStateAsync('DECT_' + id + '.setmodeon', {
val: false,
ack: true
});
await this.fritz
.setTempTarget(id, 'on')
.then(() => {
this.log.debug('Switched Mode' + id + ' to opened permanently');
this.setStateAsync('DECT_' + id + '.operationmode', {
val: 'On',
ack: true
}); //iobroker setzen des operationmode, da API Aufruf erfolgreich
this.setStateAsync('DECT_' + id + '.hkrmode', {
val: 2,
ack: true
}); //iobroker setzen des hkrmode, da API Aufruf erfolgreich
})
.catch((e) => this.errorHandlerApi(e));
}
if (dp == 'boostactivetime') {
this.log.debug(
'Nothing to send external, but the boost active time was defined for ' +
state.val +
' min'
);
}
if (dp == 'boostactive') {
if (
state.val === 0 ||
state.val === '0' ||
state.val === 'false' ||
state.val === false ||
state.val === 'off' ||
state.val === 'OFF'
) {
this.fritz
.setHkrBoost(id, 0)
.then(() => {
this.log.debug('Reset thermostat boost ' + id + ' to ' + state.val);
this.setStateAsync('DECT_' + id + '.boostactive', {
val: state.val,
ack: true
}); //iobroker State-Bedienung wird nochmal als Status geschrieben, da API-Aufruf erfolgreich
//kein pauschales Setzen des Operationmode, da unbekannt wohin es dann geht
const convTime = new Date(0);
this.setStateAsync('DECT_' + id + '.boostactiveendtime', {
val: String(convTime),
ack: true
});
})
.catch((e) => this.errorHandlerApi(e));
} else if (
state.val === 1 ||
state.val === '1' ||
state.val === 'true' ||
state.val === true ||
state.val === 'on' ||
state.val === 'ON'
) {
const minutes = await this.getStateAsync(
'DECT_' + id + '.boostactivetime'
).catch((error) => {
this.log.warn('DECT_' + +id + '.boostactivetime did not get state -> ' + error);
});
if (minutes && minutes.val !== null) {
let activetime = minutes.val;
const jetzt = +new Date();
if (minutes.val > 1440) {
activetime = 1440;
}
const ende = Math.floor(jetzt / 1000 + Number(activetime) * 60); //time for fritzbox is in seconds
this.log.debug(' unix returned ' + ende + ' real ' + new Date(ende * 1000));
this.fritz
.setHkrBoost(id, ende)
.then((body) => {
const endtime = new Date(Math.floor(body * 1000));
this.log.debug('window ' + body + ' reading to ' + endtime);
this.log.debug(
'Set thermostat boost ' +
id +
' to ' +
state.val +
' until calculated ' +
ende +
' ' +
new Date(ende * 1000)
);
this.setStateAsync('DECT_' + id + '.boostactive', {
val: state.val,
ack: true
}); //iobroker State-Bedienung wird nochmal als Status geschrieben, da API-Aufruf erfolgreich
this.setStateAsync('DECT_' + id + '.boostactiveendtime', {
val: String(endtime),
ack: true
}); //iobroker State-Bedienung wird nochmal als Status geschrieben, da API-Aufruf erfolgreich
this.setStateAsync('DECT_' + id + '.operationmode', {
val: 'Boost',
ack: true
}); //iobroker setzen des operationmode, da API Aufruf erfolgreich
})
.catch((e) => this.errorHandlerApi(e));
} else {
throw { error: 'minutes were NULL' };
}
}
}
if (dp == 'windowopenactivetime') {
this.log.debug(
'Nothing to send external, but the window open active time was defined for ' +
state.val +
' min'
);
}
if (dp == 'windowopenactiv') {
if (
state.val === 0 ||
state.val === '0' ||
state.val === 'false' ||
state.val === false ||
state.val === 'off' ||
state.val === 'OFF'
) {
this.fritz
.setWindowOpen(id, 0)
.then(() => {
this.log.debug('Reset thermostat windowopen ' + id + ' to ' + state.val);
this.setStateAsync('DECT_' + id + '.windowopenactiv', {
val: state.val,
ack: true
}); //iobroker State-Bedienung wird nochmal als Status geschrieben, da API-Aufruf erfolgreich
//keine Nachführung operationmode, da unbekannt wohin es geht
const convTime = new Date(0);
this.setStateAsync('DECT_' + id + '.windowopenactiveendtime', {
val: String(convTime),
ack: true
});
})
.catch((e) => this.errorHandlerApi(e));
} else if (
state.val === 1 ||
state.val === '1' ||
state.val === 'true' ||
state.val === true ||
state.val === 'on' ||
state.val === 'ON'
) {
const minutes = await this.getStateAsync(
'DECT_' + id + '.windowopenactivetime'
).catch((error) => {
this.log.warn(
'DECT_' + +id + '.windowopenactivetime did not get state -> ' + error
);
});
if (minutes && minutes.val !== null) {
let activetime = minutes.val;
const jetzt = +new Date();
if (minutes.val > 1440) {
activetime = 1440;
}
const ende = Math.floor(jetzt / 1000 + Number(activetime) * 60); //time for fritzbox is in seconds
this.log.debug(' unix ' + ende + ' real ' + new Date(ende * 1000));
this.fritz
.setWindowOpen(id, ende)
.then((body) => {
const endtime = new Date(Math.floor(body * 1000));
this.log.debug('window ' + body + ' reading to ' + endtime);
this.log.debug(
'Set thermostat windowopen ' +
id +
' to ' +
state.val +
' until calculated ' +
ende +
' ' +
new Date(ende * 1000)
);
this.setStateAsync('DECT_' + id + '.windowopenactiv', {
val: state.val,
ack: true
}); //iobroker State-Bedienung wird nochmal als Status geschrieben, da API-Aufruf erfolgreich
this.setStateAsync('DECT_' + id + '.windowopenactiveendtime', {
val: String(endtime),
ack: true
}); //iobroker State-Bedienung wird nochmal als Status geschrieben, da API-Aufruf erfolgreich
this.setStateAsync('DECT_' + id + '.operationmode', {
val: 'WindowOpen',
ack: true
}); //iobroker setzen des operationmode, da API Aufruf erfolgreich
})
.catch((e) => this.errorHandlerApi(e));
} else {
throw { error: 'minutes were NULL' };
}
}
}
// setswitch reicht scheinbar nicht bei simpleonoff, hier müsste irgendwie unterschieden werden ob DECT200 switch/state oder simpleonoff/state
if (dp == 'state') {
if (
state.val === 0 ||
state.val === '0' ||
state.val === 'false' ||
state.val === false ||
state.val === 'off' ||
state.val === 'OFF'
) {
const switchtyp = await this.getStateAsync(
'DECT_' + id + '.switchtype'
).catch((error) => {
this.log.warn('DECT_' + +id + '.switchtype did not get state -> ' + error);
});
if (switchtyp && switchtyp.val !== null) {
if (switchtyp.val === 'switch') {
this.fritz
.setSwitchOff(id)
.then(() => {
this.log.debug('Turned switch ' + id + ' off');
this.setStateAsync('DECT_' + id + '.state', {
val: false,
ack: true
}); //iobroker State-Bedienung wird nochmal als Status geschrieben, da API-Aufruf erfolgreich
})
.catch((e) => this.errorHandlerApi(e));
} else {
this.fritz
.setSimpleOff(id)
.then(() => {
this.log.debug('Turned switch ' + id + ' off');
this.setStateAsync('DECT_' + id + '.state', {
val: false,
ack: true
}); //iobroker State-Bedienung wird nochmal als Status geschrieben, da API-Aufruf erfolgreich
})
.catch((e) => this.errorHandlerApi(e));
}
} else {
throw { error: 'could not determine the type of switch (switch/simpleonoff)' };
}
} else if (
state.val === 1 ||
state.val === '1' ||
state.val === 'true' ||
state.val === true ||
state.val === 'on' ||
state.val === 'ON'
) {
const switchtyp = await this.getStateAsync(
'DECT_' + id + '.switchtype'
).catch((error) => {
this.log.warn('DECT_' + +id + '.switchtype did not get state -> ' + error);
});
if (switchtyp && switchtyp.val !== null) {
if (switchtyp.val === 'switch') {
this.fritz
.setSwitchOn(id)
.then(() => {
this.log.debug('Turned switch ' + id + ' on');
this.setStateAsync('DECT_' + id + '.state', {
val: true,
ack: true
}); //iobroker State-Bedienung wird nochmal als Status geschrieben, da API-Aufruf erfolgreich
})
.catch((e) => this.errorHandlerApi(e));
} else {
this.fritz
.setSimpleOn(id)
.then(() => {
this.log.debug('Turned switch ' + id + ' on');
this.setStateAsync('DECT_' + id + '.state', {
val: true,
ack: true
}); //iobroker State-Bedienung wird nochmal als Status geschrieben, da API-Aufruf erfolgreich
})
.catch((e) => this.errorHandlerApi(e));
}
} else {
throw { error: 'could not determine the type of switch (switch/simpleonoff)' };
}
}
}
if (dp == 'blindsclose') {
this.fritz
.setBlind(id, 'close')
.then(async () => {
this.log.debug('Started blind ' + id + ' to close');
await this.setStateAsync('DECT_' + id + '.blindsclose', { val: false, ack: true }); //iobroker State-Bedienung wird nochmal als Status geschrieben, da API-Aufruf erfolgreich
})
.catch((e) => this.errorHandlerApi(e));
}
if (dp == 'blindsopen') {
this.fritz
.setBlind(id, 'open')
.then(async () => {
this.log.debug('Started blind ' + id + ' to open');
await this.setStateAsync('DECT_' + id + '.blindsopen', { val: false, ack: true }); //iobroker State-Bedienung wird nochmal als Status geschrieben, da API-Aufruf erfolgreich
})
.catch((e) => this.errorHandlerApi(e));
}
if (dp == 'blindsstop') {
this.fritz
.setBlind(id, 'stop')
.then(() => {
this.log.debug('Set blind ' + id + ' to stop');
this.setStateAsync('DECT_' + id + '.blindsstop', { val: false, ack: true }); //iobroker State-Bedienung wird nochmal als Status geschrieben, da API-Aufruf erfolgreich
})
.catch((e) => this.errorHandlerApi(e));
}
if (dp == 'level') {
this.fritz
.setLevel(id, state.val)
.then(() => {
this.log.debug('Set level' + id + ' to ' + state.val);
this.setStateAsync('DECT_' + id + '.level', { val: state.val, ack: true }); //iobroker State-Bedienung wird nochmal als Status geschrieben, da API-Aufruf erfolgreich
})
.catch((e) => this.errorHandlerApi(e));
}
if (dp == 'levelpercentage') {
this.fritz
.setLevel(id, Math.floor(Number(state.val) / 100 * 255))
.then(() => {
//level is in 0...255
this.log.debug('Set level %' + id + ' to ' + state.val);
this.setStateAsync('DECT_' + id + '.levelpercentage', {
val: state.val,
ack: true
}); //iobroker State-Bedienung wird nochmal als Status geschrieben, da API-Aufruf erfolgreich
})
.catch((e) => this.errorHandlerApi(e));
}
if (dp == 'hue') {
const saturation = await this.getStateAsync('DECT_' + id + '.saturation').catch((error) => {
this.log.warn('DECT_' + +id + '.saturation did not get state -> ' + error);
});
if (saturation && saturation.val !== null) {
// oder hier die Verwendung von lasttarget
const setSaturation = saturation.val;
if (setSaturation == '') {
this.log.error(
'No saturation value exists when setting hue, please set saturation to a value '
);
} else {
this.fritz
.setColor(id, setSaturation, state.val)
.then(() => {
this.log.debug(
'Set lamp color hue ' +
id +
' to ' +
state.val +
' and saturation of ' +
setSaturation
);
this.setStateAsync('DECT_' + id + '.hue', {
val: state.val,
ack: true
}); //iobroker State-Bedienung wird nochmal als Status geschrieben, da API-Aufruf erfolgreich
})
.catch((e) => this.errorHandlerApi(e));
}
} else {
throw { error: 'minutes were NULL' };
}
}
if (dp == 'saturation') {
const hue = await this.getStateAsync('DECT_' + id + '.hue').catch((error) => {
this.log.warn('DECT_' + +id + '.hue did not get state -> ' + error);
});
if (hue && hue.val !== null) {
const setHue = hue.val;
if (setHue == '') {
this.log.error(
'No hue value exists when setting saturation, please set hue to a value '
);
} else {
this.fritz
.setColor(id, state.val, setHue)
.then(() => {
this.log.debug(
'Set lamp color saturation ' +
id +
' to ' +
state.val +
' and hue of ' +
setHue
);
this.setStateAsync('DECT_' + id + '.saturation', {
val: state.val,
ack: true
}); //iobroker State-Bedienung wird nochmal als Status geschrieben, da API-Aufruf erfolgreich
})
.catch((e) => this.errorHandlerApi(e));
}
} else {
throw { error: 'hue were NULL' };
}
}
if (dp == 'temperature') {
this.fritz
.setColorTemperature(id, state.val)
.then(() => {
this.log.debug('Set lamp color temperature ' + id + ' to ' + state.val);
this.setStateAsync('DECT_' + id + '.temperature', {
val: state.val,
ack: true
}); //iobroker State-Bedienung wird nochmal als Status geschrieben, da API-Aufruf erfolgreich
})
.catch((e) => this.errorHandlerApi(e));
}
} else if (idx.startsWith('template_')) {
//must be fritzbox template
id = idx.replace(/template_/g, ''); //template
this.log.info('Template ID: ' + id + ' identified for command (' + dp + ') : ' + state.val);
if (dp == 'toggle') {
if (
state.val === 1 ||
state.val === '1' ||
state.val === 'true' ||
state.val === true ||
state.val === 'on' ||
state.val === 'ON'
) {
this.fritz
.applyTemplate(id)
.then((sid) => {
this.log.debug('cmd Toggle to template ' + id + ' on');
this.log.debug('response ' + sid);
this.setStateAsync('template.lasttemplate', { val: sid, ack: true }); //when successfull toggle, the API returns the id of the template
})
.catch((e) => this.errorHandlerApi(e));
}
}
} else if (idx.startsWith('routine_')) {
//must be fritzbox routine
id = idx.replace(/routine_/g, ''); //routine
this.log.info('Routine ID: ' + id + ' identified for command (' + dp + ') : ' + state.val);
if (dp == 'active') {
if (
state.val === 1 ||
state.val === '1' ||
state.val === 'true' ||
state.val === true ||
state.val === 'on' ||
state.val === 'ON'
) {
state.val = true;
}
this.fritz
.setTriggerActive(id, state.val)
.then((sid) => {
this.log.debug('cmd Active to template ' + id + ' to ' + state.val);
this.log.debug('response ' + sid);
})
.catch((e) => this.errorHandlerApi(e));
}
}
}
} //from if state&ack
} else {
// The state was deleted
this.log.info(`state ${id} deleted`);
}
}
// If you need to accept messages in your adapter, uncomment the following block and the corresponding line in the constructor.
// /**
// * Some message was sent to this instance over message box. Used by email, pushover, text2speech, ...