forked from iobroker-community-adapters/ioBroker.broadlink2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
broadlink2.js
951 lines (905 loc) · 30.3 KB
/
broadlink2.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
/**
* iobroker bmw Adapter
* (c) 2016- <frankjoke@hotmail.com>
* MIT License
*/
// jshint node:true, esversion:6, strict:true, undef:true, unused:true
"use strict";
const
Broadlink = require('./broadlink_fj'),
A = require('@frankjoke/myadapter').MyAdapter,
// utils = require('./lib/utils'),
// adapter = utils.Adapter('broadlink2'),
assert = require('assert');
const scanList = {},
tempName = '.Temperature',
humName = '.Humidity',
lightName = '.Light',
airQualityName = '.AirQuality',
noiseName = '.Noise',
learnRf = 'RF',
learnIr = '',
learnName = '._Learn',
sendName = '._SendCode',
sceneName = '_SendScene',
scenesName = 'Scenes',
statesName = 'States',
learnedName = '.L.',
scanName = '_NewDeviceScan',
reachName = '._notReachable',
codeName = "CODE_",
reCODE = /^CODE_|^/,
reIsCODE = /^CODE_[a-f0-9]{16}/,
defaultName = '_Rename_learned_';
let brlink, adapterObjects = [],
states = {};
// eslint-disable-next-line no-unused-vars
A.init(module, 'broadlink2', main); // associate adapter and main with MyAdapter
//A.I('Adapter starting...');
// eslint-disable-next-line
A.objChange = function (obj, val) { // This is needed for name changes
// A.I(A.F(obj,' =O> ',val));
val = val || A.D(' objChange val not defined');
if (typeof obj === 'string' && obj.indexOf(learnedName) > 0)
return A.getObject(obj)
.then(oobj => {
A.Df('get object %O gets changed to %O', oobj, obj);
const nst = oobj.common,
ncn = nst.name,
nid = ncn.replace(A.adapter.FORBIDDEN_CHARS, '_'),
dev = obj.split('.'),
fnn = dev.slice(2, -1).concat(nid).join('.');
if (nid === dev[4] || nid.startsWith(defaultName)) // no need to rename!
return null;
if (!A.states[fnn] ? (!oobj.native.code ? A.W(`Cannot rename to ${oobj.common.name} because it does not have a learned code: ${obj}`, true) : false) :
A.W(`Cannot rename to ${ncn} because the name is already used: ${obj}`, true)) {
oobj.common.name = dev[4];
return A.setObject(obj, oobj)
.catch(e => A.W(`rename back err ${e} on ${A.O(oobj)}!`));
}
nst.id = (dev[2] + learnedName + nid);
nst.native = oobj.native;
// nst.val = codeName + oobj.native.code;
if (nid !== dev[4])
return A.makeState(nst, false, true)
.then(() => A.removeState(A.I(`rename ${obj} to ${fnn}!`, obj)).catch(() => true));
}).then(() => A.wait(20))
// .then(() => getObjects())
.catch(err => A.W(`objChange error: ${obj} ${err}`));
return A.resolve();
};
function sendCode(device, value) {
let buffer = new Buffer(value.replace(reCODE, ''), 'hex'); //var buffer = new Buffer(value.substr(5), 'hex'); // substr(5) removes CODE_ from string
return device.sendVal(buffer).then(x => device.name + ' sent ' + value + ', ' + x);
// return Promise.resolve(A.D('sendData to ' + device.name + ', Code: ' + value));
}
// eslint-disable-next-line complexity
A.stateChange = function (id, state) {
A.Df('Change %s to %O', id, state);
let thisDevice;
function startLearning(name, type) {
thisDevice = scanList[name];
assert(!!thisDevice, `wrong name "${name}" in startLearning`);
if (thisDevice.learning) return Promise.reject(A.W(`Device ${name} is still in learning mode and cannot start it again!`));
A.I(`Start ${type}-learning for device: ${name}`);
return A.makeState(name, thisDevice.learning = true, true)
.then(() => thisDevice.learn(type === learnRf))
.then(l => {
if (l.data) {
const hex = l.data;
return A.getObjectList({
startkey: A.ain + thisDevice.name + learnedName,
endkey: A.ain + thisDevice.name + learnedName + '\u9999'
})
.catch(() => ({
rows: []
}))
.then(res => {
for (let i of res.rows)
if (i.doc.native.code === hex) // ? i.doc.common.name
return A.reject(i.doc.common.name + ':' + i.doc._id);
return true;
})
.then(() => A.makeState({
id: thisDevice.name + learnedName + codeName + hex,
name: `${defaultName} ${type} ${A.dateTime()}`,
write: true,
role: 'button',
type: typeof true,
native: {
code: hex
}
}, false, A.I(`Learned new ${type} Code ${thisDevice.name} (hex): ${hex}`, true)),
nam => A.I(`Code alreadly learned from: ${thisDevice.name} with ${nam}`))
.catch(err => A.W(`learning makeState error: ${thisDevice.name}} ${err}`))
.then(() => A.wait(200));
}
return Promise.resolve();
})
.then(() => A.I(`Stop learning ${type} for ${name}!`), () => A.I(`Stop learning ${type} for ${name}!`))
.then(() => A.makeState(name, false, true))
.then(A.nop, A.nop);
}
function checkT1(device, state, id) {
if (id.endsWith('._setTime'))
return device.setTime();
if (id.endsWith('.autoMode'))
return device.setMode(state.val);
if (id.endsWith('.loopMode'))
return device.setMode(undefined, state.val);
if (id.endsWith('.sensor'))
return device.setMode(undefined, undefined, state.val);
if (id.endsWith('.thermostatTemp'))
return device.setTemp(state.val);
if (id.endsWith('.remoteLock'))
return device.setPower(undefined, state.val);
if (id.endsWith('.power'))
return device.setPower(state.val);
for (let e of ['.loopMode', '.sensor', '.osv', '.dif', '.svh', '.svl', '.roomTempAdj', '.fre', '.poweron'])
if (id.endsWith(e))
return device.setAdvanced(e.slice(1), state.val);
for (let e of ['.startHour', '.startMinute', '.temp'])
if (id.endsWith(e)) {
let i = id.split('.');
device._val[i[1]][parseInt(i[2].slice(1)) - 1][i[3]] = state.val;
return device.setSchedule(id, state.val);
}
return A.reject(A.Wf("checkT1 don't know how to set %s of %s to %O", id, device.name, state.val));
}
// A.D(`stateChange of "${id}": ${A.O(state)}`);
if (!state.ack) {
if (id.startsWith(A.ain))
id = id.slice(A.ain.length);
let idx = id.split('.'),
id0 = idx[0];
if (id0 === scanName && idx.slice(-1)[0] === scanName) return deviceScan();
if (id0 === sceneName && idx.slice(-1)[0] === sceneName) {
const scene = state.val;
state.val = true;
return sendScene(scene, state);
}
// A.D(`Somebody (${state.from}) id0 ${id0} changed ${id} of "${id0}" to ${A.O(state)}`);
if (id0 === scenesName)
return A.getObject(id)
.then((obj) =>
obj && obj.native && obj.native.scene ?
sendScene(obj.native.scene, state) :
Promise.reject(A.D(`Invalid command "${id}" in scenes`)));
if (id0 === statesName)
return A.getObject(id)
.then((obj) =>
obj && obj.native && obj.native.state ?
sendState(obj.native.state, state.val) :
Promise.reject(A.D(`Invalid command "${id}" in states`)));
let device = scanList[id0];
if (!device) return Promise.reject(A.W(`stateChange error no device found: ${id} ${A.O(state)}`));
switch (device.type.slice(0, 2)) {
case 'SP':
device.setVal(A.parseLogic(state.val));
A.I(`Change ${id} to ${state.val}`);
return Promise.resolve(device.oval = state.val);
case 'RM':
if (id.endsWith(sendName))
return state.val.startsWith(codeName) ? sendCode(device, state.val) :
Promise.reject(A.W(`Code to send to ${id0} needs to start with ${codeName}`));
if (id.endsWith(learnName + learnIr))
return startLearning(id0, learnIr);
if (id.endsWith(learnName + learnRf))
return startLearning(id0, learnRf);
return reIsCODE.test(state.val) && sendCode(device, state.val) ||
A.getObject(id)
.then((obj) =>
obj && obj.native && obj.native.code ?
setState(obj.common.name).then(() => sendCode(device, obj.native.code)) :
Promise.reject(A.W(`cannot get code to send for: ${id}=${id0} ${A.O(state)}`)));
case 'T1':
// eslint-disable-next-line no-fallthrough
return checkT1(device, state, id).then(() => device.getAll()).then(x => (A.Ir(x, 'getall returned %O after %s', x, id) && x.here && device.update) ? device.update(x) : null).catch(A.pE);
default:
return Promise.reject(A.W(`stateChange error invalid id type: ${id}=${id0} ${A.O(state)}`));
}
} else return A.resolve();
};
function deviceScan() {
if (!brlink) return Promise.reject(A.W(`No current driver to start discover!`));
if (brlink.scanning) return Promise.reject(A.W(`Scan operation in progress, no new scan can be started until it finished!`));
return A.makeState({
id: scanName,
write: true,
role: 'button',
type: typeof true,
}, brlink.scanning = true, true)
.then(() => brlink.discover())
.then(() => A.wait(2000)) // 6s for the scan of ip' should be OKs
.then(() => A.makeState(scanName, brlink.scanning = false, true))
.catch(err => A.W(`Error in deviceScan: ${brlink.scanning = false, A.O(err)}`));
}
function sendScene(scene, st) {
const s = A.T(scene, []) ? A.trim(scene) : A.T(scene, '') ? A.trim(scene.split(',')) : `error in scene: neither a string nor an Array!: ${A.O(scene)}`;
const sn = s.map(ss => A.trim(ss) === parseInt(ss).toString() ? parseInt(ss) : A.trim(ss));
return A.seriesOf(sn, i => {
if (typeof i === 'number')
return A.wait(i);
const mm = i.match(/^\s*(\d+)\s*\(\s*(\S+)\s*\)\s*(\d*)\s*$/);
if (mm)
return A.repeat(mm[1], () => sendScene([mm[2]], st).then(() => A.wait(mm[3] ? mm[3] : 300)));
if (i.split('=').length === 2) {
let s = A.trim(i.split('='));
i = s[0];
st.val = s[1];
} else st.val = true;
const f = adapterObjects.filter(x => x.common.name === i);
if (f.length === 1)
i = f[0]._id;
else if (f.length > 1)
A.W(`Multiple states with name '${i}: ${f.map(x => x._id)}`);
if (i.startsWith(A.ain))
i = i.slice(A.ain.length);
const j = A.trim(i.split('.')),
id = j[0],
code = j[1],
dev = scanList[id],
typ = dev ? dev.type.slice(0, 2) : '';
if (dev && typ === 'RM' && code.startsWith(codeName))
return sendCode(scanList[id], code);
if (typ === 'RM' || typ == 'SP' || i.startsWith(scenesName + '.'))
return A.stateChange(i, st);
if (i.startsWith(statesName + '.'))
return A.stateChange(i, {
val: st.val
});
return A.getState(i).then(() =>
A.setForeignState(i, st, false),
(err) => A.W(`id ${i[0]} not found in scene ${scene} with err: ${A.O(err)}`));
}, 100);
}
A.messages = (msg) => {
if (A.T(msg.message) !== 'string')
return A.W(`Wrong message received: ${A.O(msg)}`);
const st = {
val: true,
ack: false,
from: msg.from
};
let id = msg.message.startsWith(A.ain) ? msg.message.trim() : A.ain + (msg.message.trim());
let ids, idx, code;
switch (msg.command) {
case 'switch_off':
st.val = false;
/* falls through */
case 'switch_on':
case 'send':
return A.getObject(id)
.then(obj => obj.common.role === 'button' || (obj.common.role === 'switch' && msg.command.startsWith('switch')) ?
A.stateChange(id, st) :
Promise.reject(A.W(`Wrong id or message ${A.O(msg)} id = ${A.O(obj)}`)),
err => Promise.reject(err))
.then(() => A.D(`got message sent: ${msg.message}`));
case 'send_scene':
return sendScene(msg.message, st);
case 'send_code':
if (msg.message.startsWith(A.ain))
msg.message = msg.message.slice(A.ain.length);
ids = msg.message.split('.');
code = ids[1];
id = ids[0];
if (!id.startsWith('RM:') || !scanList[id] || !code.startsWith(codeName))
return Promise.reject(A.D(`Invalid message "${msg.message}" for "send" to ${id}${sendName}`));
return Promise.resolve(A.D(`Executed on ${id} the message "${msg.message}"`), sendCode(scanList[id], code));
case 'get':
return A.getState(id);
case 'switch':
idx = A.split(msg.message, '=');
if (idx.length !== 2 && !idx.startsWith('SP:'))
return Promise.reject(A.D(`Invalid message to "switch" ${msg.message}" to ${idx}`));
st.val = A.parseLogic(idx[1]);
return A.stateChange(idx[0], st);
default:
return Promise.reject(A.D(`Invalid command "${msg.command}" received with message ${A.O(msg)}`));
}
};
let discoverAll = 0;
let firsttime = true;
function doPoll() {
let na = [];
discoverAll = discoverAll >= 9 ? 0 : ++discoverAll;
return A.seriesOf(A.obToArray(scanList), device => {
if (!device.getAll || device.dummy) {
if (!device.searchc) {
device.searchm = 2;
device.searchc = 1;
}
if (++device.searchc % device.searchm === 0) {
na.push(device.host);
if (device.searchm < 256) device.searchm *= 2;
}
return A.resolve();
}
return device.getAll().then(x => {
if (firsttime)
A.Dr(x, 'Device %s returned %O', device.name, x);
if (x && x.here && device.update) {
return device.update(x);
}
if (x && x.here) {
x.noUpdateFunction = 'do not know how to update';
} else if (!x)
x = {
here: false
};
// A.Ir(x, 'Device %s will reject %O', device.name, x);
return A.reject(x);
}).catch(e => {
A.Df('device %s not reachable, waiting for it again %O', device.name, e);
if (device.lastResponse && device.lastResponse < Date.now() - 1000 * 60 * 5) {
if (device.close)
device.close();
A.W(`Device ${device.name} not reachable, switched it off and will search for it every while.`);
return A.makeState(device.name + reachName, device.unreach = true, true);
}
return A.resolve();
});
}, 1).catch(err => A.W(`Error in polling: ${A.O(err)}`)).then(() => firsttime = false).then(() => na.length ? brlink.discover(discoverAll ? na : undefined) : null);
}
function setState(name) {
name = name.trim();
let str = null;
for (let k in states) {
const st = states[k];
let where = A.includes(st.on, name) ? st.on : A.includes(st.off, name) ? st.off : null;
if (where) {
str = {
state: st,
index: (where === st.off ? -1 : st.on.indexOf(name))
};
break;
}
}
if (!str)
return Promise.resolve();
if (str.index < 0) // was found in off so switch state off!
return A.changeState(str.state.id, false, true);
return A.changeState(str.state.id, str.state ? true : str.index);
}
function sendState(state, val) {
var send = A.T(val, 0) && state.on[val];
if (A.T(val, true))
send = val ? state.on[0] : state.off[0];
if (state.mult && val > 9) {
const vals = val.toString().split('').map(x => parseInt(x));
return A.seriesOf(vals, num => sendState(state, num), 300);
}
const sobj = adapterObjects.filter(x => x.common.name === send);
if (sobj.length > 1)
A.W(`sendState error: multiple commands for name ${send}, ill use only first instance: ${sobj[0]._id}!`);
return (sobj && sobj.length ? A.getObject(sobj[0]._id.slice(A.ain.length)) : Promise.resolve(null)).catch(() => null)
.then(obj => {
if (!obj)
return A.W(`sendState could not find command or scene named '${send}'`);
return A.stateChange(obj._id, {
val: true,
ack: false
});
})
.then(() => A.makeState(state.id, val, true))
.catch(A.pE);
}
function updateValues(device, val, values) {
return A.seriesOf(values, (item) => {
let i = Object.assign({}, item);
const name = i.name;
delete i.name;
i.id = device.host.iname + (i.id || i.id === '' ? i.id : '.' + name);
i.write = !!i.write;
let v = val[name];
i.native = {
host: device.host
};
if (i.type === 'json') {
i.type = 'string';
v = JSON.stringify(v);
}
if (v !== undefined)
return (typeof i.fun === 'function' ? i.fun(device, i, v) : A.makeState(i, v, true)).catch(A.pE);
}).catch(e => e);
}
let rename = [];
function findName(name) {
for (let i of rename)
if (i[0] === name)
return i[1];
return null;
}
function createStatesDevice(device) {
function setp(dn) {
return [{
id: dn + '.startHour',
name: 'startHour',
write: true,
type: typeof 1,
role: "value",
}, {
id: dn + '.startMinute',
name: 'startMinute',
write: true,
type: typeof 1,
role: "value",
}, {
id: dn + '.temp',
name: 'temp',
write: true,
type: typeof 1.0,
role: "value.temperature",
}];
}
let x = device.name;
return A.makeState({
id: x + reachName,
write: false,
role: 'indicator.unreach',
type: typeof true,
native: {
host: device.host
}
}, device.unreach = false, true)
.then(() => {
switch (device.typ) {
case 'SP':
device.oval = undefined;
device.update = (val) => {
// A.If('Should update %s with %O', device.host.name, val);
return Promise.resolve().then(() => {
if (val.state !== undefined && device.oval !== val.state) {
if (device.oval !== undefined)
A.I(`Switch ${device.host.iname} changed to ${val.state} most probably manually!`);
device.oval = val.state;
return A.makeState({
id: device.host.iname,
write: true,
role: 'switch',
type: typeof true,
native: {
host: device.host
}
}, val.state, true);
}
return Promise.resolve();
})
.then(() => updateValues(device, val, [{
name: 'energy',
id: '.CurrentPower',
role: "level",
write: false,
unit: "W",
type: typeof 1.1
}, {
name: 'nightlight',
id: '.NightLight',
role: "switch",
write: true,
type: typeof true
}, {
name: 'state',
role: "switch",
type: typeof true
}]))
.catch(e => A.Wf('Update device %s Error: %O', device.host.name, e));
};
break;
case 'S1':
device.update = (val) => {
return A.seriesOf(A.ownKeysSorted(val), (i) => A.makeState({
id: device.host.iname + (i === 'here' ? '' : '.' + i),
write: false,
role: 'value',
type: i === 'here' ? typeof true : typeof 1,
native: {
host: device.host
}
},
val[i],
true), 1)
.catch(e => A.Wf('Update device %s Error: %O', device.host.name, e));
};
break;
case 'RM':
device.ltemp = undefined;
device.update = (val) => {
// A.If('Should update %s with %O', device.host.name, val);
return Promise.resolve(updateValues(device, val, [{
id: tempName,
role: "temperature",
name: 'temperature',
write: false,
unit: "°C",
type: typeof 1.1
}]));
};
A.makeState({
id: x,
role: "value",
write: true,
type: typeof true,
}, false, true)
.then(() => A.makeState({
id: x + learnName + learnIr,
write: true,
role: 'button',
type: typeof true,
}, false, true))
.then(() => A.makeState({
id: x + sendName,
role: "text",
write: true,
type: typeof ''
}, ' ', true))
.then(() => device.type === 'RMP' ? A.makeState({
id: x + learnName + learnRf,
write: true,
role: 'button',
type: typeof true,
}, false, true) : null);
break;
case 'T1':
device.setTime();
device.update = (val) => {
// A.If('Should update %s with %O', device.host.name, val);
return A.makeState({
id: x + '._setTime',
type: typeof true,
write: true,
role: "button",
}, true, true)
.then(() => updateValues(device, val, [{
id: '',
name: 'roomTemp',
type: typeof 1.1,
role: "value.temperature",
unit: "°C",
native: {
host: device.host
}
}, {
name: 'thermostatTemp',
write: true,
type: typeof 1.1,
role: "value.temperature",
unit: "°C"
}, {
name: 'roomTempAdj',
write: true,
type: typeof 1.1,
role: "value.temperature",
unit: "°C"
}, {
name: 'externalTemp',
type: typeof 1.1,
role: "value.temperature",
unit: "°C"
}, {
name: 'roomTemp',
type: typeof 1.1,
role: "value.temperature",
unit: "°C"
}, {
name: 'remoteLock',
type: typeof true,
write: true,
role: "switch",
}, {
name: 'power',
type: typeof true,
write: true,
role: "switch",
}, {
name: 'active',
type: typeof true,
write: true,
role: "switch",
}, {
name: 'time',
type: typeof '',
role: "value",
}, {
name: 'autoMode',
type: typeof 0,
role: "value",
min: 0,
max: 1,
states: "0:manual;1:auto",
write: true,
}, {
name: 'loopMode',
type: typeof 0,
write: true,
role: "value",
min: 1,
max: 3,
states: "1:weekend starts Saturday;2:weekend starts Sunday;3:All days are weekdays",
}, {
name: 'sensor',
type: typeof 0,
write: true,
role: "value",
min: 0,
max: 2,
states: "0:internal;1:external;2:internalControl-externalLimit"
}, {
name: 'weekday',
fun: (device, i, v) => {
let d = 0;
return A.seriesOf(v, (x) => {
let dn = '.weekday.s' + ++d;
return updateValues(device, x, setp(dn));
}, 0);
}
}, {
name: 'weekend',
fun: (device, i, v) => {
let d = 0;
return A.seriesOf(v, (x) => {
let dn = '.weekend.s' + ++d;
return updateValues(device, x, setp(dn));
}, 0);
}
}, {
name: 'osv',
type: typeof 0.1,
write: true,
role: "value.temperature",
unit: "°C",
min: 5,
max: 99
}, {
name: 'dif',
type: typeof 0.1,
write: true,
role: "value.temperature",
unit: "°C",
min: 1,
max: 9
}, {
name: 'svh',
type: typeof 0.1,
write: true,
role: "value.temperature",
unit: "°C",
min: 5,
max: 99
}, {
name: 'svl',
type: typeof 0.1,
write: true,
role: "value.temperature",
unit: "°C",
min: 5,
max: 99
}]))
.catch(e => A.Wf('Update device %s Error: %O', device.host.name, e));
};
break;
case 'A1':
device.update = (val) =>
Promise.resolve()
.then(() => updateValues(device, val, [{
id: '',
name: 'temperature',
type: typeof 1.1,
role: "value.temperature",
write: false,
unit: "°C",
}, {
id: humName,
name: 'humidity',
type: typeof 1.1,
role: "value.humidity",
write: false,
min: 0,
max: 100,
unit: "%"
}, {
id: lightName,
name: 'light',
type: typeof 0,
role: "value",
min: 0,
max: 3,
states: "0:finster;1:dunkel;2:normal;3:hell"
}, {
id: airQualityName,
name: 'air_quality',
type: typeof 0,
role: "value",
min: 0,
max: 3,
states: "0:sehr gut;1:gut;2:normal;3:schlecht"
}, {
id: noiseName,
name: 'noise',
type: typeof 0,
role: "value",
min: 0,
max: 3,
states: "0:ruhig;1:normal;2:laut;3:sehr laut"
}]))
.catch(e => A.Wf('Update device %s Error: %O', device.host.iname, e));
break;
default:
A.Wf('Unknown %s with %O', device.host.iname, device.host);
}
return true;
}).catch(A.pE);
}
function main() {
function renId(id, oldid, newid) {
if (id.startsWith(A.ain + oldid + '.'))
return A.ain + newid + '.' + id.slice((A.ain + oldid + '.').length);
return id;
}
let didFind = [],
notFound = [];
if (!A.C.new)
A.C.new = '';
if ((A.debug = A.C.new.endsWith('!')))
A.C.new = A.C.new.slice(A.D(`Debug mode on!`, 0), -1);
let add = A.C.new.split(',').map(x => x.split('=').map(s => s.trim()));
if (add.length === 1 && add[0].length === 1)
add = [];
if (!A.C.rename)
A.C.rename = '';
rename = A.C.rename.split(',').map(x => x.split('=').map(s => s.trim()));
if (rename.length === 1 && rename[0].length === 1)
rename = [];
rename = rename.map(x => [x[0], x[1].replace(A.adapter.FORBIDDEN_CHARS, '_')]);
A.If('Devices to add: %s', add, add.map(x => x.join('=')).join(','));
A.If('Devices to rename: %s', rename.map(x => x.join('=')).join(','));
brlink = new Broadlink(add);
brlink.on("deviceReady", device => {
const typ = device.type.slice(0, 2);
device.typ = typ;
device.removeAllListeners('error');
device.on('error', A.W);
// A.If('what is name of %O', device);
let x = findName(device.host.name);
device.host.iname = x = device.name = x ? x : device.host.name;
// A.If('found device %s and named %s, in objects: %O', device.host.name, x, A.objects[device.host.name]);
// A.getObject(device.host.name).then(res => A.If('got object %s: %O', device.host.name, res)).catch(A.pE);
if (scanList[x] && !scanList[x].dummy)
return A.Wf(`Device found already: %s with %O`, x, device.host);
A.If('Device %s dedected: address=%s, mac=%s, typ=%s, id=%s devtype=%s%s', x, device.host.address, device.host.mac, device.host.type, device.host.devhex, device.host.devname,
device.host.name === device.name ? '' : ', originalName=' + device.host.name);
scanList[x] = device;
});
A.unload = () => brlink.close.bind(brlink)(A.I('Close all connections...'));
// A.If('objects: %O', A.ownKeysSorted(A.objects));
A.D('Config IP-Address end to remove: ' + A.C.ip);
A.seriesOf(A.C.scenes, scene =>
A.makeState({
id: scenesName + '.' + scene.name.trim(),
write: true,
role: 'button',
type: typeof true,
native: {
scene: scene.scene
}
}), 10)
.then(() => brlink.start15001())
.then(() => deviceScan(A.I('Discover Broadlink devices for 10sec on ' + A.ains)))
.then(() => A.seriesOf(A.C.switches, state => {
let name = state.name && state.name.trim(),
on = state.on && state.on.trim(),
off = state.off && state.off.trim();
assert(name && on, `Invalid State without name or 'on' string: ${A.O(state)}`);
if (!off || off === '')
off = null;
const mult = (off === '+');
if (mult)
off = null;
on = A.trim(A.split(on, ','));
const option = {
id: statesName + '.' + name,
name: name,
type: off ? typeof true : typeof 0,
role: off ? "switch" : "level",
write: true,
};
if (!off) {
option.min = 0;
option.max = mult ? 9999 : on.length - 1;
if (mult)
option.states = null;
else
option.states = on.map((s, i) => `${i}:${s.trim()}`).join(';');
}
option.native = {
state: {
id: option.id,
name: option.name,
on: on,
off: off ? A.trim(A.split(off, ',')) : null,
mult: mult
}
};
if (states[option.name])
return Promise.resolve(A.W(`double state name will be ignored: ${option.name}`));
states[option.name] = option.native.state;
return A.makeState(option, undefined, true);
}, 1).catch(err => A.W(`genState generation error: ${err}`)))
.then(() => A.seriesInOI(scanList, dev => {
let oname = dev.host.name;
let iname = dev.name;
let oobj, iobj;
return A.getObject(oname).then(x => oobj = x, A.nop)
.then(() => A.getObject(iname)).then(x => iobj = x, A.nop)
.then(() => {
if (oname != iname) {
if (oobj && iobj) {
A.Wf(`Got item which had original name of %s and new name of %s,\n please delete new one to get old renamed or old one if you don't need it's items anymore.`, oname, iname);
// A.getObjects(oname).then(res => A.If('olist =%O', res.map(x => x.id)));
} else if (oobj) {
A.If('Should rename %s to %s!', oname, iname);
return A.seriesOf(A.ownKeys(A.objects), on => {
let ob = A.objects[on];
let ret = Promise.resolve();
if (ob._id.startsWith(A.ain + oname + '.') && ob.native && ob.native.code) {
let ns = Object.assign({}, ob.common);
ns.name = renId(ns.name, oname, iname);
ns.id = renId(ob._id, oname, iname);
ns.native = ob.native;
ret = A.makeState(ns, false, true);
}
return ret.then(() => A.delState(ob._id)).then(() => A.delObject(ob._id)).catch(A.pE);
}, 0);
}
}
})
.then(() => createStatesDevice(dev));
}, 0))
.then(() => {
for (let i of A.ownKeys(A.objects))
if (i.startsWith(A.ain))
adapterObjects.push(A.objects[i]);
return null;
})
.then(() => A.Df('%s has %d old states!', A.name, adapterObjects.length))
.then(() => didFind = Object.keys(scanList))
.then(() => A.seriesOf(A.obToArray(A.objects).filter(x => x._id.startsWith(A.ain) && x.native && x.native.host), dev => {
let id = dev.native.host.name; // dev._id.slice(A.ain.length);
if (id && !findName(id) && !scanList[id] && dev._id === A.ain + dev.common.name && dev.common.name.indexOf('.') < 0) {
// !id.endsWith(learnName + learnRf) && !id.endsWith(learnName + learnIr)) {
// A.If('found %s', id);
let device = {
name: id,
fun: Promise.reject,
host: dev.native.host,
dummy: true
};
if (brlink.getDev(dev.native.host.mac)) {
device = brlink.getDev(dev.native.host.mac);
A.Wf('seems that device %s got renamed to %s! You may delete old device and change your scripts!', id, device.name);
} else {
A.W(`device ${id} not found, please rescan later again or delete it! It was: ${A.obToArray(device.host)}`);
scanList[id] = device;
notFound.push(id);
}
}
return Promise.resolve(true);
}, 1))
.then(() => doPoll())
.then(() => A.makeState({
id: sceneName,
write: true,
role: 'text',
type: typeof '',
}, ' ', true))
.then(() => {
const p = parseInt(A.C.poll);
if (p) {
setInterval(doPoll, p * 1000);
A.D(`Poll every ${p} secods.`);
}
})
.then(() => (A.I(`${A.ains} started and found ${didFind.length} devices named '${didFind.join("', '")}'.`),
notFound.length > 0 ? A.I(`${notFound.length} were not found: ${notFound}`) : null), e => A.W(`Error in main: ${e}`))
.catch(e => A.W(`Unhandled error in main: ${e}`));
}