-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
594 lines (519 loc) · 18.4 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
'use strict';
/*
* Created with @iobroker/create-adapter v2.6.2
*/
// The adapter-core module gives you access to the core ioBroker functions
// you need to create an adapter
const utils = require('@iobroker/adapter-core');
const { AsyncWaremaHub } = require('./lib/WmsApi/asyncHub.js');
const { AsyncVenetianBlind } = require('./lib/WmsApi/devices/AsyncDevices.js');
const DEV_POS_STATE = {
CLOSING: 0,
OPENING: 1,
STOPPED: 2,
};
const FAST_SINGLE_POLLING_TIME = 15000;
class WmsWebcontrolPro extends utils.Adapter {
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
constructor(options) {
super({
...options,
name: 'wms-webcontrol-pro',
});
this.on('ready', this.onReady.bind(this));
// @ts-ignore
this.on('stateChange', this.onStateChange.bind(this));
// this.on('objectChange', this.onObjectChange.bind(this));
// this.on('message', this.onMessage.bind(this));
this.on('unload', this.onUnload.bind(this));
this.pollingAllDev = null;
this.pollingTimeAllDev = 60000;
this.pollingSingleDev = null;
this.devices = null;
this.isTxLock = false;
this.hub = null;
this.pauseSchedule = null;
}
/**
* Is called when databases are connected and adapter received configuration.
*/
async onReady() {
// Initialize your adapter here
this.checkCfg();
this.pollingTimeAllDev = this.config.optPollTime * 1000;
this.hub = new AsyncWaremaHub(this.config.optIp);
this.updateConStates(true);
this.log.info('hub device connected');
try {
this.devices = await this.hub.getDevices();
this.log.debug('wms devices retrieved');
this.updateHubStates(this.hub.getStatus());
this.updateDevStates();
this.schedulePollAllDevPos(this.pollingTimeAllDev);
} catch (error) {
this.updateConStates(false);
this.log.error('Error: ' + error);
this.delayRestartMs = 15 * 60 * 1000;
this.log.info('restarting adapter in ' + this.delayRestartMs + 'ms');
this.delay(this.delayRestartMs);
this.restart();
}
}
checkCfg() {
if (this.config.optIp == '' || this.config.optPollTime < 3) {
this.log.error('IP address not set or polling time below 3 seconds');
this.disable();
}
if (this.config.pausePollingTime == '' || this.config.resumePollingTime == '') {
this.log.info('Pause and resume times disabled');
this.pauseSchedule = new PauseSchedule(null, null);
} else {
try {
const pauseTime = new Time(this.config.pausePollingTime);
const resumeTime = new Time(this.config.resumePollingTime);
this.pauseSchedule = new PauseSchedule(pauseTime, resumeTime);
} catch (err) {
this.log.error('Syntax error in given pause or resume time: ' + err.message);
this.disable();
}
}
}
async createObj(pathName, name, objType, role, dataType, enableWrite, enableRead) {
await this.setObjectNotExistsAsync(pathName, {
type: objType,
common: {
name: name,
type: dataType,
role: role,
read: enableRead,
write: enableWrite,
},
native: {},
});
}
async updateConStates(isOnline) {
this.log.debug('updating connection info to: ' + isOnline);
await this.createObj('info.connected', 'info.connected', 'state', 'indicator', 'boolean', false, true);
await this.setStateAsync(this.name + '.' + this.instance + '.info.connected', isOnline, true);
}
async updateHubStates(hubStatus) {
this.log.debug('creating adapter objects');
//create states when not existing
await this.createObj('hub.serialNumber', 'hub.serialNumber', 'state', 'number', 'number', true, false);
await this.createObj('hub.name', 'hub.name', 'state', 'string', 'string', true, false);
await this.createObj(
'hub.cloudConnectionStatus',
'hub.cloudConnectionStatus',
'state',
'number',
'number',
true,
false,
);
await this.createObj(
'hub.bootloaderVersion',
'hub.bootloaderVersion',
'state',
'string',
'string',
true,
false,
);
await this.createObj('hub.softwareVersion', 'hub.softwareVersion', 'state', 'string', 'string', true, false);
await this.createObj('hub.bootTime', 'hub.bootTime', 'state', 'number', 'number', true, false);
await this.createObj('hub.containerVersion', 'hub.containerVersion', 'state', 'string', 'string', true, false);
await this.createObj('hub.hostname', 'hub.hostname', 'state', 'string', 'string', true, false);
await this.createObj('hub.ipAddress', 'hub.ipAddress', 'state', 'string', 'string', true, false);
await this.createObj('hub.netMask', 'hub.netMask', 'state', 'string', 'string', true, false);
await this.createObj('hub.isRegistered', 'hub.isRegistered', 'state', 'boolean', 'boolean', true, false);
await this.createObj('hub.time', 'hub.time', 'state', 'string', 'string', true, false);
//update hub objects
this.log.info('updating hub device objects');
this.setStateAsync(this.name + '.' + this.instance + '.hub.serialNumber', hubStatus.serialNumber, true);
this.setStateAsync(this.name + '.' + this.instance + '.hub.name', hubStatus.name, true);
this.setStateAsync(
this.name + '.' + this.instance + '.hub.cloudConnectionStatus',
hubStatus.cloudConnectionStatus,
true,
);
this.setStateAsync(
this.name + '.' + this.instance + '.hub.bootloaderVersion',
hubStatus.bootloaderVersion,
true,
);
this.setStateAsync(this.name + '.' + this.instance + '.hub.softwareVersion', hubStatus.softwareVersion, true);
this.setStateAsync(this.name + '.' + this.instance + '.hub.bootTime', hubStatus.bootTime, true);
this.setStateAsync(this.name + '.' + this.instance + '.hub.containerVersion', hubStatus.containerVersion, true);
this.setStateAsync(this.name + '.' + this.instance + '.hub.hostname', hubStatus.hostname, true);
this.setStateAsync(this.name + '.' + this.instance + '.hub.ipAddress', hubStatus.ipAddress, true);
this.setStateAsync(this.name + '.' + this.instance + '.hub.netMask', hubStatus.netMask, true);
this.setStateAsync(this.name + '.' + this.instance + '.hub.isRegistered', hubStatus.isRegistered, true);
this.setStateAsync(this.name + '.' + this.instance + '.hub.time', hubStatus.time, true);
}
async updateDevStates() {
const devices = this.getDevices();
if (devices != null) {
this.log.debug('creating device objects');
for (const d of Object.values(devices)) {
await this.createObj(d.SN + '.name', d.SN + '.name', 'state', 'string', 'string', true, false);
await this.createObj(d.SN + '.channel', d.SN + '.channel', 'state', 'number', 'number', true, false);
await this.createObj(d.SN + '.setting0', d.SN + '.setting0', 'state', 'state', 'number', true, true);
await this.createObj(d.SN + '.setting1', d.SN + '.setting1', 'state', 'state', 'number', true, true);
await this.createObj(d.SN + '.setting2', d.SN + '.setting2', 'state', 'state', 'number', true, true);
await this.createObj(d.SN + '.setting3', d.SN + '.setting3', 'state', 'state', 'number', true, true);
await this.createObj(d.SN + '.posState', d.SN + '.posState', 'state', 'state', 'number', true, false);
this.setStateAsync(this.name + '.' + this.instance + '.' + d.SN + '.name', d.name, true);
this.setStateAsync(this.name + '.' + this.instance + '.' + d.SN + '.channel', d.getChannel(), true);
this.setStateAsync(
this.name + '.' + this.instance + '.' + d.SN + '.posState',
DEV_POS_STATE.STOPPED,
true,
);
//subscribe to states
this.subscribeStates(d.SN + '.setting*');
}
}
}
areBlindSettingsEqual(a, b) {
return (
a != null &&
b != null &&
a.getSetting0Calc() == b.getSetting0Calc() &&
a.getSetting1Calc() == b.getSetting1Calc() &&
a.getSetting2Calc() == b.getSetting2Calc() &&
a.getSetting3Calc() == b.getSetting3Calc()
);
}
async pullDevPos(d) {
const prevPos = d.getPositionFromRam();
const pos = await d.getPosition();
const posState = await this.getStateAsync(this.name + '.' + this.instance + '.' + d.SN + '.posState');
let result = 0; //0: pull and update successful; 1: device position has been stopped; -1: error retrieving position
if (!pos.isValid()) {
result = -1;
return result;
}
const blindSetEqual = this.areBlindSettingsEqual(prevPos, pos);
if (posState != null && posState.val != DEV_POS_STATE.STOPPED) {
//device motor seems running due to a position request; checking if stopped
if (blindSetEqual == true) {
this.log.debug('switchting to stopped state because blind cover has reached target pos');
await this.setStateAsync(
this.name + '.' + this.instance + '.' + d.SN + '.posState',
DEV_POS_STATE.STOPPED,
true,
);
result = 1;
}
}
this.setStateAsync(this.name + '.' + this.instance + '.' + d.SN + '.setting0', pos.getSetting0Calc(), true);
this.setStateAsync(this.name + '.' + this.instance + '.' + d.SN + '.setting1', pos.getSetting1Calc(), true);
this.setStateAsync(this.name + '.' + this.instance + '.' + d.SN + '.setting2', pos.getSetting2Calc(), true);
this.setStateAsync(this.name + '.' + this.instance + '.' + d.SN + '.setting3', pos.getSetting3Calc(), true);
return result;
}
async pollSingleDevPos(d, intervalMs) {
this.log.debug('single device poll - started for: ' + d.name);
this.clearScheduleSingleDevPos();
const resPullDev = await this.pullDevPos(d);
if (0 == resPullDev || -1 == resPullDev) {
//device updated successfully
this.log.debug('single device poll - re-schedule: ' + intervalMs + 'ms');
this.schedulePollSingleDevPos(d, intervalMs);
} else if (1 == resPullDev) {
//disable posititon state switched to stopped
this.log.debug('single device (' + d.name + ') poll - disabled');
}
}
async pollAllDevPos() {
this.clearScheduleAllDevPos();
//check pause time
if (this.pauseSchedule != null && !this.pauseSchedule.isInPauseTime()) {
const devices = this.getDevices();
// check tx locked
if (this.isTxLocked() == false && devices != null) {
this.log.debug('polling of all device positions');
//request new positions
let numDev = 0;
let getPosErrCnt = 0;
for (const d of Object.values(devices)) {
numDev = numDev + 1;
const resDevPos = await this.pullDevPos(d);
if (resDevPos == -1) {
//error fetching new device position
getPosErrCnt = getPosErrCnt + 1;
this.log.warn(
'failed getting position (device: ' + d.name + ', error counter: ' + getPosErrCnt + ')',
);
}
//delay to not harm hub device
await this.delay(100);
}
//failed position updates exceed threshold
/*if (getPosErrCnt >= numDev) {
// getting all positions failed
this.log.error('restarting adapter because failed position update exceed error counter of ' + numDev);
//this.restart();
}*/
} else {
this.log.debug('discard polling during another transmit');
}
} else {
this.log.debug('discard polling between pause and resume time');
}
// setup new cycle time
this.log.debug('scheduling next polling device cycle: ' + this.pollingTimeAllDev + 'ms');
this.schedulePollAllDevPos(this.pollingTimeAllDev);
}
setPollLock(lock) {
this.isTxLock = lock;
}
isTxLocked() {
return this.isTxLock;
}
getDevices() {
return this.devices;
}
/**
* Is called when adapter shuts down - callback has to be called under any circumstances!
* @param {() => void} callback
*/
onUnload(callback) {
try {
// Here you must clear all timeouts or intervals that may still be active
if (this.pollingAllDev) {
this.clearTimeout(this.pollingAllDev);
this.pollingAllDev = null;
}
if (this.pollingSingleDev) {
this.clearTimeout(this.pollingSingleDev);
this.pollingSingleDev = null;
}
callback();
} catch {
callback();
}
}
// If you need to react to object changes, uncomment the following block and the corresponding line in the constructor.
// You also need to subscribe to the objects with `this.subscribeObjects`, similar to `this.subscribeStates`.
// /**
// * 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
*/
async onStateChange(id, state) {
if (state && state.ack == false && state.val != null) {
// The state was changed
this.log.debug(`state ${id} changed: ${state.val} (ack = ${state.ack})`);
//find out device sn
const idSplitted = id.split('.');
const idSetting = idSplitted[idSplitted.length - 1];
const idSn = parseInt(idSplitted[idSplitted.length - 2]);
//error checks:
if (!idSetting.startsWith('setting') && state.val == null) {
//discard change on not relevant states
this.log.debug('not a valid state');
return 0;
}
//process state change:
const dev = this.hub?.getDeviceFromSerialNumber(idSn);
const newPos = state.val;
switch (idSetting) {
case 'setting0': {
const blindStatus = dev.getPositionFromRam();
let prevPos = -1;
if (blindStatus != null && !blindStatus.isValid()) {
prevPos = blindStatus.getSetting0Calc();
} else {
this.log.debug('previous device position not available; proceeding with user request');
}
if (prevPos != newPos) {
//req new position
this.setPollLock(true);
dev.setPosition(newPos);
this.setPollLock(false);
//monitor and update device direction state
this.updDevDirectionState(dev, prevPos, newPos);
} else {
this.log.debug('discarding user requested setting because it is not different to actual value');
}
break;
}
case 'setting1': {
if (dev instanceof AsyncVenetianBlind) {
const set0 = await this.getStateAsync(
this.name + '.' + this.instance + '.' + dev.SN + '.setting0',
);
//req new position
this.setPollLock(true);
dev.setPosition(set0, newPos);
this.setPollLock(false);
//todo: monitor and update device direction state for tilt
}
break;
}
default:
this.log.debug('discard state change because not supported yet');
}
//cleanup
//-
}
}
async updDevDirectionState(dev, curPos, newPos) {
//update the device direction state once and check for stopped state in device polling function
let isCoverDriving = false;
if (curPos < newPos) {
await this.setStateAsync(
this.name + '.' + this.instance + '.' + dev.SN + '.posState',
DEV_POS_STATE.CLOSING,
true,
);
isCoverDriving = true;
} else if (curPos > newPos) {
await this.setStateAsync(
this.name + '.' + this.instance + '.' + dev.SN + '.posState',
DEV_POS_STATE.OPENING,
true,
);
isCoverDriving = true;
} else {
//no driving required
await this.setStateAsync(
this.name + '.' + this.instance + '.' + dev.SN + '.posState',
DEV_POS_STATE.STOPPED,
true,
);
}
if (isCoverDriving) {
this.log.debug(
'schedule poll for single device (' + dev.name + ') position: ' + FAST_SINGLE_POLLING_TIME + 'ms',
);
this.schedulePollSingleDevPos(dev, FAST_SINGLE_POLLING_TIME);
}
}
schedulePollAllDevPos(t) {
if (this.pollingAllDev) {
this.clearTimeout(this.pollingAllDev);
}
this.pollingTimeAllDev = t;
this.pollingAllDev = this.setTimeout(() => {
this.pollAllDevPos();
}, t);
}
schedulePollSingleDevPos(dev, t) {
if (this.pollingSingleDev) {
this.clearTimeout(this.pollingSingleDev);
}
this.pollingSingleDev = this.setTimeout(() => {
this.pollSingleDevPos(dev, t);
}, t);
}
clearScheduleAllDevPos() {
if (this.pollingAllDev) {
this.clearTimeout(this.pollingAllDev);
this.pollingAllDev = null;
}
}
clearScheduleSingleDevPos() {
if (this.pollingSingleDev) {
this.clearTimeout(this.pollingSingleDev);
this.pollingSingleDev = null;
}
}
// If you need to accept messages in your adapter, uncomment the following block and the corresponding line in the constructor.
// /**
// * Some message was sent to this instance over message box. Used by email, pushover, text2speech, ...
// * Using this method requires "common.messagebox" 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 Time {
constructor(timeStr) {
const match = timeStr.match(/^(\d{1,2}):(\d{2}):(\d{2})\s*(AM|PM)$/i);
if (!match) {
throw new Error('Invalid time format. Use HH:MM:SS AM/PM');
}
let [_, hours, minutes, seconds, period] = match;
hours = parseInt(hours);
if (hours < 1 || hours > 12) {
throw new Error('Hours must be between 1 and 12');
}
// Convert to 24-hour format
if (period.toUpperCase() === 'PM' && hours !== 12) {
hours += 12;
} else if (period.toUpperCase() === 'AM' && hours === 12) {
hours = 0;
}
this.hours = hours;
this.minutes = parseInt(minutes);
this.seconds = parseInt(seconds);
if (this.minutes > 59 || this.seconds > 59) {
throw new Error('Minutes and seconds must be between 0 and 59');
}
}
toString() {
return `${this.hours.toString().padStart(2, '0')}:${this.minutes.toString().padStart(2, '0')}:${this.seconds.toString().padStart(2, '0')}`;
}
}
class PauseSchedule {
constructor(pause, resume) {
this.pause = pause;
this.resume = resume;
}
isInPauseTime(curDateTime = new Date()) {
if (this.resume == null || this.pause == null) {
return false;
} else {
const now = curDateTime;
const currentMinutes = now.getHours() * 60 + now.getMinutes();
const pauseMinutes = this.pause.hours * 60 + this.pause.minutes;
const resumeMinutes = this.resume.hours * 60 + this.resume.minutes;
if (pauseMinutes < resumeMinutes) {
// Normal case (e.g. pause 08:00, resume 17:00)
return currentMinutes >= pauseMinutes && currentMinutes < resumeMinutes;
} else {
// Overnight case (e.g. pause 22:00, resume 06:00)
return currentMinutes >= pauseMinutes || currentMinutes < resumeMinutes;
}
}
}
}
if (require.main !== module) {
// Export the constructor in compact mode
/**
* @param {Partial<utils.AdapterOptions>} [options={}]
*/
module.exports = {
...{ Time, PauseSchedule },
...(options) => new WmsWebcontrolPro(options),
};
} else {
// otherwise start the instance directly
new WmsWebcontrolPro();
}