-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
main.js
696 lines (599 loc) · 24 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
/**
*
* ioBroker hs100 Adapter
*
* (c) 2014-2020 arteck <arteck@outlook.com>
*
* MIT License
*
*/
'use strict';
const utils = require('@iobroker/adapter-core');
const {Client} = require('tplink-smarthome-api');
const client = new Client({
defaultSendOptions: {timeout: 20000, transport: 'tcp'},
});
const MAX_POWER_VALUE = 10 * 1000; // max value for power consumption: 10 kW
let interval = 0;
let _requestInterval = null;
class hs100Controll extends utils.Adapter {
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
constructor(options) {
super({
...options,
name: 'hs100',
});
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));
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
this.setState('info.connection', false, true);
await this.initialization();
await this.create_state();
this.getInfos();
}
/**
* Is called when adapter shuts down - callback has to be called under any circumstances!
* @param {() => void} callback
*/
onUnload(callback) {
try {
if (_requestInterval) clearInterval(_requestInterval);
this.log.info('cleaned everything up...');
this.setState('info.connection', false, true);
callback();
} catch (e) {
callback();
}
}
/**
* Is called if a subscribed object changes
* @param {string} id
* @param {ioBroker.Object | null | undefined} obj
*/
onObjectChange(id, obj) {
if (obj) {
// The object was changed
this.log.info(`object ${id} changed: ${JSON.stringify(obj)}`);
} else {
// The object was deleted
this.log.info(`object ${id} deleted`);
}
}
/**
* Is called if a subscribed state changes
* @param {string} id
* @param {ioBroker.State | null | undefined} state
*/
onStateChange(id, state) {
if (state) {
// The state was changed
const tmp = id.split('.');
const dp = tmp.pop();
const idx = tmp.pop();
const ip = idx.replace(/[_\s]+/g, '.');
this.setDevice(ip, dp, state);
this.log.debug(`stateID ${id} changed: ${state.val} (ack = ${state.ack})`);
} else {
// The state was deleted
this.log.info(`state ${id} deleted`);
}
}
async setDevice(ip, dp, state) {
try {
const device = await client.getDevice({host: ip});
if (device.model.search(/LB/i) != -1) {
const lightstate = device.sysInfo.light_state;
if (state && state.ack != null) {
if (!state.ack) {
if (dp == 'state') {
device.setPowerState(state.val).catch(err => {
this.log.warn('setPowerState Socket connection Timeout : ' + ip);
});
} else {
//findAndReplace(lightstate, dp, state.val);
device.lighting.setLightState(lightstate).catch(err => {
this.log.warn('setLightState Socket connection Timeout : ' + ip);
});
}
}
}
} else {
if (state && !state.ack) {
if (dp == 'state') {
device.setPowerState(state.val).catch(err => {
this.log.warn('LB setPowerState Socket connection Timeout : ' + ip);
});
} else {
if (dp == 'ledState') {
device.setLedState(state.val).catch(err => {
this.log.warn('LB setLedState Socket connection Timeout : ' + ip);
});
}
}
}
}
} catch (error) {
this.log.warn(`Info Message setDevice for IP ${ip} : ${error.stack}`);
}
}
async getInfos() {
this.log.debug(`get Information`);
const devices = this.config.devices;
try {
for (const i in devices) {
if (devices[i].active) {
this.updateDevice(devices[i]);
}
}
if (!_requestInterval) {
_requestInterval= setInterval(async () => {
await this.getInfos();
}, interval);
}
} catch (err) {
this.log.error('getInfosError ' + JSON.stringify(err));
}
}
async updateDevice(device) {
let hs_state;
const ip = device.ip;
const dev_name = device.name;
const ip_state = await this.ip_replace(ip);
try {
const result = await client.getDevice({host: ip});
if (result) {
const hs_lastupdate = Number(Date.now());
const hs_model = await this.hs_all_info(result,ip_state);
if (hs_model.search(/LB/i) != -1) {
hs_state = result.sysInfo.light_state.on_off == 0 ? false : true;
} else {
hs_state = result.sysInfo.relay_state == 0 ? false : true;
}
this.setForeignState(`${this.namespace}.${ip_state}.state`, hs_state, true);
this.setForeignState(`${this.namespace}.${ip_state}.last_update`, hs_lastupdate, true);
if (hs_model.search(/110/i) != -1 || hs_model.search(/115/i) != -1) {
await this.hs_getRealtime(result,ip_state,dev_name);
}
if (hs_model.search(/LB/i) != -1 || hs_model.search(/110/i) != -1 || hs_model.search(/115/i) != -1) {
await this.hs_getMonthStats(result,ip_state,dev_name);
await this.hs_getDayStats(result,ip_state,dev_name);
}
// Bulb
if (hs_model.search(/LB/i) != -1) {
await this.lb_dimmable(result,ip_state,dev_name);
}
// bulb KL60
if (hs_model.search(/KL/i) != -1) {
const kl_bright = result.sysInfo.light_state.brightness;
this.setForeignState(`${this.namespace}.${ip_state}.brightness`, kl_bright, true);
}
}
} catch (err) {
if (!this.config.warning) {
this.log.warn(`Socket connection Timeout ${ip_state} ${dev_name} please reconnect the Device`);
}
}
}
async hs_all_info(result,ip_state) {
const hs_mac = result.mac;
const hs_sw_ver = result.softwareVersion;
const hs_hw_ver = result.hardwareVersion;
const hs_model = result.model;
this.setForeignState(`${this.namespace}.${ip_state}.sw_ver`, hs_sw_ver || 'undefined', true);
this.setForeignState(`${this.namespace}.${ip_state}.hw_ver`, hs_hw_ver || 'undefined', true);
this.setForeignState(`${this.namespace}.${ip_state}.model`, hs_model || 'undefined', true);
this.setForeignState(`${this.namespace}.${ip_state}.mac`, hs_mac || 'undefined', true);
return hs_model;
}
async hs_getDayStats(result,ip_state,dev_name) {
const dat = new Date();
const jahr = dat.getFullYear();
const monat = dat.getMonth() + 1; // von 0 - 11 also +1
const tag = dat.getDate();
try {
result.emeter.getDayStats(jahr, monat).then((resultDayStats) => {
const dayList = resultDayStats.day_list;
let energy_v = 0;
for (let i = 0; i < dayList.length; i++) {
if (dayList[i].day === tag) {
if (dayList[i].energy != undefined) {
energy_v = dayList[i].energy;
break;
} else {
energy_v = dayList[i].energy_wh / 1000;
break;
}
}
}
this.setForeignState(`${this.namespace}.${ip_state}.totalNow`, parseFloat(energy_v) || 0, true);
});
} catch (err) {
this.log.error(`result.emeter.getDayStats ${ip_state} ${dev_name}`);
}
}
async lb_dimmable(result,ip_state) {
if (result.sysInfo.is_dimmable == 1) {
//this.log.warn('result lb110 --->>>> : ' + JSON.stringify(result));
//let devLight = result.lighting.getLightState();
const lb_bright = result.sysInfo.light_state.brightness;
const lb_color_temp = result.sysInfo.light_state.color_temp;
const lb_hue = result.sysInfo.light_state.hue;
const lb_saturation = result.sysInfo.light_state.saturation;
this.setForeignState(`${this.namespace}.${ip_state}.brightness`, lb_bright, true);
this.setForeignState(`${this.namespace}.${ip_state}.color_temp`, lb_color_temp, true);
this.setForeignState(`${this.namespace}.${ip_state}.hue`, lb_hue, true);
this.setForeignState(`${this.namespace}.${ip_state}.saturation`, lb_saturation, true);
}
}
async hs_getMonthStats(result,ip_state,dev_name) {
const dat = new Date();
const jahr = dat.getFullYear();
const monat = dat.getMonth() + 1; // von 0 - 11 also +1
try {
result.emeter.getMonthStats(jahr).then((resultMonthStats) => {
const mothList = resultMonthStats.month_list;
let energy_v = 0;
if (mothList != undefined) {
for (let i = 0; i < mothList.length; i++) {
if (mothList[i].month === monat) {
if (mothList[i].energy != undefined) {
energy_v = mothList[i].energy;
break;
} else {
energy_v = mothList[i].energy_wh / 1000;
break;
}
}
}
this.setForeignState(`${this.namespace}.${ip_state}.totalMonthNow`, parseFloat(energy_v) || 0, true);
}
});
} catch (err) {
this.log.error(`result.emeter.getMonthStats ${ip_state} ${dev_name}`);
}
}
async hs_getRealtime(result,ip_state,dev_name) {
const hs_hw_ver = result.hardwareVersion;
let hs_current;
let hs_power;
let hs_voltage;
try {
result.emeter.getRealtime().then((resultRealtime) => {
if (typeof resultRealtime != 'undefined') {
if (hs_hw_ver == '2.0' || hs_hw_ver == '3.0') {
hs_current = resultRealtime.current_ma;
if (resultRealtime.power_mw > 0) {
hs_power = resultRealtime.power_mw / 1000;
} else {
hs_power = resultRealtime.power_mw;
}
if (resultRealtime.voltage_mv > 0) {
hs_voltage = resultRealtime.voltage_mv / 1000;
} else {
hs_voltage = resultRealtime.voltage_mv;
}
} else {
hs_current = resultRealtime.current;
hs_power = resultRealtime.power;
hs_voltage = Math.ceil(resultRealtime.voltage);
}
const hs_led = result.sysInfo.led_off == 0 ? true : false;
this.setForeignState(`${this.namespace}.${ip_state}.current`, parseFloat(hs_current) || 0, true);
if (hs_power < MAX_POWER_VALUE) {
this.setForeignState(`${this.namespace}.${ip_state}.power`, parseFloat(hs_power) || 0, true);
}
this.setForeignState(`${this.namespace}.${ip_state}.voltage`, parseFloat(hs_voltage) || 0, true);
this.setForeignState(`${this.namespace}.${ip_state}.ledState`, hs_led, true);
this.log.debug(`Refresh Data HS110 ${ip_state} ${dev_name}`);
}
});
} catch (err) {
this.log.error(`Error in hs_getRealtime ${ip_state} ${dev_name}`);
}
}
async create_state() {
this.log.debug(`create state`);
const devices = this.config.devices;
try {
for (const k in devices) {
const dev_ip = devices[k].ip;
const dev_name = devices[k].name;
if (devices[k].active) {
this.log.info(`Start with ${dev_ip} ${dev_name} `);
await this.cre_state(dev_ip, dev_name);
}
}
this.setState('info.connection', true, true);
} catch (err) {
this.log.debug(`create state problem`);
}
}
async ip_replace(ip) {
const id_state = ip.replace(/[.\s]+/g, '_');
return id_state;
}
async cre_state(ip, devName) {
let hs_model;
let hs_name;;
try {
this.log.debug('create_state for IP : ' + ip);
const result = await client.getDevice({host: ip});
if (result) {
hs_model = result.model;
let hs_state = result.sysInfo.relay_state;
const ip_state = await this.ip_replace(ip);
hs_name = devName;
if (hs_state == 0) {
hs_state = false;
} else {
hs_state = true;
}
this.extendObjectAsync(`${ip_state}`, {
type: 'device',
common: {
name: hs_name || ip,
},
native: {},
});
this.extendObjectAsync(`${ip_state}.state`, {
type: 'state',
common: {
name: hs_name || ip,
type: 'boolean',
read: true,
write: true,
def: hs_state,
role: 'switch',
desc: 'Switch on/off'
},
native: {},
});
this.extendObjectAsync(`${ip_state}.last_update`, {
type: 'state',
common: {
name: hs_name || ip,
type: 'number',
read: true,
write: false,
role: 'value.time',
desc: 'last update'
},
native: {},
});
this.extendObjectAsync(`${ip_state}.mac`, {
type: 'state',
common: {
name: hs_name || ip,
type: 'string',
read: true,
write: false,
def: result.mac,
role: 'value',
desc: 'Mac address'
},
native: {},
});
this.extendObjectAsync(`${ip_state}.sw_ver`, {
type: 'state',
common: {
name: hs_name || ip,
type: 'string',
read: true,
write: false,
def: result.softwareVersion,
role: 'value',
desc: 'Software Version'
},
native: {},
});
this.extendObjectAsync(`${ip_state}.hw_ver`, {
type: 'state',
common: {
name: hs_name || ip,
type: 'string',
read: true,
write: false,
def: result.hardwareVersion,
role: 'value',
desc: 'Hardware Version'
},
native: {},
});
this.extendObjectAsync(`${ip_state}.model`, {
type: 'state',
common: {
name: hs_name || ip,
type: 'string',
read: true,
write: false,
def: hs_model,
role: 'value',
desc: 'Model'
},
native: {},
});
// plug HS110
if (hs_model.search(/110/i) != -1 || hs_model.search(/115/i) != -1) {
this.extendObjectAsync(`${ip_state}.current`, {
type: 'state',
common: {
name: hs_name || ip,
type: 'number',
read: true,
write: false,
def: 0,
role: 'value.current',
unit: `mA`,
desc: 'current value',
},
native: {},
});
this.extendObjectAsync(`${ip_state}.power`, {
type: 'state',
common: {
name: hs_name || ip,
type: 'number',
read: true,
write: false,
unit: 'W',
def: 0,
role: 'value',
desc: 'power value'
},
native: {},
});
this.extendObjectAsync(`${ip_state}.voltage`, {
type: 'state',
common: {
name: hs_name || ip,
type: 'number',
read: true,
write: false,
def: 0,
role: 'value.voltage',
unit: 'V',
desc: 'voltage value'
},
native: {},
});
this.extendObjectAsync(`${ip_state}.ledState`, {
type: 'state',
common: {
name: hs_name || ip,
type: 'boolean',
read: true,
write: false,
def: hs_state,
role: 'switch',
desc: 'Led on/off'
},
native: {},
});
}
// bulb LBxxx
if (hs_model.search(/LB/i) != -1) {
this.extendObjectAsync(`${ip_state}.brightness`, {
type: 'state',
common: {
name: hs_name || ip,
type: 'number',
read: true,
write: false,
def: 100,
role: 'value',
desc: 'brightness'
},
native: {},
});
this.extendObjectAsync(`${ip_state}.saturation`, {
type: 'state',
common: {
name: hs_name || ip,
type: 'number',
read: true,
write: false,
def: 100,
role: 'value',
desc: 'saturation'
},
native: {},
});
this.extendObjectAsync(`${ip_state}.hue`, {
type: 'state',
common: {
name: hs_name || ip,
type: 'number',
read: true,
write: false,
def: 0,
role: 'value',
desc: 'color'
},
native: {},
});
this.extendObjectAsync(`${ip_state}.color_temp`, {
type: 'state',
common: {
name: hs_name || ip,
type: 'number',
read: true,
write: false,
def: 2700,
role: 'value',
desc: 'color_temp'
},
native: {},
});
}
if (hs_model.search(/LB/i) != -1 || hs_model.search(/110/i) != -1 || hs_model.search(/115/i) != -1) {
this.extendObjectAsync(`${ip_state}.totalNow`, {
type: 'state',
common: {
name: hs_name || ip,
type: 'number',
read: true,
write: false,
def: 0,
role: 'value',
unit: 'kWh',
desc: 'total now value'
},
native: {},
});
this.extendObjectAsync(`${ip_state}.totalMonthNow`, {
type: 'state',
common: {
name: hs_name || ip,
type: 'number',
read: true,
write: false,
def: 0,
role: 'value',
unit: 'kWh',
desc: 'total month now value'
},
native: {},
});
}
}
const ip_state = await this.ip_replace(ip);
this.subscribeForeignStates(`${this.namespace}.${ip_state}.state`);
this.log.debug(hs_model + ' generated ' + ip);
} catch (error) {
this.log.debug('State already present ' + ip);
}
}
async initialization() {
try {
if (this.config.devices === undefined) {
this.log.debug(`initialization undefined No one IP configured`);
}
interval = parseInt(this.config.interval * 1000, 10);
if (interval < 5000) {
interval = 5000;
}
} catch (error) {
this.log.error('initialization fail');
}
}
}
// @ts-ignore parent is a valid property on module
if (module.parent) {
// Export the constructor in compact mode
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
module.exports = (options) => new hs100Controll(options);
} else {
// otherwise start the instance directly
new hs100Controll();
}