-
Notifications
You must be signed in to change notification settings - Fork 0
/
fjadapter.js
1386 lines (1264 loc) · 40.7 KB
/
fjadapter.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
/* eslint-disable no-await-in-loop */
/* eslint-disable valid-jsdoc */
/* eslint-disable no-prototype-builtins */
/**
* iobroker MyAdapter II class
* (c) 2020- <frankjoke@hotmail.com>
* MIT License
*
* V 1.0.1 July 2020
* V 1.9.99 May 2020
*/
"use strict";
//@ts-disable TS80006
//@js-disable TS80006
class CacheP {
constructor(options = {}) {
if (typeof options === "function") options = { fun: options };
this._o = Object.assign(
{},
{
maxage: 0,
delay: 0,
fun: null,
},
options
);
this._c = {};
return this;
}
async cacheItem(item, prefereCache = true, funa) {
let options = {
pref_c: prefereCache === true,
};
if (typeof funa === "function") options.fun = funa;
const check =
typeof item === "object" && item.getItem
? typeof item.getItem === "function"
? item.getItem(item)
: item.getItem
: item;
if (typeof prefereCache === "object") Object.assign(options, prefereCache);
options = Object.assign({}, this._o, options);
const { fun, delay, pref_c, maxage } = options;
if (delay) await MyAdapter.wait(this._delay);
// MyAdapter.D("CacheP %s, %o: %o, %o", check, this._o, item, options);
if (pref_c && this.isCached(check)) return this._c[check].value;
// assert(MyAdapter.T(fun) === 'function', `checkItem needs a function to fill cache!`);
let value;
try {
// MyAdapter.D("CacheP not cached: %s: %O", check, fun);
value = await fun(item);
// MyAdapter.D("CacheP not cached result: %s: %O", check, value);
} catch (e) {
// MyAdapter.W("CacheP Error in cache-function %O for %s: %o", fun, check, e);
}
// MyAdapter.D("CacheP %s returned %s", check, value);
if (value) this._c[check] = { time: Date.now(), value };
else this._c[check] = undefined;
return value;
}
isCached(item, maxage = 0) {
if (!maxage) maxage = this._o.maxage || 0;
const check =
typeof item === "object" && item.getItem
? typeof item.getItem === "function"
? item.getItem(item)
: item.getItem
: item;
const c = this._c[check];
if (!c) return null;
// MyAdapter.D("MaxAge %s, %d, %d", check, maxage, c.time+maxage, Date.now());
if (maxage > 0 && c.time + maxage < Date.now()) {
this._c[check] = undefined;
return null;
}
return c;
}
setMaxAge(val) {
this._o.maxage = val;
return val;
}
setDelay(val) {
this._o.delay = val;
return val;
}
setFun(val) {
this._o.fun = val;
return val;
}
clearCache() {
this._c = {};
}
get cache() {
return this._c;
}
cacheSync(item, prefereCache = true, funa) {
const options = {
pref_c: prefereCache === true,
};
if (typeof funa === "function") options.fun = funa;
const check =
typeof item === "object" && item.getItem
? typeof item.getItem === "function"
? item.getItem(item)
: item.getItem
: item;
if (typeof prefereCache === "object") Object.assign(options, prefereCache);
const { fun, delay, pref_c, maxage } = Object.assign({}, this._o, options);
if (pref_c && this.isCached(check)) return this._c[check].value;
let value;
try {
value = fun(item);
if (value) this._c[check] = { time: Date.now(), value };
else this._c[check] = undefined;
} finally {
return value;
}
}
}
class HrTime {
constructor(time) {
this.time = time;
}
get diff() {
return process.hrtime(this._stime);
}
get text() {
const t = this.diff;
const ns = t[1].toString(10);
return t[0].toString(10) + "." + ("0".repeat(9 - ns.length) + ns).slice(0, 6);
}
toString() {
return this.text;
}
get time() {
return Number(this.text);
}
set time(t) {
this._stime = t || process.hrtime();
}
}
// you have to call the adapter function and pass a options object
// name has to be set and has to be equal to adapters folder name and main file name excluding extension
// adapter will be restarted automatically every time as the configuration changed, e.g system.adapter.template.0
const util = require("util"),
cp = require("child_process"),
os = require("os"),
fs = require("fs"),
masync = require("modern-async"),
plugandplay = require("plug-and-play"),
assert = require("assert"),
axios = require("axios");
const objects = {},
states = {},
createdStates = {},
sstate = {},
plugins = plugandplay(),
mstate = {};
plugins.$plugins = {};
plugins.$options = {};
let adapter,
aoptions,
aname,
schedulers = [],
_objChange,
_stateChange,
stopping = false,
maxdelay = 0,
// allStates = null,
// stateChange = null,
systemconf = null;
function startAdapter(options) {
if (!options) options = aoptions;
options = options || {};
if (typeof options === "string")
options = {
name: options,
};
else options.name = aname;
options = Object.assign(options, {
/**
* Is called when databases are connected and adapter received configuration.
*/
async ready() {
// Initialize your adapter here
MyAdapter.extendObject = adapter.extendObjectAsync.bind(adapter);
await plugins.call({
name: "adapter$init",
args: {
adapter,
},
handler: ({ adapter }) => {
// console.log("Default adapter$init handler is starting", adapter.name);
// return amain && amain(adapter);
},
});
await MyAdapter.initAdapter();
await plugins.call({
name: "adapter$start",
args: {
adapter,
},
handler: async ({ adapter }, handler) => {
// MyAdapter.D("Default adapter$start for %s is starting", adapter.namespace);
return handler;
},
});
await plugins.call({
name: "adapter$run",
args: {
adapter,
},
handler: async ({ adapter }, handler) => {
// MyAdapter.D("Default adapter$run handler for %s is starting.", adapter.namespace);
return handler;
},
});
},
/* Is called when adapter shuts down - callback has to be called under any circumstances!
* @param {() => void} callback
*/
async unload(callback) {
try {
await MyAdapter.stop(0, false);
callback();
} catch (e) {
callback();
}
},
/**
* Is called if a subscribed object changes
* @param {string} id
* @param {ioBroker.Object | null | undefined} obj
*/
async objectChange(id, obj) {
// MyAdapter.D("Object %s was changed top %o", id, obj);
setImmediate(() =>
plugins
.call({
name: "adapter$objectChange",
args: {
adapter,
id,
obj,
},
handler: async ({ adapter, id, obj }, handler) => {
// MyAdapter.S("Default adapter$stateChange handler for %s: %s.", id, MyAdapter.O(state));
return handler;
},
})
.catch((err) => MyAdapter.W(`Error in ObjChange for ${id} = ${MyAdapter.O(err)}`))
);
if (obj) {
// The object was changed
objects[id] = obj;
// this.log.info(`object ${id} changed: ${JSON.stringify(obj)}`);
} else if (id) {
// The object was deleted
if (states[id]) delete states[id];
if (sstate[id]) delete sstate[id];
if (objects[id]) delete objects[id];
// this.log.info(`object ${id} deleted`);
}
},
/**
* Is called if a subscribed state changes
* @param {string} id
* @param {ioBroker.State | null | undefined} state
*/
async stateChange(id, state) {
// MyAdapter.D("State %s was changed top %o", id, state);
// if (!state || state.from !== "system.adapter." + MyAdapter.ains)
setImmediate(() =>
plugins
.call({
name: "adapter$stateChange",
args: {
adapter,
id,
state,
},
handler: async ({ adapter, id, state }, handler) => {
// MyAdapter.S("Default adapter$stateChange handler for %s: %s.", id, MyAdapter.O(state));
return handler;
},
})
.catch((err) => MyAdapter.W(`Error in StateChange for ${id} = ${MyAdapter.O(err)}`))
);
// if (allStates)
// allStates(id, state).catch(e => this.W(`Error in AllStates for ${id} = ${this.O(e)}`)));
if (state) {
states[id] = state;
// The state was changed
// this.log.info(`state ${id} changed: ${state.val} (ack = ${state.ack})`);
} else if (id) {
// The state was deleted
delete states[id];
delete sstate[id];
// this.log.info(`state ${id} deleted`);
}
},
// /**
// * 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
// */
/* message(obj) {
if (typeof obj === "object" && obj.command)
MyAdapter.processMessage(
obj
// MyAdapter.D(`received Message ${MyAdapter.O(obj)}`, obj)
);
// if (obj.command === "send") {
// // e.g. send email or pushover or whatever
// this.log.info("send command");
// // Send response in callback if required
// if (obj.callback) this.sendTo(obj.from, obj.command, "Message received", obj.callback);
// }
// }
},
*/
});
if (plugins.get({ name: "adapter$message" }).length) {
options.message = (obj) => {
if (typeof obj === "object" && obj.command) {
plugins.call({
name: "adapter$message",
args: { message: obj },
handler: async ({ message }) => Array.D(`Message received: ${MyAdapter.O(message)}`),
});
if (obj.callback) adapter.sendTo(obj.from, obj.command, "Message received", obj.callback);
}
};
}
try {
const utils = require("@iobroker/adapter-core");
adapter = new utils.Adapter(options);
// MyAdapter.If("got following adapter: %o", options);
} catch (e) {
// eslint-disable-next-line no-console
console.error("cannot find ioBroker...");
}
if (adapter) MyAdapter.init2(adapter);
return adapter;
}
function slog(log, text, val) {
adapter && adapter.log && typeof adapter.log[log] === "function"
? // eslint-disable-next-line no-console
adapter.log[log](text)
: console.log(log + ":", text);
return val !== undefined ? val : text;
}
function addSState(n, id) {
if (!mstate[n]) {
if (sstate[n] && sstate[n] !== id) {
sstate[id] = id;
mstate[n] = [id];
delete sstate[n];
} else sstate[n] = id;
} else {
mstate[n].push(id);
sstate[id] = id;
}
}
class MyAdapter {
static get sleep() {
return masync.sleep;
}
static get asyncWrap() {
return masync.asyncWrap;
}
static map(iterable, iteratee, concurrency=0) {
return concurrency>0 ? masync.mapLimit(iterable, iteratee, concurrency) : masync.map(iterable, iteratee);
}
static mapSeries(iterable, iteratee) {
return masync.mapSeries(iterable, iteratee);
}
static get MA() {
return masync;
}
static setLogLevel(level = "info") {
return adapter.setForeignStateAsync("system.adapter." + adapter.namespace + ".logLevel", level);
}
static get asyncRoot() {
return masync.asyncRoot;
}
static get inspect() {
return util.inspect;
}
static get plugins() {
return plugins;
}
static get $plugins() {
return plugins.$plugins;
}
static get $options() {
return plugins.$options;
}
static get $F() {
return plugins.$plugins.functions;
}
static addHooks(hooks, options = {}) {
if (typeof hooks === "function") hooks = { [hooks.name]: hooks };
return plugins.register(Object.assign({}, options, { hooks }));
}
static get config() {
return adapter.config;
}
static set stateChange(val) {
_stateChange = val;
}
static get stateChange() {
return _stateChange;
}
static set objChange(val) {
_objChange = val;
}
static get objChange() {
return _objChange;
}
static scheduler(fn, timer) {
const sch = new masync.Scheduler(fn, timer);
schedulers.push(sch);
sch.start();
return sch;
}
static getObjects(name) {
name = !name ? "" : name;
const opt = {
include_docs: true,
};
if (name) {
name = name === "*" ? "" : name;
opt.startkey = (name.startsWith("system.") ? "" : this.ain) + name;
opt.endkey = (name.startsWith("system.") ? "" : this.ain) + name + "\u9999";
}
return adapter.getObjectListAsync(opt).then(
(res) => (res && res.rows ? res.rows : []),
() => []
);
}
// eslint-disable-next-line complexity
static async initAdapter() {
try {
this.D("Adapter %s starting.", this.ains);
this.getObjectList = adapter.getObjectListAsync
? adapter.getObjectListAsync.bind(adapter)
: this.c2p(adapter.objects.getObjectList).bind(adapter.objects);
this.getForeignState = adapter.getForeignStateAsync.bind(adapter);
this.setForeignState = adapter.setForeignStateAsync.bind(adapter);
this.getState = adapter.getStateAsync.bind(adapter);
this.setState = adapter.setStateAsync.bind(adapter);
this.getStates = adapter.getStatesAsync.bind(adapter);
this.removeState = async (id, opt) => {
await adapter.delStateAsync(id, opt).catch(this.nop);
await adapter.delObjectAsync((delete states[id], id), opt).catch(this.nop);
};
const ms = await adapter.getStatesAsync("*").catch((err) => this.W(err));
for (const s of Object.keys(ms)) states[s] = ms[s];
// console.log(states);
let res = await this.getObjects("*");
const len = res.length;
for (const i of res) {
const o = i.doc;
objects[o._id] = o;
if (o.type === "state" && o.common && o.common.name) {
if (adapter.config.forceinit && o._id.startsWith(this.ain))
await this.removeState(o.common.name);
// if (!o._id.startsWith('system.adapter.'))
addSState(o.common.name, o._id);
}
}
res = await adapter.getForeignObjectAsync("system.config").catch(() => null);
if (res) {
systemconf = res.common;
// this.If('systemconf: %o', systemconf);
if (systemconf && systemconf.language) adapter.config.lang = systemconf.language;
if (systemconf && systemconf.latitude) {
adapter.config.latitude = parseFloat(systemconf.latitude);
adapter.config.longitude = parseFloat(systemconf.longitude);
}
// if (adapter.config.forceinit)
// this.seriesOf(res, (i) => this.removeState(i.doc.common.name), 2)
// this.If('loaded adapter config: %o', adapter.config);
}
res = await adapter.getForeignObjectAsync("system.adapter." + this.ains).catch(() => null);
if (res) {
adapter.config.adapterConf = res.common;
// this.If('adapterconf = %s: %o', 'system.adapter.' + this.ains, adapterconf);
// this.If('adapter: %o', adapter);
if (adapter.config.adapterConf && adapter.config.adapterConf.loglevel)
adapter.config.loglevel = adapter.config.adapterConf.loglevel;
// this.If('loglevel: %s, debug: %s', adapter.config.loglevel, MyAdapter.debug);
// if (adapter.config.forceinit)
// this.seriesOf(res, (i) => this.removeState(i.doc.common.name), 2)
// this.If('loaded adapter config: %o', adapter.config);
}
this.D(
`${adapter.name} received ${len} objects and ${this.ownKeys(states).length} states`
// } states, with config ${this.ownKeys(adapter.config)}`
);
adapter.subscribeStates("*");
if (adapter._objChange) adapter.subscribeObjects("*");
// .then(() => objChange ? MyAdapter.c2p(adapter.subscribeObjects)('*').then(a => MyAdapter.I('eso '+a),a => MyAdapter.I('eso '+a)) : MyAdapter.resolve())
// this.I(aname + " initialization started...");
} catch (e) {
this.stop(this.E(aname + " Initialization Error:" + this.F(e)));
}
}
static init(amodule, options) {
// assert(!adapter, `myAdapter:(${ori_adapter.name}) defined already!`);
// amain = ori_main;
if (typeof options === "string")
options = {
name: options,
};
aoptions = Object.assign({}, options);
aname = aoptions.name;
if (amodule && amodule.parent) {
amodule.exports = (options) => (adapter = startAdapter(options));
} else {
adapter = startAdapter(aoptions);
}
}
static get AI() {
return adapter;
}
static setConnected(value) {
createdStates[this.ain + "info.connection"] = "info.connection";
return adapter.setStateAsync("info.connection", { val: value, ack: true });
}
static init2() {
// if (adapter) this.If('adpter: %o',adapter);
assert(adapter && adapter.name, "myAdapter:(adapter) no adapter here!");
aname = adapter.name;
// inDebug =
stopping = false;
// curDebug = 1;
systemconf = null;
this.writeFile = this.c2p(fs.writeFile);
this.readFile = this.c2p(fs.readFile);
this.getForeignObject = adapter.getForeignObjectAsync.bind(adapter);
this.setForeignObject = adapter.setForeignObjectAsync.bind(adapter);
this.getForeignObjects = adapter.getForeignObjectsAsync.bind(adapter);
this.getObject = adapter.getObjectAsync.bind(adapter);
this.deleteState = (id) =>
adapter
.deleteStateAsync(id)
.catch((res) => (res === "Not exists" ? this.resolve() : this.reject(res)));
this.delObject = (id, opt) =>
adapter
.delObjectAsync(id, opt)
.catch((res) => (res === "Not exists" ? this.resolve() : this.reject(res)));
this.delState = (id, opt) =>
adapter
.delStateAsync(id, opt)
.catch((res) => (res === "Not exists" ? this.resolve() : this.reject(res)));
this.removeState = (id, opt) =>
adapter.delStateAsync(id, opt).then(() => this.delObject((delete states[id], id), opt));
this.setObject = adapter.setObjectAsync.bind(adapter);
this.createState = adapter.createStateAsync.bind(adapter);
this.extendObject = adapter.extendObjectAsync.bind(adapter);
this.extendForeignObject = adapter.extendForeignObjectAsync.bind(adapter);
// adapter.removeAllListeners();
process.on("rejectionHandled", (reason, promise) =>
this.W("Promise problem rejectionHandled of Promise %s with reason %s", promise, reason)
);
process.on("unhandledRejection", (reason, promise) =>
this.W("Promise problem unhandledRejection of Promise %o with reason %o", promise, reason)
);
return adapter;
}
static idName(id) {
if (objects[id] && objects[id].common) return objects[id].common.name; // + '(' + id + ')';
if (sstate[id] && sstate[id] !== id) return id; // + '(' + sstate[id] + ')';
return id; // +'(?)';
}
static J(/** string */ str, /** function */ reviewer) {
let res;
if (!str) return str;
if (typeof str !== "string") str = str.toString();
try {
res = JSON.parse(str, reviewer);
} catch (e) {
res = {
error: e,
error_description: `${e} on string ${str}`,
};
}
return res;
}
static pE(x, y) {
y = y ? y : MyAdapter.pE;
function get() {
const oldLimit = Error.stackTraceLimit;
Error.stackTraceLimit = Infinity;
const orig = Error.prepareStackTrace;
Error.prepareStackTrace = function (_, stack) {
return stack;
};
const err = new Error("Test");
Error.captureStackTrace(err, y);
const stack = err.stack;
Error.prepareStackTrace = orig;
Error.stackTraceLimit = oldLimit;
return stack.map((site) =>
site.getFileName()
? (site.getFunctionName() || "anonymous") +
" in " +
site.getFileName() +
" @" +
site.getLineNumber() +
":" +
site.getColumnNumber()
: ""
);
}
MyAdapter.W("Promise failed @ %o error: %o", get().join("; "), x);
return x;
}
static setMaxDelay(seconds = 0) {
maxdelay = seconds * 1000;
}
static nop(obj) {
return obj;
}
static split(x, s) {
return this.trim((typeof x === "string" ? x : `${x}`).split(s));
}
static trim(x) {
return Array.isArray(x) ? x.map(this.trim) : typeof x === "string" ? x.trim() : `${x}`.trim();
}
/* static A(arg) {
if (!arg)
this.E(this.f.apply(null, Array.prototype.slice.call(arguments, 1)));
assert.apply(null, arguments);
}
*/
static D(...str) {
return slog("debug", this.f(...str));
}
static S(...str) {
return slog("silly", this.f(...str));
}
static F(...args) {
return util.format(...args);
}
static f(...args) {
return this.F(...args).replace(/\n\s+/g, " ");
}
static I(...args) {
return slog("info", this.f(...args));
}
static W(...args) {
return slog("warn", this.f(...args));
}
static E(...args) {
return slog("error", this.f(...args));
}
static toNumber(v) {
return isNaN(Number(v)) ? 0 : Number(v);
}
static toInteger(v) {
return parseInt(this.toNumber(v));
}
static set addq(promise) {
stq.p = promise;
return stq;
}
static get name() {
return aname;
}
static get states() {
return states;
}
static get adapter() {
return adapter;
}
static get aObjects() {
return adapter.objects;
}
static get objects() {
return objects;
}
static get ains() {
return adapter.namespace;
}
static get ain() {
return this.ains + ".";
}
static get C() {
return adapter.config;
}
static fullName(id) {
return this.ain + id;
}
static parseLogic(obj) {
return this.includes(
["0", "off", "aus", "false", "inactive", ""],
obj.toString().trim().toLowerCase()
)
? false
: this.includes(
["1", "-1", "on", "ein", "true", "active"],
obj.toString().trim().toLowerCase()
);
}
static clone(obj) {
return JSON.parse(JSON.stringify(obj));
}
static P(pv, res, rej) {
if (pv instanceof Promise) return pv;
if (pv && typeof pv.then === "function") return new Promise((rs, rj) => pv.then(rs, rj));
if (pv) return this.resolve(res || pv);
return this.reject(rej || pv);
}
static nothing() {
return null;
}
static nextTick(x) {
return new Promise((res) => process.nextTick(() => res(x)));
}
static resolve(x) {
return this.nextTick(x);
}
static reject(x) {
return this.nextTick().then((_) => x);
}
static wait(time, arg) {
time = parseInt(this.toNumber(time));
if (time <= 0) return this.nextTick(arg);
return new Promise((resolve) => setTimeout(() => resolve(arg), time));
}
static async retry(nretry, fn, wait, ...args) {
//change args!!!
// assert(typeof fn === 'function', 'retry (,fn,) error: fn is not a function!');
nretry = this.toInteger(nretry);
nretry = nretry || 2;
while (nretry > 0)
try {
const res = await fn(...args);
return res;
} catch (err) {
nretry--;
if (!nretry) return Promise.reject(err);
await this.wait(wait || 0);
}
return null;
}
static async pSequence(arr, promise, wait) {
wait = wait || 0;
if (!Array.isArray(arr) && typeof arr === "object")
arr = Object.entries(arr).filter((o) => arr.hasOwnProperty(o[0]));
const res = [];
for (const i of arr) {
if (res.length) await this.wait(wait);
try {
const r = await promise(i);
res.push(r);
} catch (e) {
res.push(e);
}
}
return res;
}
static pTimeout(pr, time, callback) {
const t = this.toNumber(time);
let st = null;
return new Promise((resolve, reject) => {
const rs = (res) => {
if (st) clearTimeout(st);
st = null;
return resolve(res);
},
rj = (err) => {
if (st) clearTimeout(st);
st = null;
return reject(err);
};
st = setTimeout(() => {
st = null;
reject(`timer ${t} run out`);
}, t);
if (callback) callback(rs, rj);
this.P(pr).then(rs, rj);
});
}
static async Ptime(promise, arg) {
const start = Date.now();
if (typeof promise === "function") promise = promise(arg);
await Promise.resolve(promise).catch(() => null);
const end = Date.now();
return end - start;
}
static O(obj, level) {
return util
.inspect(obj, {
depth: level || 2,
colors: false,
})
.replace(/\n\s*/g, "");
}
static removeEmpty(obj) {
if (this.T(obj) !== "object") return obj;
const a = this.clone(obj);
for (const n of Object.getOwnPropertyNames(a))
if (!a[n] && typeof a[n] !== "boolean") delete a[n];
return a;
}
static String(obj, level = 2) {
return typeof obj === "string" ? obj : this.O(obj, level);
}
static N(fun, ...args) {
return setImmediate(fun, ...args);
} // move fun to next schedule keeping arguments
static T(i, j) {
let t = typeof i;
if (t === "object") {
if (Array.isArray(i)) t = "array";
else if (i instanceof RegExp) t = "regexp";
else if (i === null) t = "null";
} else if (t === "number" && isNaN(i)) t = "NaN";
return j === undefined ? t : this.T(j) === t;
}
static locDate(date) {
return date instanceof Date
? new Date(date.getTime() - date.getTimezoneOffset() * 60000)
: typeof date === "string"
? new Date(Date.parse(date) - new Date().getTimezoneOffset() * 60000)
: !isNaN(+date)
? new Date(+date - new Date().getTimezoneOffset() * 60000)
: new Date(Date.now() - new Date().getTimezoneOffset() * 60000);
}
static dateTime(date) {
return this.locDate(date).toISOString().slice(0, -5).replace("T", "@");
}
static obToArray(obj) {
return Object.keys(obj)
.filter((x) => obj.hasOwnProperty(x))
.map((i) => obj[i]);
}
static includes(obj, value) {
return this.T(obj) === "object"
? obj[value] !== undefined
: Array.isArray(obj)
? obj.find((x) => x === value) !== undefined
: obj === value;
}
static ownKeys(obj) {
return this.T(obj) === "object" ? Object.getOwnPropertyNames(obj) : [];
// return this.T(obj) === 'object' ? Object.keys(obj).filter(k => obj.hasOwnProperty(k)) : [];
}
static ownKeysSorted(obj) {
return this.ownKeys(obj).sort(function (a, b) {
a = a.toLowerCase();
b = b.toLowerCase();
if (a > b) return 1;
if (a < b) return -1;
return 0;
});
}
static async stop(dostop = 0, stopcall = false) {
if (stopping) return;
schedulers.forEach((sch) => sch.stop());
try {
await plugins.call({
name: "adapter$stop",
args: {
dostop,
stopcall,
adapter,
},
handler: async ({ dostop }, handler) => {
MyAdapter.I(`adapter$stop called with ${dostop}/${stopcall}!`);
await MyAdapter.plugins.call({
name: "plugins$stop",
args: { plugins: MyAdapter.$plugins, adapter },
handler: async ({ plugins }, handler) => {
MyAdapter.D("plugins$stop executed for %o", plugins);
return handler;
},
});
return null;
},
});
} finally {
stopping = true;
}
if (stopcall) {
const x = dostop < 0 ? 0 : dostop || 0;
MyAdapter.D(
"Adapter will exit now with code %s and method %s!",
x,
adapter && adapter.terminate ? "adapter.terminate" : "process.exit"
);
if (adapter && adapter.terminate) adapter.terminate(x);
else process.exit(x);
}
}