-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathmain.js
2098 lines (1729 loc) · 94.7 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.12.1
*/
// The adapter-core module gives you access to the core ioBroker functions
// you need to create an adapter
const utils = require("@iobroker/adapter-core");
const mathjs = require("mathjs");
const fs = require('fs');
const moment = require("moment");
const momentDurationFormatSetup = require("moment-duration-format");
momentDurationFormatSetup(moment);
// Default values, falls system config nicht geladen werden kann
var mySystemConfig = { language: "en", dateFormat: "DD.MM.YYYY", durationFormat: "dd[T] hh[h] mm[m]" };
// Load your modules here, e.g.:
// const fs = require("fs");
class Linkeddevices extends utils.Adapter {
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
constructor(options) {
super({
...options,
name: "linkeddevices",
});
this.on("ready", this.onReady.bind(this));
this.on("objectChange", this.onObjectChange.bind(this));
this.on("stateChange", this.onStateChange.bind(this));
// this.on("message", this.onMessage.bind(this));
this.on("unload", this.onUnload.bind(this));
this.on("message", this.onMessage.bind(this))
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
this.log.debug("[onReady] deleteDeadLinkedObjects: '" + this.config.deleteDeadLinkedObjects + "'");
// Initialize your adapter here
await this.initialObjects()
// subscribe für alle Objekt, um Änderungen die diesen Adapter betreffen mitzubekommen
this.subscribeForeignObjects("*");
// The adapters config (in the instance object everything under the attribute "native") is accessible via
// this.config:
// this.log.info("config option1: " + this.config.option1);
// this.log.info("config option2: " + this.config.option2);
/*
For every state in the system there has to be also an object of type state
Here a simple template for a boolean variable named "testVariable"
Because every adapter instance uses its own unique namespace variable names can't collide with other adapters variables
*/
// await this.setObjectAsync("testVariable", {
// type: "state",
// common: {
// name: "testVariable",
// type: "boolean",
// role: "indicator",
// read: true,
// write: true,
// },
// native: {},
// });
/*
setState examples
you will notice that each setState will cause the stateChange event to fire (because of above subscribeStates cmd)
*/
// the variable testVariable is set to true as command (ack=false)
// await this.setStateAsync("testVariable", true);
// same thing, but the value is flagged "ack"
// ack should be always set to true if the value is received from or acknowledged from the target system
// await this.setStateAsync("testVariable", { val: true, ack: true });
// same thing, but the state is deleted after 30s (getState will return null afterwards)
// await this.setStateAsync("testVariable", { val: true, ack: true, expire: 30 });
// examples for the checkPassword/checkGroup functions
// let result = await this.checkPasswordAsync("admin", "iobroker");
// this.log.info("check user admin pw ioboker: " + result);
// result = await this.checkGroupAsync("admin", "admin");
// this.log.info("check group user admin group admin: " + result);
}
/**
* Is called when adapter shuts down - callback has to be called under any circumstances!
* @param {() => void} callback
*/
onUnload(callback) {
try {
this.log.info("cleaned everything up...");
callback();
} catch (e) {
callback();
}
}
/**
* Is called if a subscribed object changes
* @param {string} id
* @param {ioBroker.Object | null | undefined} obj
*/
async onObjectChange(id, obj) {
if (obj) {
if (!id.startsWith(this.namespace) && obj.common && obj.common.custom && obj.common.custom[this.namespace]) {
if (this.dicLinkedParentObjects && id in this.dicLinkedParentObjects) {
//bereits verlinktes parentObject wurde geändert -> ist im dicLinkedParentObjects enthalten
let linkedId = this.getLinkedObjectId(obj);
// Prüfen ob die linkedId schon verwendet wird, bzw. ob es die gleiche ist oder wenn 'isLinked === false' ist
if (!this.isLinkedIdInUse(obj, linkedId)) {
// nicht verwendet
if (this.dicLinkedParentObjects[id] === linkedId) {
// linkedId wurde für parentObject nicht geändert -> Eingaben wurden nur aktualisiert
this.log.info("[onObjectChange] parentObject '" + id + "' properties changed");
await this.createLinkedObject(obj);
} else {
// alte linkedId aus dic holen
let oldLinkedId = this.dicLinkedParentObjects[id];
let oldLinkedObj = await this.getForeignObjectAsync(oldLinkedId);
// linkedId wurde für parentObject geändert -> neue linkedId für parentObject in dic schreiben
this.dicLinkedParentObjects[id] = linkedId;
this.log.info("[onObjectChange] linkedId '" + oldLinkedId + "' changed to '" + linkedId + "' for parentObject '" + id + "'");
// linkedObject "custom.isLinked = false" Status setzen
await this.resetLinkedObjectStatusById(oldLinkedId);
// linkedObject löschen -> abhängig von Config
await this.removeNotLinkedObject(oldLinkedId);
// LinkedObject erzeugen, oldLinkeObject mit übergeben, damit custom settings von anderen adaptern mit verschoben werden
// @ts-ignore
await this.createLinkedObject(obj, oldLinkedObj);
}
} else {
// wird bereits verwendet -> 'custom.linkedId' vom parentObject auf alte linkedId zurücksetzen
let oldLinkedId = this.dicLinkedParentObjects[id];
this.log.info("[onObjectChange] reset linkedId to '" + oldLinkedId + "' for parentObject '" + id + "'");
// namespace aus oldLinkedId entfernen
oldLinkedId = oldLinkedId.replace(this.namespace + ".", "");
// alte linkedId in parentObject schreiben
obj.common.custom[this.namespace].linkedId = oldLinkedId;
await this.setForeignObjectAsync(id, obj);
}
this.storeInfoStates();
} else {
// neues parentObject hinzugefügt bzw. aktiviert ('enabled==true') -> nicht im dicLinkedParentObjects enthalten
let linkedId = this.getLinkedObjectId(obj);
this.log.info("[onObjectChange] new parentObject '" + id + "' linked to '" + linkedId + "'");
// Prüfen ob die linkedId schon verwendet wird
if (!this.isLinkedIdInUse(obj, linkedId)) {
// nicht verwendet
await this.createLinkedObject(obj);
} else {
// wird bereits verwendet -> 'parentObj.common.custom[linkeddevices.x]' löschen
if (obj.common.custom[this.namespace].enabled === true) {
delete obj.common.custom[this.namespace];
await this.setForeignObjectAsync(obj._id, obj);
this.logDicLinkedObjectsStatus();
this.logDicLinkedParentObjects();
}
}
this.storeInfoStates();
}
if (this.dicLinkedParentObjects) {
this.log.info("[onObjectChange] count of active linkedObjects: " + Object.keys(this.dicLinkedParentObjects).length)
}
} else {
// bereits verlinktes parentObject wurde deaktiviert
if (!id.startsWith(this.namespace) && this.dicLinkedParentObjects && id in this.dicLinkedParentObjects) {
this.log.info("[onObjectChange] parentObject '" + id + "' deactivated");
// alte linkedId holen und aus dicLinkedObjectsStatus löschen
let oldLinkedId = this.dicLinkedParentObjects[id];
if (this.dicLinkedObjectsStatus) this.dicLinkedObjectsStatus[oldLinkedId] = false;
// parentObject aus dicLinkedParentObjects löschen
delete this.dicLinkedParentObjects[id];
this.logDicLinkedParentObjects();
// linkedObject "custom.isLinked = false" Status setzen
await this.resetLinkedObjectStatusById(oldLinkedId);
// linkedObject löschen -> abhängig von Config
await this.removeNotLinkedObject(oldLinkedId);
if (this.dicLinkedParentObjects) {
this.log.info("[onObjectChange] count of active linkedObjects: " + Object.keys(this.dicLinkedParentObjects).length)
}
this.storeInfoStates();
}
//INFO: bereits verlinktes parentObject wurde gelöscht -> wird nicht über objectChange erkannt
}
} else {
// Objekt wurde gelöscht
if (this.dicLinkedParentObjects && id in this.dicLinkedParentObjects) {
let linkedId = this.dicLinkedParentObjects[id];
let linkedObject = await this.getForeignObjectAsync(linkedId);
if (linkedObject && linkedObject.common && linkedObject.common.custom && linkedObject.common.custom[this.namespace] && linkedObject.common.custom[this.namespace].isLinked) {
linkedObject.common.custom[this.namespace].isLinked = false;
linkedObject.common.icon = 'linkeddevices_missing.png';
this.setForeignObject(linkedId, linkedObject);
this.log.info(`parentObject '${id}' deleted, linkedObject '${linkedId}' status 'isLinked' set to '${linkedObject.common.custom[this.namespace].isLinked}'`);
delete this.dicLinkedParentObjects[id];
this.logDicLinkedParentObjects();
this.storeInfoStates();
}
}
}
// 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`);
// this.log.info(JSON.stringify(obj));
// }
}
/**
* Is called if a subscribed state changes
* @param {string} id
* @param {ioBroker.State | null | undefined} state
*/
async onStateChange(id, state) {
try {
// 'state' hat sich geändert -> darauf wird nur reagiert wenn nicht der Adapter selbst auslöser ist
if (state && state.from != `system.adapter.${this.namespace}`) {
let changedValue = state.val;
// parentObject 'state' hat sich geändert -> linkedObject 'state' ändern
if (this.dicLinkedParentObjects && id in this.dicLinkedParentObjects) {
let linkedObjId = this.dicLinkedParentObjects[id];
// ggf. kann für das linkedObject eine Umrechnung festgelegt sein
changedValue = await this.getConvertedValue(linkedObjId, changedValue);
await this.logStateChange(id, state, linkedObjId, "parentObject", changedValue);
await this.setForeignStateAsync(linkedObjId, { val: changedValue, ack: state.ack });
}
// linkedObject 'state' hat sich geändert -> parentObject 'state' ändern
else if (this.dicLinkedObjectsStatus && id in this.dicLinkedObjectsStatus) {
// @ts-ignore
let parentObjId = Object.keys(this.dicLinkedParentObjects).find(key => this.dicLinkedParentObjects[key] === id);
// Wenn 'custom.isLinked = true', dann auf Änderung reagieren, da Verlinkung existiert
if (this.dicLinkedObjectsStatus[id] === true && parentObjId) {
// ggf. kann für das linkedObject eine Umrechnung festgelegt sein -> parentObject zurück rechnen
changedValue = await this.getConvertedValue(parentObjId, changedValue, true);
await this.logStateChange(id, state, parentObjId, "linkedObject", changedValue);
await this.setForeignStateAsync(parentObjId, { val: changedValue, ack: state.ack });
}
}
}
} catch (err) {
this.log.error(`[onStateChange] changedId '${id}', error: ${err.message}, stack: ${err.stack}`);
}
}
/**
* Some message was sent to this instance over message box. Used by email, pushover, text2speech, ...
* Using this method requires "common.message" property to be set to true in io-package.json
* @param {ioBroker.Message} obj
*/
async onMessage(obj) {
this.log.debug(`message received: ${JSON.stringify(obj)}`);
if (typeof obj === 'object') {
if (obj.command === 'assignTo' && obj.message) {
// @ts-ignore
if (obj.message.linkedId && obj.message.parentId) {
// @ts-ignore
let result = await this.assignToParentObject(obj.message.linkedId, obj.message.parentId);
// Send response in callback if required
if (obj.callback && result) {
this.sendTo(obj.from, obj.command, result, obj.callback);
}
} else {
this.log.error("missing linkedId and parentId in message of sendTo command!")
}
} else if (obj.command === 'autoRepair') {
let result = await this.autoRepair();
// Send response in callback if required
if (obj.callback && result) {
this.sendTo(obj.from, obj.command, result, obj.callback);
}
} else if (obj.command === 'suggestions_prefixId') {
// message from custom dialog
let objOfInstance = await this.getForeignObjectsAsync(`${this.namespace}.*`);
let prefixIdSuggestionList = [];
for (var id in objOfInstance) {
let linkedObject = objOfInstance[id];
if (linkedObject && linkedObject.common && linkedObject.common.custom && linkedObject.common.custom[this.namespace]) {
// nur Objekte betrachten die custom vom Namespace haben -> es kann sein das andere Objekte existieren
let cleanId = id.replace(`${this.namespace}.`, '');
// alle prefixIds von rechts immer bis zum '.' durchlaufen und übergeben
let prefixId = cleanId;
for (var i = 0; i <= cleanId.split(".").length - 1; i++) {
prefixId = prefixId.substring(0, prefixId.lastIndexOf('.'))
if (prefixId) {
if (!prefixIdSuggestionList.includes(prefixId)) {
// nur zu prefixId array hinzufügen wenn noch nicht vorhanden
prefixIdSuggestionList.push(prefixId);
}
}
}
}
}
prefixIdSuggestionList.sort(function (a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
})
this.sendTo(obj.from, obj.command, prefixIdSuggestionList, obj.callback);
} else if (obj.command === 'suggestions_stateId') {
// message from custom dialog
let objOfInstance = await this.getForeignObjectsAsync(`${this.namespace}.*`);
let stateIdSuggestionList = [];
for (var id in objOfInstance) {
let linkedObject = objOfInstance[id];
if (linkedObject && linkedObject.common && linkedObject.common.custom && linkedObject.common.custom[this.namespace]) {
// nur Objekte betrachten die custom vom Namespace haben -> es kann sein das andere Objekte existieren
let cleanId = id.replace(`${this.namespace}.`, '');
let stateId = cleanId.substring(cleanId.lastIndexOf('.'), cleanId.length).replace('.', '');
if (!stateIdSuggestionList.includes(stateId)) {
// nur zu prefixId array hinzufügen wenn noch nicht vorhanden
stateIdSuggestionList.push(stateId);
}
}
}
stateIdSuggestionList.sort(function (a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
})
this.sendTo(obj.from, obj.command, stateIdSuggestionList, obj.callback);
} else if (obj.command === 'suggestions_name') {
// message from custom dialog
let objOfInstance = await this.getForeignObjectsAsync(`${this.namespace}.*`);
let nameSugestionList = [];
for (var id in objOfInstance) {
let linkedObject = objOfInstance[id];
if (linkedObject && linkedObject.common && linkedObject.common.custom && linkedObject.common.custom[this.namespace]) {
if (linkedObject.common.name) {
let name = linkedObject.common.name;
if (typeof (name) === 'object') {
var sysConfig = await this.getForeignObjectAsync('system.config');
if (sysConfig && sysConfig.common) {
if (sysConfig.common.language) {
name = name[sysConfig.common.language];
} else {
name = name && name['en'] ? name['en'] : '';
}
}
}
if (!nameSugestionList.includes(name)) {
// nur zu prefixId array hinzufügen wenn noch nicht vorhanden
nameSugestionList.push(name);
}
}
}
}
nameSugestionList.sort(function (a, b) {
return a.toLowerCase().localeCompare(b.toLowerCase());
})
this.sendTo(obj.from, obj.command, nameSugestionList, obj.callback);
} else if (obj.command === 'getParentName') {
// message from custom dialog
if (obj.message && obj.message['parentId']) {
let parentObj = await this.getForeignObjectAsync(obj.message['parentId']);
if (parentObj && parentObj.common && parentObj.common.name) {
this.sendTo(obj.from, obj.command, parentObj.common.name, obj.callback);
} else {
this.sendTo(obj.from, obj.command, "Error", obj.callback);
}
} else {
this.sendTo(obj.from, obj.command, "Error", obj.callback);
}
}
}
}
async autoRepair() {
this.log.info(`[autoRepair] start auto repair...`);
let error = false;
try {
let linkedObjList = await this.getAdapterObjectsAsync();
for (let linkedId in linkedObjList) {
let linkedObj = linkedObjList[linkedId];
// alle nicht mehr verlinkten objekte suchen
if (linkedObj && linkedObj.common && linkedObj.common.custom && linkedObj.common.custom[this.namespace] && linkedObj.common.custom[this.namespace].isLinked === false) {
if (linkedObj.common.custom[this.namespace].parentId) {
let parentId = linkedObj.common.custom[this.namespace].parentId;
// prüfen ob parentObjekt noch existiert
let parentObject = await this.getForeignObjectAsync(parentId);
if (parentObject) {
// parentObjekt existiert noch -> reparieren
this.log.debug(`[autoRepair] parentObject '${parentId}' of linkedObject '${linkedId} still exist -> try to repair the link'`);
let result = await this.assignToParentObject(linkedId, parentId);
if (result) {
if (result.success === true) {
this.log.info(`[autoRepair] link repaired for linkedObject '${linkedId} (parentObject '${parentId}')`);
} else {
this.log.error(`[autoRepair] link not repaired for linkedObject '${linkedId} (parentObject '${parentId}') -> error: ${result.error}`);
error = true;
}
}
} else {
// parentObjekt existiert nicht mehr
this.log.debug(`[autoRepair] parentObject '${parentId}' of linkedObject '${linkedId} not exist anymore'`);
}
} else {
// linkedObjekt hat keine parentId
this.log.warn(`[autoRepair] linkedObject '${linkedId} has no parentId!'`)
}
}
}
this.log.info(`[autoRepair] auto repair finished`);
return { success: true, error: error };
} catch (err) {
this.log.error(`[autoRepair] error: ${err.message}`);
this.log.error("[autoRepair] stack: " + err.stack);
return { success: true, error: err.message };
}
}
/**
* @param {string} linkedId
* @param {string} parentId
*/
async assignToParentObject(linkedId, parentId) {
this.log.debug(`[assignToParentObject] start linkedObject '${linkedId}' assigning to parentObject '${parentId}'`);
// notwendige custom daten an neu zugeordnete parentObjekte übergeben
try {
let linkedObject = await this.getForeignObjectAsync(linkedId);
let parentObject = await this.getForeignObjectAsync(parentId);
if (linkedObject && linkedObject.common && linkedObject.common.custom && linkedObject.common.custom[this.namespace]) {
if (parentObject && parentObject.common) {
// common Daten des linkedObjects holen, die beim parentObject in den Settings konfiguriert werden können
let customForParentObj = {};
let expertSettings = false;
if (linkedObject.common.name) {
if (parentObject.common.name) {
if (parentObject.common.name != linkedObject.common.name) {
// nur übergeben wenn unterschiedlich zwischen linkedObject & parentObject ist
customForParentObj["name"] = linkedObject.common.name;
}
} else {
customForParentObj["name"] = linkedObject.common.name;
}
}
if (linkedObject.common.role) {
if (parentObject.common.role) {
if (parentObject.common.role != linkedObject.common.role) {
// nur übergeben wenn unterschiedlich zwischen linkedObject & parentObject ist
customForParentObj["role"] = linkedObject.common.role;
}
} else {
customForParentObj["role"] = linkedObject.common.role;
}
}
if (linkedObject.common.unit) {
if (parentObject.common.unit) {
if (parentObject.common.unit != linkedObject.common.unit) {
// nur übergeben wenn unterschiedlich zwischen linkedObject & parentObject ist
customForParentObj["number_unit"] = linkedObject.common.unit;
expertSettings = true;
}
} else {
if (linkedObject.common.type === 'number' && parentObject.common.type === 'string') {
// string_to_number: unit muss in andere prop gespreichert werden
customForParentObj["string_to_number_unit"] = linkedObject.common.unit;
expertSettings = true;
} else {
customForParentObj["number_unit"] = linkedObject.common.unit;
expertSettings = true;
}
}
}
if (linkedObject.common.max) {
if (parentObject.common.max) {
if (parentObject.common.max != linkedObject.common.max) {
// nur übergeben wenn unterschiedlich zwischen linkedObject & parentObject ist
customForParentObj["number_max"] = linkedObject.common.max;
expertSettings = true;
}
} else {
customForParentObj["number_max"] = linkedObject.common.max;
expertSettings = true;
}
}
if (linkedObject.common.min) {
if (parentObject.common.min) {
if (parentObject.common.min != linkedObject.common.min) {
// nur übergeben wenn unterschiedlich zwischen linkedObject & parentObject ist
customForParentObj["number_min"] = linkedObject.common.min;
expertSettings = true;
}
} else {
customForParentObj["number_min"] = linkedObject.common.min;
expertSettings = true;
}
}
if (linkedObject.common.type) {
if (parentObject.common.type && parentObject.common.type != linkedObject.common.type) {
// nur übergeben wenn Einheit unterschiedlich zwischen linkedObject & parentObject ist
let convertToKey = parentObject.common.type + "_convertTo";
if (linkedObject.common.custom && linkedObject.common.custom[this.namespace] && linkedObject.common.custom[this.namespace].number_to_duration_format) {
// Spezial Format: Duration
customForParentObj[convertToKey] = "duration"
expertSettings = true;
} else if (linkedObject.common.custom && linkedObject.common.custom[this.namespace] && linkedObject.common.custom[this.namespace].number_to_datetime_format) {
// Spezial Format: DateTime
customForParentObj[convertToKey] = "datetime"
expertSettings = true;
} else if (linkedObject.common.custom && linkedObject.common.custom[this.namespace] && linkedObject.common.custom[this.namespace].string_to_duration_format) {
// Spezial Format: Duration
customForParentObj[convertToKey] = "duration"
expertSettings = true;
} else if (linkedObject.common.custom && linkedObject.common.custom[this.namespace] && linkedObject.common.custom[this.namespace].string_to_datetime_format) {
// Spezial Format: DateTime
customForParentObj[convertToKey] = "datetime"
expertSettings = true;
} else {
// kein Spezial Format
customForParentObj[convertToKey] = linkedObject.common.type;
expertSettings = true;
}
}
}
// custom Data vom linked Object holen und um nicht benötigte keys für das parentObject bereinigen
let customFromLinkedObject = linkedObject.common.custom[this.namespace];
if (customFromLinkedObject.enabled) {
delete customFromLinkedObject.enabled;
}
if (customFromLinkedObject.parentId) {
delete customFromLinkedObject.parentId;
}
if (customFromLinkedObject.parentType) {
delete customFromLinkedObject.parentType;
}
if (customFromLinkedObject.isLinked || !customFromLinkedObject.isLinked) {
delete customFromLinkedObject.isLinked;
}
// bereinigt custom Data und common Data vom linkedObject zusammenführen
if (Object.keys(customFromLinkedObject).length > 0) {
// Wenn custom Daten in linkedObject vorhanden -> dann expertSettings setzen
expertSettings = true;
}
Object.assign(customForParentObj, customFromLinkedObject);
// weitere benötigte Daten hinzufügen
customForParentObj.enabled = true;
customForParentObj.linkedId = linkedObject._id.replace(this.namespace + ".", "");
customForParentObj.expertSettings = expertSettings;
// custom Data an parentObject übergeben
if (parentObject.common.custom) {
// custom von anderen Adaptern vorhanden
parentObject.common.custom[this.namespace] = customForParentObj;
} else {
// kein custom vorhanden
parentObject.common.custom = { [this.namespace]: customForParentObj };
}
// parentObject aktualisieren -> linkedObject Daten werden automatisch wegen neustart des Adapters nach dem speichern aktualisiert
await this.setForeignObjectAsync(parentId, parentObject);
this.log.info(`[assignToParentObject] linkedObject '${linkedId}' assigned to parentObject '${parentId}' successful`);
return { success: true, error: null };
}
}
} catch (err) {
this.log.error(`[assignToParentObject] linkedObject '${linkedId}', parentObject '${parentId}' error: ${err.message}`);
this.log.error("[assignToParentObject] stack: " + err.stack);
return { success: true, error: err.message };
}
}
/**
* @param {string} id
* @param {ioBroker.State} state
* @param {string} objId
* @param {string} logPrefix
*/
async logStateChange(id, state, objId, logPrefix, changedValue) {
let objState = await this.getForeignStateAsync(objId);
let logChangeStateFor = "parentObject";
if (logPrefix === "parentObject") {
logChangeStateFor = "linkedObject";
}
if (objState) {
if (state.val != objState.val || state.ack != objState.ack) {
this.log.debug(`[onStateChange] ${logPrefix} state '${id}' changed to '${state.val}' (ack = ${state.ack}) --> set ${logChangeStateFor} state '${objId}' to '${changedValue}'`)
} else if (state.ts != objState.ts) {
this.log.debug(`[onStateChange] ${logPrefix} state '${id}' timestamp changed --> set ${logChangeStateFor} state '${objId}' to '${changedValue}'`)
} else {
this.log.debug(`[onStateChange] ${logPrefix} state '${id}' other changes --> set ${logChangeStateFor} state '${objId}' to '${changedValue}'`)
}
} else {
this.log.debug(`[onStateChange] ${logPrefix} empty state '${id}' set to '${state.val}' (ack = ${state.ack}) --> set ${logChangeStateFor} state '${objId}' to '${changedValue}'`)
}
}
async initialObjects() {
this.log.info('[initialObjects] started...')
// benötigte Daten aus System Config holen
this.getSystemConfig();
// all unsubscripe to begin completly new
this.unsubscribeForeignStates("*");
this.dicLinkedObjectsStatus = {}; // Dic für 'isLinked' Status aller linkedObjects
this.dicLinkedParentObjects = {}; // Dic für parentObjects die mit einem linkedObject verlinkt sind
await this.resetAllLinkedObjectsStatus();
await this.createAllLinkedObjects();
await this.removeAllNotLinkedObjects();
if (this.dicLinkedObjectsStatus) this.log.debug("[initialObjects] 'dicLinkedObjectsStatus' items count: " + Object.keys(this.dicLinkedObjectsStatus).length);
this.storeInfoStates();
// subscribe für alle 'states' des Adapters, um Änderungen mitzubekommen
await this.subscribeStatesAsync('*');
this.log.info('[initialObjects] finished')
}
sort_by_key(array, key) {
return array.sort(function (a, b) {
var x = a[key]; var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
async getSystemConfig() {
// benötigte Daten aus System Config holen
var sysConfig = Object(await this.getForeignObjectAsync('system.config'));
if (sysConfig && sysConfig.common) {
if (sysConfig.common.language) {
// language übergeben
mySystemConfig.language = sysConfig.common.language;
}
if (sysConfig.common.dateFormat) {
mySystemConfig.dateFormat = sysConfig.common.dateFormat;
}
this.log.debug(`[getSystemConfig] system configs successful loaded: '${JSON.stringify(mySystemConfig)}'`);
} else {
this.log.warn(`[getSystemConfig] could not load system configs! Using adapter default values '${JSON.stringify(mySystemConfig)}'`);
}
}
/*
* 'custom.isLinked' auf 'False' für alle vorhanden verlinkten datenpunkte setzen -> status wird später zum löschen benötigt
* auch für parentObject die inzwischen auf 'enabled==false' gesetzt wurden
*/
async resetAllLinkedObjectsStatus() {
// alle Datenpunkte des Adapters durchlaufen
let linkedObjList = await this.getAdapterObjectsAsync();
for (let idLinkedObj in linkedObjList) {
let linkedObj = linkedObjList[idLinkedObj];
await this.resetLinkedObjectStatus(linkedObj);
}
if (this.dicLinkedObjectsStatus) {
this.log.debug("[resetAllLinkedObjectsStatus] 'dicLinkedObjectsStatus' items count: " + Object.keys(this.dicLinkedObjectsStatus).length);
this.log.silly("[resetAllLinkedObjectsStatus] linkedObjects status " + JSON.stringify(this.dicLinkedObjectsStatus));
}
}
/**
* 'custom.isLinked' auf 'False' für linkedObject setzen
* @param {ioBroker.Object} linkedObj
*/
async resetLinkedObjectStatus(linkedObj) {
if (linkedObj && linkedObj.common && linkedObj.common.custom && linkedObj.common.custom[this.namespace] &&
(linkedObj.common.custom[this.namespace].isLinked || !linkedObj.common.custom[this.namespace].isLinked)) {
// Wenn Datenpunkt Property 'isLinked' hat, dann auf 'False' setzen
linkedObj.common.custom[this.namespace].isLinked = false;
linkedObj.common.icon = 'linkeddevices_missing.png';
// existierende linkedObjects in dict packen
if (this.dicLinkedObjectsStatus) this.dicLinkedObjectsStatus[linkedObj._id] = false;
await this.setForeignObjectAsync(linkedObj._id, linkedObj);
this.log.debug("[resetLinkedObjectStatus] 'isLinked' status reseted for '" + linkedObj._id + "'");
}
}
/**
* 'custom.isLinked' auf 'False' für linkedId setzen
* @param {String} linkedId
*/
async resetLinkedObjectStatusById(linkedId) {
let linkedObj = Object();
linkedObj = await this.getForeignObjectAsync(linkedId);
await this.resetLinkedObjectStatus(linkedObj);
this.logDicLinkedObjectsStatus();
}
/*
* alle Obejkte finden, die verlinkt werden sollen und linkedObject erzeugen bzw. aktualisieren
*/
async createAllLinkedObjects() {
let parentObjList = await this.getForeignObjectsAsync('');
for (let idParentObj in parentObjList) {
let parentObj = parentObjList[idParentObj]
await this.createLinkedObject(parentObj);
}
if (this.dicLinkedObjectsStatus) {
this.log.debug("[createAllLinkedObjects] 'dicLinkedObjectsStatus' items count: " + Object.keys(this.dicLinkedObjectsStatus).length);
this.log.silly("[createAllLinkedObjects] linkedObjects status " + JSON.stringify(this.dicLinkedObjectsStatus));
for (var key in this.dicLinkedObjectsStatus) {
if (this.dicLinkedObjectsStatus.hasOwnProperty(key) && this.dicLinkedObjectsStatus[key] === false) {
this.log.warn(`linkedObject '${key}' is not linked any more!`);
}
}
}
if (this.dicLinkedParentObjects) {
this.log.info("[createAllLinkedObjects] count of active linkedObjects: " + Object.keys(this.dicLinkedParentObjects).length)
this.log.debug("[createAllLinkedObjects] active linkedObjects " + JSON.stringify(this.dicLinkedParentObjects));
}
}
/**
* Create linked object channel if it not exist
* @param {string} linkedId
*/
async createLinkedObjectChannel(linkedId) {
// id um namespace bereinigen
let cleanId = linkedId.replace(`${this.namespace}.`, '');
// wenn '.' vorhanden, dann channel erstellen
if (cleanId.includes('.')) {
let channelId = linkedId;
for (var i = 0; i <= cleanId.split(".").length - 1; i++) {
// bis zum namespace channels erstellen
channelId = channelId.substring(0, channelId.lastIndexOf('.'))
if (channelId && channelId != this.namespace) {
let channelExistObj = await this.getObjectAsync(channelId);
if (!channelExistObj) {
// channel Objekt existiert nicht -> anlegen
await this.setObjectNotExistsAsync(channelId, {
_id: channelId,
type: "channel",
common: {
name: `${channelId.replace(`${this.namespace}.`, '').replace(/\./g, ' ')}`,
desc: 'Created by linkeddevices'
},
native: {}
});
this.log.debug(`[createLinkedObjectChannel] channel '${channelId}' created.`);
} else {
this.log.debug(`[createLinkedObjectChannel] channel '${channelId}' already exist!`);
}
}
}
}
}
/**
* linkedObject mit parentObject erstellen bzw. aktualisieren und 'isLinked' Status setzen (= hat eine existierende Verlinkung)
* @param {ioBroker.Object} parentObj
* @param {ioBroker.Object} oldLinkedObj
*/
async createLinkedObject(parentObj, oldLinkedObj = Object()) {
try {
var linkedId = null;
// Datenpunkte sind von 'linkeddevices' und aktiviert
if (parentObj && !parentObj._id.startsWith(this.namespace) && parentObj.common && parentObj.common.custom && parentObj.common.custom[this.namespace]
&& parentObj.common.custom[this.namespace].enabled) {
// Todo: check structure if channel, device, etc.
// let tmp = parentObj._id.lastIndexOf(".");
// this.log.info(parentObj._id.substring(0, tmp));
if (!parentObj.common.custom[this.namespace].linkedId || !parentObj.common.custom[this.namespace].linkedId.length || parentObj.common.custom[this.namespace].linkedId === "") {
// 'custom.linkedId' fehlt oder hat keinen Wert
this.log.error("[createLinkedObject] No 'linkedId' defined for object: '" + parentObj._id + "'");
} else {
// 'custom.linkedId' vorhanden
linkedId = this.getLinkedObjectId(parentObj);
if ((/[*?"'\[\]]/).test(linkedId)) {
// 'custom.linkedId' enthält illegale zeichen
this.log.error("[createLinkedObject] linkedId: '" + linkedId + "' contains illegal characters (parentId: '" + parentObj._id + "')");
} else {
// Create channel object if need.
await this.createLinkedObjectChannel(linkedId);
// LinkedObjekt daten übergeben
let linkedObj = Object();
linkedObj.type = parentObj.type;
// common data mit expert settings an linkedObject übergeben
linkedObj.common = this.getCommonData(parentObj, linkedId);
// Übernehmen custom data von anderen Adaptern
await this.setExistingCustomData(linkedId, linkedObj, oldLinkedObj);
// custom data (expert settings) an linkedObject übergeben
linkedObj.common.custom[this.namespace] = this.getCustomData(parentObj, linkedId);
this.log.silly(`[createLinkedObject] custom data set for '${linkedId}' ("${this.namespace}":${JSON.stringify(linkedObj.common.custom[this.namespace])})`)
// falls native data vorhanden sind -> übergeben
if (parentObj.native) {
linkedObj.native = parentObj.native;
if (Object.keys(linkedObj.native).length > 0) {
this.log.debug(`[createLinkedObject] native data set for '${linkedId}' ("native":${JSON.stringify(parentObj.native)})`)
} else {
this.log.silly(`[createLinkedObject] native data set for '${linkedId}' ("native":${JSON.stringify(parentObj.native)})`)
}
}
let merged = false;
let existingLinkedObj = await this.getForeignObjectAsync(linkedId);
if (existingLinkedObj && linkedObj && linkedObj.common && linkedObj.common.custom && linkedObj.common.custom[this.namespace] && linkedObj.common.custom[this.namespace].mergeSettingsOnRestart) {
// wenn linkedObject bereits existiert und user 'merge' setting aktiviert hat -> linkedObject settings mergen
merged = true;
await this.extendForeignObjectAsync(linkedId, linkedObj);
} else {
// LinkedObjekt erzeugen oder Änderungen schreiben -> wird vollständig überschrieben
await this.setForeignObjectAsync(linkedId, linkedObj);
}
// ggf. können neue linkedObjects hinzugekommen sein -> in dic packen
if (this.dicLinkedObjectsStatus) this.dicLinkedObjectsStatus[linkedId] = true;
this.logDicLinkedObjectsStatus();
// linked parentObjects in dic speichern
if (this.dicLinkedParentObjects) this.dicLinkedParentObjects[parentObj._id] = linkedId;
this.logDicLinkedParentObjects();
// state value für linkedObject setzen, wird vom parent übernommen
let parentState = await this.getForeignStateAsync(parentObj._id);
let linkedState = await this.getForeignStateAsync(linkedId);
if (parentState) {
// ggf. kann für das linkedObject eine Umrechnung festgelegt sein
let parentValue = await this.getConvertedValue(linkedId, parentState.val);
if (linkedState) {
if (linkedState.val != parentValue || linkedState.ack != parentState.ack) {
// Nur aktualisieren, sofern nicht gleich -> damit wird z.B. bei button kein press ausgelöst
await this.setForeignStateAsync(linkedId, { val: parentValue, ack: true });
this.log.debug(`[createLinkedObject] update value for '${linkedId}' to '${parentValue}'`);
} else {
this.log.debug(`[createLinkedObject] value for '${linkedId}' is up to date`);
}
} else {
// linkedObject hat noch keinen state value
await this.setForeignStateAsync(linkedId, { val: parentValue, ack: true });
this.log.debug(`[createLinkedObject] set value for '${linkedId}' to '${parentValue}'`);
}
} else {
this.log.debug(`[createLinkedObject] no value set for '${linkedId}' because parentObject has no value`);
}
// subscribe für parentObject 'state', um Änderungen mitzubekommen
await this.subscribeForeignStatesAsync(parentObj._id);
if (parentObj.common.type === linkedObj.common.type) {
this.log.info(`[createLinkedObject] linked object '${parentObj._id}'${(merged) ? ' merged' : ''} to '${linkedId}'`);
} else {
this.log.info(`[createLinkedObject] linked object '${parentObj._id}' (${parentObj.common.type})${(merged) ? ' merged' : ''} to '${linkedId}' (${linkedObj.common.type})`);
}
}
}
}
} catch (err) {
this.log.error(`[createLinkedObject] parentObject '${parentObj._id}', linkedObject '${linkedId}' error: ${err.message}`);
this.log.error("[createLinkedObject] stack: " + err.stack);
}
}
/*
* alle LinkedObjects löschen, die keine existierende Verlinkung mehr haben ('custom.isLinked' == false), sofern nicht in Config deaktiviert
*/
async removeAllNotLinkedObjects() {
if (this.config.deleteDeadLinkedObjects) {
// dic verwenden
if (this.dicLinkedObjectsStatus) {
for (var linkedId in this.dicLinkedObjectsStatus) {