-
Notifications
You must be signed in to change notification settings - Fork 10
/
fjadapter-core.js
1231 lines (1125 loc) · 43.3 KB
/
fjadapter-core.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-prototype-builtins */
/**
* iobroker MyAdapter II class
* (c) 2020- <frankjoke@hotmail.com>
* MIT License
*
* V 0.2.0 Mai 2020
*/
'use strict';
//@ts-disable TS80006
//@js-disable TS80006
class Mcore {
construnctor(options) {
console.log('Mcore:', options);
}
}
let acore = {
Adapter: Mcore
};
if (process.env.fjadapter != 'TESTING')
acore = require('@iobroker/adapter-core');
class CacheP {
constructor(fun, delay) { // neue Einträge werden mit dieser Funktion kreiert
if (typeof fun != 'function')
throw 'CacheP needs an async function returning a Promise as first argument!';
this._cache = {};
this._fun = fun;
this._delay = delay || 0;
return this;
}
async cacheItem(item, prefereCache = true, fun) {
fun = fun || this._fun;
if (this._delay)
await new Promise(res => setTimeout(() => res(), this._delay));
if (prefereCache && this._cache[item] !== undefined)
return this._cache[item];
if (!fun)
fun = this._fun;
// assert(A.T(fun) === 'function', `checkItem needs a function to fill cache!`);
const res = await fun(item);
this._cache[item] = res;
return res;
}
isCached(x) {
return this._cache[x] !== undefined;
}
clearCache() {
this._cache = {};
}
get cache() {
return this._cache;
}
cacheSync(item, prefereCache = true, fun) {
const cached = this.isCached(item);
if (cached && prefereCache)
return this._cache[item];
fun = fun || this._fun;
if (typeof fun == 'function') try {
const res = fun(item);
if (res) {
this._cache[item] = res;
return res;
}
} finally {
// empty
}
return null;
}
}
class HrTime {
constructor(time) {
this._stime = time ? time : process.hrtime();
}
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);
}
get time() {
return Number(this.text);
}
set time(t) {
this._stime = t || process.hrtime();
}
}
class Sequence {
constructor(p, delay) {
this._p = p ? p : Promise.resolve();
this._delay = delay || 0;
return this;
}
get p() {
return this._p;
}
set p(val) {
this.add(val);
return;
}
add(val, ...args) {
const fun = typeof val === 'function' ? val : () => val;
if (this._delay) {
const n = () => new Promise(res => setTimeout(() => res(), this._delay));
this._p = this._p.then(() => n(), () => n());
}
this._p = this._p.then(() => fun(...args), () => fun(...args));
return this;
}
async then(res, rej) {
return this._p = this._p.then(res, rej);
} catch (rej) {
return this._p = this._p.then(x => x, rej);
}
}
// 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'),
exec = require('child_process').exec,
os = require('os'),
assert = require('assert'),
axios = require('axios');
const objects = {},
stq = new Sequence(),
states = {},
createdStates = {},
sstate = {},
mstate = {};
let adapter, aoptions, aname, amain, timer,
stopping = false,
inDebug = false,
curDebug = 1,
// allStates = null,
// stateChange = null,
systemconf = null;
let messages = (mes) => Promise.resolve(MyAdapter.W(`Message ${this.O(mes)} received and no handler defined!`));
function slog(log, text) {
if (inDebug === undefined)
return text;
return adapter && adapter.log && typeof adapter.log[log] === 'function' ?
// eslint-disable-next-line no-console
adapter.log[log](text) : console.log(log + ': ' + 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 IobAdapter extends acore.Adapter {
/**
* @param {Partial<ioBroker.AdapterOptions>} [options={}]
*/
constructor(options) {
super(options);
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._stateChange = options.stateChange;
this._objChange = options.objChange;
this._onStop = options.onStop;
this._onUnload = options.onUnload;
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
// Initialize your adapter here
MyAdapter.extendObject = adapter.extendObjectAsync.bind(adapter);
await MyAdapter.initAdapter();
await Promise.resolve(amain(this));
}
/* Is called when adapter shuts down - callback has to be called under any circumstances!
* @param {() => void} callback
*/
async onUnload(callback) {
try {
await Promise.resolve(this._onUnload ? this._onUnload(null) : null).catch(e => this.Wf(e));
MyAdapter.stop(null, callback);
callback();
} catch (e) {
callback();
}
}
/**
* Is called if a subscribed object changes
* @param {string} id
* @param {ioBroker.Object | null | undefined} obj
*/
onObjectChange(id, obj) {
// MyAdapter.Df("Object %s was changed top %O", id, obj);
if (typeof this._objChange == 'function')
setTimeout(() => this._objChange(id, obj), 0);
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
*/
onStateChange(id, state) {
// MyAdapter.Df("State %s was changed top %O", id, state);
if (this._stateChange && (!state || state.from !== 'system.adapter.' + this.ains))
setImmediate(() => this._stateChange(id, state).catch(err => this.W(`Error in StateChange for ${id} = ${this.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
// */
onMessage(obj) {
if (typeof obj === 'object' && obj.message) {
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);
}
}
}
}
class MyAdapter {
static get config() {
return adapter.config;
}
static processMessage(obj) {
return (obj.command === 'debug' ? this.resolve(`debug set to '${inDebug = isNaN(parseInt(obj.message)) ? this.parseLogic(obj.message) : parseInt(obj.message)}'`) : messages(obj))
.then(res => this.D(`Message from '${obj.from}', command '${obj.command}', message '${this.S(obj.message)}' executed with result:"${this.S(res)}"`, res),
err => this.W(`invalid Message ${this.O(obj)} caused error ${this.O(err)}`, err))
.then(res => obj.callback ? adapter.sendTo(obj.from, obj.command, res, obj.callback) : undefined)
.then(() => this.c2p(adapter.getMessage)().then(obj => obj ? this.processMessage(obj) : true));
}
static async 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 : [], () => []);
}
static async initAdapter() {
try {
this.Df('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;
if (adapter.config.loglevel === 'debug' || adapter.config.loglevel === 'silly')
this.debug = true;
// 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);
}
MyAdapter.D(`${adapter.name} received ${len} objects and ${this.ownKeys(states).length} 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...');
// process.on('rejectionHandled', (reason, promise) => this.Wr(true, 'Promise problem rejectionHandled of Promise %s with reason %s', promise, reason));
// process.on('unhandledRejection', (reason, promise) => this.Wr(true, 'Promise problem unhandledRejection of Promise %O with reason %O', promise, reason));
} catch (e) {
this.stop(this.E(aname + ' Initialization Error:' + this.F(e)));
}
}
static init(amodule, options, ori_main) {
// assert(!adapter, `myAdapter:(${ori_adapter.name}) defined already!`);
if (typeof ori_main !== 'function')
throw 'No main function defined!';
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 = new IobAdapter(options));
} else {
adapter = new IobAdapter(aoptions);
}
}
static get AI() {
return adapter;
}
/*
static init2() {
// if (adapter) this.If('adpter: %O',adapter);
assert(adapter && adapter.name, 'myAdapter:(adapter) no adapter here!');
aname = adapter.name;
inDebug = timer = stopping = false;
curDebug = 1;
systemconf = null;
objects = {};
states = {};
stq = new Sequence();
sstate = {};
mstate = {};
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.Wr(true, 'Promise problem rejectionHandled of Promise %s with reason %s', promise, reason));
process.on('unhandledRejection', (reason, promise) => this.Wr(true, 'Promise problem unhandledRejection of Promise %O with reason %O', promise, reason));
adapter.on('message', obj => obj && this.processMessage(this.D(`received Message ${this.O(obj)}`, obj)))
.on('unload', callback => this.stop(false, callback))
.on('ready', () => this.resolve().then(() => this.initAdapter()).then(() => setImmediate(amain), e => this.Ef('Adapter Error, stop: %O', e)))
.on('objectChange', (id, obj) => obj && obj._id && objChange && setTimeout((id, obj) => objChange(id, obj), 0, id, obj))
.on('stateChange', (id, state) => setTimeout((id, state) => {
(state && stateChange && state.from !== 'system.adapter.' + this.ains ?
stateChange(id, state).catch(err => this.W(`Error in StateChange for ${id} = ${this.O(err)}`)) :
Promise.resolve())
.then(() => allStates && allStates(id, state).catch(e => this.W(`Error in AllStates for ${id} = ${this.O(e)}`)))
.then(() => states[id] = state);
}, 0, id, state));
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.Wf('Promise failed @ %O error: %o', get().join('; '), x);
return x;
}
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, val) {
if (!inDebug || curDebug > Number(inDebug))
return val !== undefined ? val : str;
return (inDebug ?
slog('info', `debug: ${str}`) :
slog('debug', str), val !== undefined ? val : str);
}
static Dr(str) {
if (!inDebug && curDebug > Number(inDebug))
return str;
else {
const s = this.f.apply(null, Array.prototype.slice.call(arguments, 1));
if (inDebug)
slog('info', `debug: ` + s);
else
slog('debug', s);
}
return str;
}
static Df(...str) {
if (!(!inDebug && curDebug > Number(inDebug))) {
str = this.f(...str);
return inDebug ? slog('info', 'debug: ' + str) : slog('debug', str);
}
}
static F() {
return util.format.apply(null, arguments);
}
static f() {
return util.format.apply(null, arguments).replace(/\n\s+/g, ' ');
}
static I(l, v) {
return (slog('info', l), v === undefined ? l : v);
}
static Ir(ret) {
slog('info', this.f.apply(null, Array.prototype.slice.call(arguments, 1)));
return ret;
}
static If() {
return slog('info', this.f.apply(null, arguments));
}
static Wf() {
return slog('warn', this.f.apply(null, arguments));
}
static Wr(ret) {
slog('warn', this.f.apply(null, Array.prototype.slice.call(arguments, 1)));
return ret;
}
static Er(ret) {
slog('error', this.f.apply(null, Array.prototype.slice.call(arguments, 1)));
return ret;
}
static W(l, v) {
return (slog('warn', l), v === undefined ? l : v);
}
static E(l, v) {
return (slog('error', l), v === undefined ? l : v);
}
static Ef() {
return slog('error', this.f.apply(null, arguments));
}
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;
}
static get debug() {
return inDebug;
}
static set debug(y) {
inDebug = y;
}
static get timer() {
return timer;
}
static set timer(y) {
timer = y;
}
static get messages() {
return messages;
}
static set messages(y) {
assert(typeof y === 'function', 'Error: messages handler not a function!');
messages = y;
}
// static get stateChange() {
// return stateChange;
// }
// static set stateChange(y) {
// stateChange = (assert(typeof y === "function", "Error: StateChange handler not a function!"), y);
// }
// static get allStates() {
// return allStates;
// }
// static set allStates(y) {
// allStates = (assert(typeof y === "function", "Error: StateChange handler not a function!"), y);
// }
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 debugLevel() {
return curDebug;
}
static set debugLevel(y) {
curDebug = y;
}
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 wait(time, arg) {
if (isNaN(Number(time)) || Number(time) < 0)
time = 0;
if (typeof arg === 'function') {
let args = Array.prototype.slice.call(arguments, 2);
return new Promise(res => setTimeout(r => res(arg.apply(null, args)), time));
}
return new Promise(res => setTimeout(res, time, arg));
}
*/
static async 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 async nextTick(x) {
return new Promise((res) => process.nextTick(() => res(x)));
}
static async resolve(x) {
return this.nextTick(x);
}
static async reject(x) {
await this.nextTick();
return Promise.reject(x);
}
static async 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 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 async pTimeout(pr, time, callback) {
const t = parseInt(time);
assert(typeof t === 'number' && t > 0, `pTimeout requires a positive number as second argument for the ms`);
let st = null;
assert(!callback || callback && typeof callback === 'function', `pTimeout requires optionally a function for callback as third argument`);
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 S(obj, level) {
return typeof obj === 'string' ? obj : this.O(obj, level);
}
static N(fun, ...args) {
return setImmediate.apply(null, [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, callback) { // dostop
if (stopping) return;
try {
if (adapter._onStop)
adapter._onStop(dostop);
} finally {
stopping = true;
if (timer) {
if (Array.isArray(timer))
timer.forEach(t => clearInterval(t));
else
clearInterval(timer);
timer = null;
}
}
this.I(`Adapter disconnected and stopped with dostop(${dostop}) and callback(${!!callback})`);
if (!callback) {
const x = dostop < 0 ? 0 : dostop || 0;
MyAdapter.Df('Adapter will exit now with code %s and method %s!', x, adapter && adapter.terminate ? 'adapter.terminate' : 'process.exit');
adapter && adapter.terminate ? adapter.terminate(x) : process.exit(x);
} else
try {
callback && callback();
} finally {
callback && callback();
}
}
static seriesOf(obj, promfn, delay) { // fun gets(item) and returns a promise
assert(typeof promfn === 'function', 'series(obj,promfn,delay) error: promfn is not a function!');
delay = parseInt(delay) || 0;
let p = Promise.resolve();
const nv = [],
f = delay > 0 ? (k) => p = p.then(() => promfn(k).then(res => this.wait(delay, nv.push(res)))) :
(k) => p = p.then(() => promfn(k));
for (const item of obj)
f(item);
return p.then(() => nv);
}
static seriesInOI(obj, promfn, delay) { // fun gets(item) and returns a promise
assert(typeof promfn === 'function', 'series(obj,promfn,delay) error: promfn is not a function!');
delay = parseInt(delay) || 0;
let p = Promise.resolve();
const nv = [],
f = delay > 0 ? (k) => p = p.then(() => promfn(k).then(res => this.wait(delay, nv.push(res)))) :
(k) => p = p.then(() => promfn(k));
for (const item in obj)
f(obj[item]);
return p.then(() => nv);
}
static seriesIn(obj, promfn, delay) { // fun gets(item,object) and returns a promise
assert(typeof promfn === 'function', 'series(obj,promfn,delay) error: promfn is not a function!');
delay = parseInt(delay) || 0;
let p = Promise.resolve();
const nv = [],
f = delay > 0 ? (k) => p = p.then(() => promfn(k).then(res => this.wait(delay, nv.push(res)))) :
(k) => p = p.then(() => promfn(k));
for (const item in obj)
f(item, obj);
return p.then(() => nv);
}
static c2p(f, b) {
const p = util.promisify(f);
return b ? p.bind(b) : p;
}
/*
static c1p(f) {
assert(typeof f === 'function', 'c1p (f) error: f is not a function!');
return function () {
const args = Array.prototype.slice.call(arguments);
return new Promise(res => (args.push((result) => res(result)), f.apply(this, args)));
};
}
static c1pe(f) { // one parameter != null = error
assert(typeof f === 'function', 'c1pe (f) error: f is not a function!');
return function () {
const args = Array.prototype.slice.call(arguments);
return new Promise((res, rej) => (args.push((result) => !result ? res(result) : rej(result)), f.apply(this, args)));
};
}
static retry(nretry, fn, arg, wait) {
assert(typeof fn === "function", "retry (,fn,) error: fn is not a function!");
nretry = parseInt(nretry);
nretry = isNaN(nretry) ? 2 : nretry;
return Promise.resolve(fn(arg)).catch(err => nretry <= 0 ? this.reject(err) : this.wait(wait > 0 ? wait : 0).then(() => this.retry(nretry - 1, fn, arg, wait)));
}
static
while ( fw, fn, time) {
assert(typeof fw === "function" && typeof fn === "function", "retry (fw,fn,) error: fw or fn is not a function!");
time = parseInt(time) || 0;
return !fw() ? this.resolve(true) :
fn().then(() => true, () => true)
.then(() => this.wait(time))
.then(() => this.while(fw, fn, time));
}
static repeat( nretry, fn, arg, len) {
assert(typeof fn === "function", "repeat (,fn,) error: fn is not a function!");
nretry = parseInt(nretry) || 0;
return fn(arg)
.then(res => this.reject(res))
.catch(res => nretry <= 0 ? this.resolve(res) : this.wait(len > 0 ? len : 0).then(() => this.repeat(nretry - 1, fn, arg)));
}
*/
static async exec(command) {
// assert(typeof command === "string", "exec (fn) error: fn is not a string!");
const istest = command.startsWith('!');
return new Promise((resolve, reject) => {
try {
exec(istest ? command.slice(1) : command, (error, stdout, stderr) => {
if (istest && error) {
error[stderr] = stderr;
return reject(error);
}
resolve(stdout);
});
} catch (e) {
reject(e);
}
});
}
/*
static request(opt, value, transform) {
if (typeof opt === "string")
opt = this.url(opt.trim());
if (!(opt instanceof url.Url)) {
if (this.T(opt) !== "object" || !opt.hasOwnProperty("url"))
return Promise.reject(this.W(`Invalid opt or Url for request: ${this.O(opt)}`));
opt = this.url(opt.url, opt);
}
if (opt.json)
if (opt.headers) opt.headers.Accept = "application/json";
else opt.headers = {
Accept: "application/json"
};
if (!opt.protocol)
opt.protocol = "http:";
const fun = opt.protocol.startsWith("https") ? https.request : http.request;
// this.D(`opt: ${this.O(opt)}`);
return new Promise((resolve, reject) => {
let data = new Buffer(""),
res;
const req = fun(opt, function (result) {
res = result;
// MyAdapter.D(`status: ${MyAdapter.O(res.statusCode)}/${http.STATUS_CODES[res.statusCode]}`);
res.setEncoding(opt.encoding ? opt.encoding : "utf8");
if (MyAdapter.T(opt.status) === "array" && opt.status.indexOf(res.statusCode) < 0)
return reject(MyAdapter.D(`request for ${url.format(opt)} had status ${res.statusCode}/${http.STATUS_CODES[res.statusCode]} other than supported ${opt.status}`));
res.on("data", chunk => data += chunk)
.on("end", () => {
// res.removeAllListeners();
// req.removeAllListeners();
if (MyAdapter.T(transform) === "function")
data = transform(data);