iobroker.smartcontrol 1.2.0 → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/.github/ISSUE_TEMPLATE/BugReport.md +36 -36
  2. package/.github/ISSUE_TEMPLATE/Enhancement.md +19 -19
  3. package/.github/auto-merge.yml +17 -17
  4. package/.github/workflows/dependabot-auto-merge.yml +22 -22
  5. package/.github/workflows/npmpublish.yml +30 -30
  6. package/.github/workflows/test-and-release.yml +92 -129
  7. package/.releaseconfig.json +3 -0
  8. package/LICENSE +21 -21
  9. package/README.md +374 -402
  10. package/admin/doc-md/readme.txt +6 -6
  11. package/admin/doc-md/start_de.md +124 -124
  12. package/admin/doc-md/start_en.md +126 -126
  13. package/admin/doc-md/table-conditions_de.md +10 -10
  14. package/admin/doc-md/table-conditions_en.md +10 -10
  15. package/admin/doc-md/table-execution_de.md +12 -12
  16. package/admin/doc-md/table-execution_en.md +12 -12
  17. package/admin/doc-md/table-target-devices_de.md +18 -18
  18. package/admin/doc-md/table-target-devices_en.md +21 -21
  19. package/admin/doc-md/table-target-enums_de.md +13 -13
  20. package/admin/doc-md/table-target-enums_en.md +15 -15
  21. package/admin/doc-md/table-target-url_de.md +29 -29
  22. package/admin/doc-md/table-target-url_en.md +27 -27
  23. package/admin/doc-md/table-trigger-devices_de.md +12 -12
  24. package/admin/doc-md/table-trigger-devices_en.md +10 -10
  25. package/admin/doc-md/table-trigger-motion_de.md +23 -23
  26. package/admin/doc-md/table-trigger-motion_en.md +24 -24
  27. package/admin/doc-md/table-trigger-times_de.md +13 -13
  28. package/admin/doc-md/table-trigger-times_en.md +11 -11
  29. package/admin/doc-md/table-zones_de.md +14 -14
  30. package/admin/doc-md/table-zones_en.md +13 -13
  31. package/admin/doc-md/table-zones_select-targets_de.md +18 -18
  32. package/admin/doc-md/table-zones_select-targets_en.md +18 -18
  33. package/admin/index_m.html +1 -1
  34. package/admin/index_m.js +118 -88
  35. package/admin/zero-md/webcomponents-loader.min.js +8 -8
  36. package/admin/zero-md/zero-md.min.js.js +8 -8
  37. package/io-package.json +461 -433
  38. package/lib/adapter-config.d.ts +15 -15
  39. package/lib/constants.js +128 -125
  40. package/lib/helper.js +1069 -1059
  41. package/lib/tools.js +93 -93
  42. package/lib/trigger-class.js +964 -964
  43. package/main.js +105 -48
  44. package/main.test.js +30 -30
  45. package/package.json +73 -70
@@ -1,965 +1,965 @@
1
- 'use strict';
2
- /* eslint-disable no-inner-declarations -- // cite: *prior to ES6*, a function declaration is only allowed in the first level of a program or the body of another function */
3
-
4
- /**
5
- * @class Trigger
6
- * @desc For handling of triggers and their associated target devices.
7
- * Every instance of this class is a specific trigger (motion sensor/'other device'/time trigger)
8
- * @author Mic-M <https://github.com/Mic-M/ioBroker.smartcontrol>
9
- * @license MIT
10
- *
11
- * Initial Properties:
12
- * ---Generic Properties---
13
- * {string} triggerName Name of Trigger
14
- * {string} triggerTableId table name: 'tableTriggerDevices', 'tableTriggerMotion', or 'tableTriggerTimes'
15
- * {string} triggerStatePath State Path of Trigger, if a state
16
- * {string} triggerStateVal Trigger state value from Options Table
17
- * {string} triggerIsToggle Trigger is a toggle, so isToggle is true in tableTriggerDevices
18
- * {boolean} targetOff If true, targets will be switched off, and not on.
19
- * ---Motion Trigger---
20
- * {boolean} triggerIsMotion Is trigger a motion sensor?
21
- * {boolean} motionNotIfManual if true: motion trigger should not set timeout if target device was turned on previously without a motion trigger.
22
- * {number} motionDuration Duration (timer) in seconds for motion sensor
23
- * {string} motionBriStatePath State Path of brightness state
24
- * {number} motionBriThreshold Threshold of brightness
25
- * {object} motionTimer Timer object for motion to switch targets off
26
- * {boolean} mimicMotion For trigger devices linked/associated with a motion sensor (tableTriggerMotion -> motionLinkedTrigger)
27
- * {string} mimicMotionTriggerName Trigger name of device linked to motion sensor
28
- * {boolean} mimicMotionIgnoreMotionOn Ignore motion if motion sensor is set to true
29
- * ---Time Trigger---
30
- * {boolean} triggerIsTime Is trigger a time trigger?
31
- * {string} triggerTime If time trigger: time like '42 * * * *' or 'sunset+30'
32
- * {array} triggerTmAdditionCond Array of additional condition names for "Must be fulfilled"
33
- * {boolean} triggerTmAddCondAll if true: all conditions must be met, if false: at least one condition must be met
34
- * {string} triggerTmNever Array of additional condition names for "Never" which shall not be
35
- * {boolean} triggerTmNeverAll if true: all conditions must be met, if false: at least one condition must be met
36
- *
37
- * Properties set by this._asyncUpdateCurrentActiveZones()
38
- * {array} zoneNames All zone names that were triggered and meet all conditions
39
- * {object} zoneTargetNames All target device names per zone, like {Hallway:['Hallway Light'], Bath:['Light', 'Radio Bath']}
40
- * NOTE: Motion Trigger - If target was already turned on previously by a non-motion trigger:
41
- * We will remove that device to not schedule timer, if motionNotIfManual
42
- *
43
- */
44
- class Trigger {
45
-
46
- /**
47
- * Constructor
48
- *
49
- * @param {object} adapter - ioBroker adapter instance object
50
- * @param {string} triggerName - Name of trigger.
51
- */
52
- constructor(adapter, triggerName) {
53
- this.adapter = adapter;
54
- this.triggerName = triggerName;
55
- this.zoneOffTimer = null;
56
- this._init();
57
- }
58
-
59
- /**
60
- * Set properties (retrieving from adapter configuration)
61
- */
62
- _init() {
63
-
64
- try {
65
-
66
- this.triggerStatePath = undefined; // set below accordingly if state
67
- this.triggerStateVal = undefined; // set below accordingly if state
68
- this.triggerIsMotion = false; // set to true below, if motion
69
- this.triggerIsToggle = false; // set to true below, if tableTriggerDevices.isToggle=true
70
- this.targetOff = false; // set to true below, if activated in other devices or time trigger table
71
- this.mimicMotion = false; // set accordingly in main.js
72
- this.mimicMotionTriggerName = undefined; // set accordingly in main.js
73
- this.mimicMotionIgnoreMotionOn = false; // set to true below, if tableTriggerMotion.ignoreMotionOn is true
74
-
75
- /**
76
- * Get all triggered table rows and set properties accordingly.
77
- */
78
- const result = { row: {}, tableId: '' };
79
- for (const lpTable of ['tableTriggerDevices', 'tableTriggerMotion', 'tableTriggerTimes']) {
80
- for (const lpRow of this.adapter.config[lpTable]) {
81
- if (lpRow.active && lpRow.name == this.triggerName) {
82
- result.row = lpRow;
83
- result.tableId = lpTable;
84
- break;
85
- }
86
- }
87
- if (result.index > -1) break;
88
- }
89
-
90
- switch (result.tableId) {
91
-
92
- case 'tableTriggerDevices':
93
- this.triggerTableId = result.tableId;
94
- this.triggerStatePath = result.row.stateId;
95
- this.triggerStateVal = result.row.stateVal;
96
- this.triggerIsToggle = result.row.isToggle;
97
- this.targetOff = result.row.targetOff;
98
- break;
99
-
100
- case 'tableTriggerMotion':
101
- this.triggerTableId = result.tableId;
102
- this.triggerIsMotion = true;
103
- this.motionTimer = null;
104
- this.triggerStatePath = result.row.stateId;
105
- this.triggerStateVal = true; // is always true for motion sensors to indicate if on
106
- this.motionNotIfManual = result.row.notIfManual;
107
- this.mimicMotionIgnoreMotionOn = result.row.ignoreMotionOn;
108
-
109
- if (result.row.duration && parseInt(result.row.duration) > 0) {
110
- this.motionDuration = parseInt(result.row.duration);
111
- } else {
112
- this.motionDuration = 0;
113
- }
114
- if (result.row.briThreshold && parseInt(result.row.briThreshold) > 0 && result.row.briStateId && result.row.briStateId.length > 5) {
115
- this.motionBriStatePath = result.row.briStateId;
116
- this.motionBriThreshold = result.row.briThreshold;
117
- } else {
118
- this.motionBriStatePath = '';
119
- this.motionBriThreshold = 0;
120
- }
121
- break;
122
-
123
- case 'tableTriggerTimes':
124
- this.triggerTableId = result.tableId;
125
- this.triggerIsTime = true;
126
- this.targetOff = result.row.targetOff;
127
- this.triggerTime = result.row.time;
128
- this.triggerTmAdditionCond = result.row.additionalConditions;
129
- this.triggerTmAddCondAll = result.row.additionalConditionsAll;
130
- this.triggerTmNever = result.row.never;
131
- this.triggerTmNeverAll = result.row.neverAll;
132
- break;
133
-
134
- default:
135
- throw (`No active trigger '${this.triggerName}' found in any trigger table.`);
136
- }
137
-
138
- } catch (error) {
139
- this.adapter.x.helper.dumpError('_init()]', error);
140
- }
141
-
142
- }
143
-
144
- /**
145
- * Set all target devices for all zones
146
- * Note: No need to remove duplicates, this is being taken care of by asyncVerifyConfig() function.
147
- * @fires _asyncSetTargetDevices_processZone()
148
- */
149
- async asyncSetTargetDevices() {
150
-
151
- try {
152
-
153
- await this._asyncUpdateCurrentActiveZones(); // update current active zone properties
154
- if (!this.zoneNames || !this.zoneTargetNames) return;
155
-
156
- // Timer zoneOn (delay for switching zone on)
157
- for (const lpZoneName of this.zoneNames) {
158
- clearTimeout(this.adapter.x.timersZoneOn[lpZoneName]);
159
- this.adapter.x.timersZoneOn[lpZoneName] = null;
160
- const zoneOnSecs = parseInt(this.adapter.getOptionTableValue('tableZones', 'name', lpZoneName, 'onAfter'));
161
- if (!zoneOnSecs || zoneOnSecs < 1) {
162
- this.adapter.log.debug(`Trigger [${this.triggerName}] Zone '${lpZoneName}' No 'On after x sec' time is set, so we do not set such delay (timer).`);
163
- this._asyncSetTargetDevices_processZone(lpZoneName);
164
- } else {
165
- this.adapter.x.timersZoneOn[lpZoneName] = setTimeout(() => {
166
- this._asyncSetTargetDevices_processZone(lpZoneName);
167
- }, zoneOnSecs * 1000);
168
- }
169
- }
170
-
171
- } catch (error) {
172
- this.adapter.x.helper.dumpError('[asyncSetTargetDevices]', error);
173
- }
174
-
175
- }
176
-
177
-
178
- /**
179
- * Set all target devices: Process zone - Start
180
- * @param {string} zoneName - Name of zone
181
- */
182
- async _asyncSetTargetDevices_processZone(zoneName) {
183
-
184
- try {
185
-
186
- if (!this.zoneNames || !this.zoneTargetNames) return;
187
-
188
- /**
189
- * Prepare: If Motion Sensor triggered - verify brightness if bri is set
190
- */
191
- if (!this.mimicMotion && this.triggerIsMotion && !this.adapter.x.helper.isLikeEmpty(this.motionBriStatePath) && this.adapter.x.helper.isNumber(this.motionBriThreshold) && parseInt(this.motionBriThreshold) > 0) {
192
-
193
- if (this.adapter.config.motionIgnoreBriIfZoneOn && this.adapter.x.zonesIsOn[zoneName]) {
194
- // Disregard Brightness if zone is on (if this.adapter.config.motionIgnoreBriIfZoneOn == true)
195
- this.adapter.log.debug(`Trigger [${this.triggerName}] Zone '${zoneName}' is on and new motion detected, therefore, we disregard any current brightness.`);
196
- } else {
197
- // Verify brightness
198
- const briStateObjCurr = await this.adapter.x.helper.asyncGetForeignState(this.motionBriStatePath); // {val: false, ack: true, ts: 1591117034451, …}
199
- const briStateValCurrent = briStateObjCurr.val;
200
- if (this.adapter.x.helper.isLikeEmpty(briStateValCurrent) || !this.adapter.x.helper.isNumber(briStateValCurrent) || parseInt(briStateValCurrent) < 0) {
201
- // Bri not valid, so disregard bri and continue
202
- this.adapter.log.debug(`Trigger [${this.triggerName}] Brightness of ${briStateValCurrent} of ${this.motionBriStatePath} is not valid. State Value: [${briStateValCurrent}]. Therefore, bri will be disregarded and we continue.`);
203
- } else if (parseInt(briStateValCurrent) < parseInt(this.motionBriThreshold)) {
204
- // continue
205
- this.adapter.log.debug(`Trigger [${this.triggerName}] Brightness of ${briStateValCurrent} is < threshold of ${this.motionBriThreshold}, so we continue.`);
206
- } else {
207
- // Brightness condition is not met!
208
- this.adapter.x.helper.logExtendedInfo(`Trigger [${this.triggerName}] activated but current brightness of ${briStateValCurrent} is >= threshold of ${this.motionBriThreshold} -> Motion disregarded.`);
209
- return; // go out
210
- }
211
- }
212
- } else if (!this.mimicMotion && this.triggerIsMotion) {
213
- this.adapter.log.debug(`Trigger [${this.triggerName}] - no brightness defined for this motion sensor, so continue and do not use bri as an additional criterion.`);
214
- }
215
-
216
- /**
217
- * Ignore motion sensor triggered motion=true, if mimicMotionIgnoreMotionOn set to true
218
- */
219
- const timeLeft = this.adapter.x.helper.getTimeoutTimeLeft(this.adapter.x.timersMimicMotionTrigger[zoneName]);
220
- if (!this.mimicMotion && this.triggerStateVal && this.triggerIsMotion && this.mimicMotionIgnoreMotionOn) {
221
- if (timeLeft > -1) {
222
- this.adapter.log.debug(`Trigger [${this.triggerName}] - Zone ${zoneName}: 'Mimic motion' is active, so we take over`);
223
- // timer will be canceled below
224
- } else {
225
- this.adapter.log.info(`Trigger [${this.triggerName}] - Zone ${zoneName}: No execution due to activated zone option 'ignore motion on'.`);
226
- return;
227
- }
228
- }
229
-
230
- // Clear "linked devices" (mimic motion) timer for motion trigger
231
- if (this.triggerIsMotion && (timeLeft > -1)) {
232
- clearTimeout(this.adapter.x.timersMimicMotionTrigger[zoneName]);
233
- this.adapter.x.timersMimicMotionTrigger[zoneName] = null;
234
- this.adapter.log.debug(`Clearing timer 'Linked device to motion', which was still running for ${(timeLeft / 1000).toFixed(0)} seconds.`);
235
- }
236
-
237
-
238
-
239
- /**
240
- * -- Main --
241
- * Loop thru the target device names and switch accordingly.
242
- * Code supports delay, therefore, implementation is different as if we would not have this support (like processing all devices, then call finalize(), etc.)
243
- */
244
- const lSwitchedDevices = [];
245
- const lAlreadyOnDevices = [];
246
- const lDelayedDevices = [];
247
- const lDelaySecs = []; // for each device, delay to turn on, e.g. [0, 10]
248
- let onOff = 'on'; // for toggle
249
-
250
- // get delay ('onAfter')
251
- const targetsOverwrite = this.adapter.getOptionTableValue('tableZones', 'name', zoneName, 'targetsOverwrite'); // like: {'Hallway.Light':{val:'new val', delay:10}, 'Hallway.Radio':{val:'Radio XYZ'}}
252
-
253
- let counterDevicesProcessed = 0; // Once all processed, we will call a function
254
- for (const lpTargetDeviceName of this.zoneTargetNames[zoneName]) {
255
-
256
- let delay = this.adapter.getOptionTableValue('tableTargetDevices', 'name', lpTargetDeviceName, 'onAfter');
257
- if (delay !== undefined && this.adapter.x.helper.isNumber(delay) && parseInt(delay) > 0) {
258
- delay = parseInt(delay);
259
- } else {
260
- delay = 0;
261
- }
262
- lDelaySecs.push(delay);
263
-
264
- // Targets overwrite: state value, and delay
265
- let overwriteValue = null;
266
- if (targetsOverwrite && targetsOverwrite[lpTargetDeviceName]) {
267
- if (!this.adapter.x.helper.isLikeEmpty(targetsOverwrite[lpTargetDeviceName].val)) {
268
- overwriteValue = targetsOverwrite[lpTargetDeviceName].val;
269
- }
270
- if (targetsOverwrite[lpTargetDeviceName].delay!==undefined
271
- && this.adapter.x.helper.isNumber(targetsOverwrite[lpTargetDeviceName].delay)
272
- && parseInt(targetsOverwrite[lpTargetDeviceName].delay) > -1) {
273
- delay = parseInt(targetsOverwrite[lpTargetDeviceName].delay);
274
- }
275
- }
276
-
277
-
278
- /**
279
- * let's call function switchTargetDevice()
280
- */
281
- // Timer (delay) to switch device on
282
- if (delay > 0) lDelayedDevices.push(lpTargetDeviceName);
283
- clearTimeout(this.adapter.x.timersZoneDeviceOnDelay[zoneName+'_'+ lpTargetDeviceName]);
284
- this.adapter.x.timersZoneDeviceOnDelay[zoneName+'_'+ lpTargetDeviceName] = null;
285
-
286
- if (delay > 0) {
287
- // set timeout
288
- this.adapter.x.timersZoneDeviceOnDelay[zoneName+'_'+ lpTargetDeviceName] = setTimeout(()=>{ switchTargetDeviceAsync(this); }, delay * 1000);
289
- } else {
290
- // call right away
291
- await switchTargetDeviceAsync(this);
292
- }
293
-
294
- /**
295
- * Function switchTargetDevice
296
- * @param {object} that - this
297
- */
298
- async function switchTargetDeviceAsync(that) {
299
-
300
- try {
301
-
302
- if (!that.zoneTargetNames) return;
303
-
304
- counterDevicesProcessed++; // +1
305
-
306
- // If target device should be switched off, and not on, per config in trigger table
307
- // Will be overwritten later if toggle is activated
308
- if (that.targetOff) onOff = 'off';
309
-
310
- // Toggle
311
- if (that.triggerIsToggle) {
312
- // If we have Toggle, we are using the ON state/value to check.
313
- const onState = that.adapter.getOptionTableValue('tableTargetDevices', 'name', lpTargetDeviceName, 'onState');
314
- const onVal = that.adapter.getOptionTableValue('tableTargetDevices', 'name', lpTargetDeviceName, 'onValue');
315
- const currentStateVal = await that.adapter.x.helper.asyncGetForeignStateValue(onState);
316
- if (currentStateVal == null) throw (`Could not get current state value for '${onState}' of device '${lpTargetDeviceName}'`);
317
- if (onVal == currentStateVal) {
318
- onOff = 'off';
319
- } else {
320
- onOff = 'on';
321
- }
322
- }
323
-
324
- // Get option values.
325
- const lpTargetState = that.adapter.getOptionTableValue('tableTargetDevices', 'name', lpTargetDeviceName, onOff + 'State');
326
- let lpTargetVal = that.adapter.getOptionTableValue('tableTargetDevices', 'name', lpTargetDeviceName, onOff + 'Value');
327
- const noTargetCheckStr = (onOff == 'on') ? 'noTargetOnCheck' : 'noTargetOffCheck';
328
- const doNotCheckTarget = that.adapter.getOptionTableValue('tableTargetDevices', 'name', lpTargetDeviceName, noTargetCheckStr);
329
-
330
- if (lpTargetState == undefined || lpTargetVal == undefined) {
331
- throw (`Unable to retrieve target '${onOff}' state/value for target device '${lpTargetDeviceName}'`);
332
- }
333
-
334
- // Overwrite target values if according value is set in Zones table
335
- if (onOff == 'on' && overwriteValue !== null) {
336
- lpTargetVal = overwriteValue;
337
- }
338
-
339
- // Let's get current state value
340
- let currentStateVal;
341
- if (!doNotCheckTarget) {
342
- currentStateVal = await that.adapter.x.helper.asyncGetForeignStateValue(lpTargetState);
343
- if (currentStateVal == null) {
344
- throw (`Could not get current state value for '${lpTargetState}' of device '${lpTargetDeviceName}'`);
345
- }
346
- }
347
-
348
- // Set target state.
349
- // Note: Verification of the state value and conversion as needed was performed already by asyncVerifyConfig()
350
- // Check if device is already on.
351
- if (doNotCheckTarget || (!doNotCheckTarget && (currentStateVal != lpTargetVal))) {
352
-
353
- // Set state
354
- await that.adapter.setForeignStateAsync(lpTargetState, { val: lpTargetVal, ack: false });
355
- //if (delay == 0) lSwitchedDevices.push(lpTargetDeviceName);
356
- lSwitchedDevices.push(lpTargetDeviceName);
357
- if (that.motionNotIfManual) {
358
- if (that.triggerIsMotion) {
359
- // triggered by motion, so add to that.adapter.x.motionTriggeredDevices
360
- if (that.adapter.x.motionTriggeredDevices.indexOf(lpTargetDeviceName) == -1) {
361
- that.adapter.x.motionTriggeredDevices.push(lpTargetDeviceName);
362
- }
363
- } else {
364
- //Triggered by NON-motion, so remove from that.adapter.x.motionTriggeredDevices
365
- that.adapter.x.motionTriggeredDevices = that.adapter.x.helper.arrayRemoveElementByValue(that.adapter.x.motionTriggeredDevices, lpTargetDeviceName);
366
- }
367
- }
368
- // set json log to smartcontrol.x.info.log.switchedTargetDevices.json
369
- that.adapter.x.helper.setJsonLog('switchedTargetDevices', {
370
- time: that.adapter.x.helper.dateToLocalIsoString(new Date()),
371
- name: lpTargetDeviceName,
372
- objectId: lpTargetState,
373
- value: lpTargetVal,
374
- triggerName: that.triggerName,
375
- ts: Date.now(),
376
- });
377
-
378
- } else {
379
- // do not set target state
380
- // if (delay == 0) lAlreadyOnDevices.push(lpTargetDeviceName);
381
- lAlreadyOnDevices.push(lpTargetDeviceName);
382
- }
383
-
384
- if (counterDevicesProcessed == that.zoneTargetNames[zoneName].length) {
385
-
386
- /**
387
- * All devices processed, so we continue here
388
- */
389
- if (!that.zoneTargetNames || !that.zoneNames) return;
390
-
391
- /**
392
- * Motion Trigger: If target was already turned on previously by a non-motion trigger: do not schedule timer.
393
- * Also, provide some log info in logMotion
394
- */
395
- let logMotion = '';
396
- if (!that.mimicMotion && that.triggerIsMotion && that.motionDuration && that.motionDuration > 0) {
397
- const lRemovedDevices = [];
398
- if (that.motionNotIfManual) {
399
- for (const lpTargetDevice of lAlreadyOnDevices) {
400
- if (that.adapter.x.motionTriggeredDevices.indexOf(lpTargetDevice) > -1) {
401
- // Device was already on and motion triggered before.
402
- } else {
403
- // Device was already on, but NO motion triggered before.
404
- // Therefore, we will exclude device from the timer
405
- that.zoneTargetNames[zoneName] = that.adapter.x.helper.arrayRemoveElementByValue(that.zoneTargetNames[zoneName], lpTargetDevice);
406
- lRemovedDevices.push(lpTargetDevice);
407
- }
408
- }
409
- }
410
- if (that.zoneTargetNames[zoneName].length < 1) {
411
- logMotion = `No motion timer will be set to turn off since device(s) turned on manually before.`;
412
- } else {
413
- if (lRemovedDevices.length == 0) {
414
- logMotion = `Timer of ${that.motionDuration}s will be set to turn off once no more motion recognized.`;
415
- } else {
416
- logMotion = `Timer of ${that.motionDuration}s will be set to turn off once no more motion recognized. Limited to '${that.zoneTargetNames[zoneName].toString()}'. ${lRemovedDevices.toString()} were turned on manually before.`;
417
- }
418
- }
419
- }
420
-
421
-
422
- /**
423
- * Set "always off after" timer if set in Table Zones.
424
- */
425
- if (that.triggerIsToggle && onOff == 'off') {
426
- // Toggle is activated and zone is turned off, so kill/delete the timer.
427
- const zoneOffTimeLeft = that.adapter.x.helper.getTimeoutTimeLeft(that.adapter.x.timersZoneOff[zoneName]);
428
- if (zoneOffTimeLeft > -1) {
429
- that.adapter.log.debug(`Trigger [${that.triggerName}] Zone '${zoneName}': Turn off 'always off' timer, since still running ${(zoneOffTimeLeft / 1000).toFixed(0)} seconds and toggle trigger triggered to turn off.`);
430
- clearTimeout(that.adapter.x.timersZoneOff[zoneName]);
431
- that.adapter.x.timersZoneOff[zoneName] = null;
432
- }
433
-
434
- } else {
435
- if (that.triggerIsMotion && (that.zoneTargetNames[zoneName].length < 1)) {
436
- that.adapter.x.helper.logExtendedInfo(`Trigger [${that.triggerName}], Zone '${that.zoneNames.toString()}': no 'always off after' timer set since device(s) turned on manually before.`);
437
- } else {
438
- const zoneOffSecs = parseInt(that.adapter.getOptionTableValue('tableZones', 'name', zoneName, 'offAfter'));
439
- that.asyncSetZoneTimer_zoneOff('timersZoneOff', zoneName, zoneOffSecs);
440
- }
441
- }
442
-
443
- /**
444
- * If "mimic motion": set off timer for zone
445
- */
446
- if (that.mimicMotion) {
447
- const zoneOffSecs = parseInt(that.adapter.getOptionTableValue('tableTriggerMotion', 'name', that.triggerName, 'motionLinkedDuration'));
448
- that.asyncSetZoneTimer_zoneOff('timersMimicMotionTrigger', zoneName, zoneOffSecs);
449
- }
450
-
451
-
452
- // Set "Zone is on" status
453
- that.adapter.x.zonesIsOn[zoneName] = true;
454
-
455
- /**
456
- * JSON log for info.log.zoneActivations.json
457
- */
458
- const alwaysOff = parseInt(that.adapter.getOptionTableValue('tableZones', 'name', zoneName, 'offAfter'));
459
- that.adapter.x.helper.setJsonLog('zoneActivations', {
460
- ts: Date.now(),
461
- time: that.adapter.x.helper.dateToLocalIsoString(new Date()),
462
- zone: zoneName,
463
- trigger: (!that.mimicMotion) ? that.triggerName : that.mimicMotionTriggerName,
464
- targetsAll: that.zoneTargetNames[zoneName].toString(),
465
- targetsAllDelays: JSON.stringify(lDelaySecs),
466
- targetsSet: lSwitchedDevices.toString(),
467
- targetsSkipped: lAlreadyOnDevices.toString(),
468
- motionTimer: (that.motionDuration) ? that.motionDuration : 0,
469
- alwaysOffTimer: (isNaN(alwaysOff)) ? 0 : alwaysOff,
470
- });
471
-
472
- // Finalize
473
- if (lSwitchedDevices.length > 0) {
474
- if (lAlreadyOnDevices.length < 1) {
475
- that.adapter.x.helper.logExtendedInfo(`Trigger [${that.triggerName}] activated Zone '${zoneName}'. Turned ${onOff}: ${lSwitchedDevices.toString()}.`);
476
- } else {
477
- that.adapter.x.helper.logExtendedInfo(`Trigger [${that.triggerName}] activated Zone '${zoneName}'. Turned ${onOff}: ${lSwitchedDevices.toString()}. Not turned ${onOff} (as already ${onOff}): '${lAlreadyOnDevices.toString()}'`);
478
- }
479
- } else {
480
- if (lAlreadyOnDevices.length > 0) that.adapter.x.helper.logExtendedInfo(`Trigger [${that.triggerName}] activated Zone '${zoneName}'. However, device(s) '${lAlreadyOnDevices.toString()}' not turned ${onOff} as these are already ${onOff}.`);
481
- }
482
- if (lDelayedDevices.length > 0) that.adapter.x.helper.logExtendedInfo(`Trigger [${that.triggerName}] Following device(s) will be switched ${onOff} later, since a delay was set: ${lDelayedDevices.toString()}.`);
483
- if (logMotion) that.adapter.x.helper.logExtendedInfo(`Trigger [${that.triggerName}] Zone '${zoneName}': ${logMotion}`);
484
-
485
- }
486
-
487
- } catch (error) {
488
- that.adapter.x.helper.dumpError(`[switchTargetDevice]`, error);
489
- return;
490
- }
491
-
492
- }
493
-
494
- }
495
-
496
-
497
- } catch (error) {
498
- this.adapter.x.helper.dumpError(`[_asyncSetTargetDevices_processZone]`, error);
499
- return;
500
- }
501
- }
502
-
503
-
504
- /**
505
- * Set timeout to switch devices of a zone off for zoneOff timer
506
- * @param {string} timerObjectKey - e.g. 'timersZoneOff' or 'timersMimicMotionTrigger'
507
- * @param {string} zoneName - Zone Name
508
- * @param {number} zoneOffAfter - Switch zone off after this number of seconds
509
- */
510
- async asyncSetZoneTimer_zoneOff(timerObjectKey, zoneName, zoneOffAfter) {
511
-
512
- try {
513
-
514
- if (!zoneOffAfter || zoneOffAfter < 1) {
515
- this.adapter.log.debug(`Trigger [${this.triggerName}] Zone '${zoneName}' No 'Always off after' time is set, so we do not set such timer.`);
516
- return;
517
- }
518
-
519
- // Get current target devices info
520
- const targets = await this._asyncGetTargetDevicesInfoOfZone(zoneName);
521
-
522
- // First: clear timers. Note: we use timeLeft since we need this anyways for log.
523
- const timeLeft = this.adapter.x.helper.getTimeoutTimeLeft(this.adapter.x[timerObjectKey][zoneName]);
524
- if (timeLeft > -1) {
525
- clearTimeout(this.adapter.x[timerObjectKey][zoneName]);
526
- this.adapter.x[timerObjectKey][zoneName] = null;
527
- }
528
-
529
- // Set timer
530
- this.adapter.x[timerObjectKey][zoneName] = setTimeout(() => {
531
- this._asyncSetZoneTimer_doOnTimeout(zoneName, timerObjectKey, targets, zoneOffAfter);
532
- }, zoneOffAfter * 1000);
533
-
534
- // Some log
535
- if (timeLeft > -1) {
536
- this.adapter.x.helper.logExtendedInfo(`Trigger [${this.triggerName}] 'zoneOff' ${zoneOffAfter}s timer still running ${(timeLeft / 1000).toFixed(0)}s. We stop it and set new to ${zoneOffAfter}s.`);
537
- } else {
538
- this.adapter.x.helper.logExtendedInfo(`Trigger [${this.triggerName}] 'zoneOff' ${zoneOffAfter}s timer for zone '${zoneName}' initially started.`);
539
- }
540
-
541
- } catch (error) {
542
- this.adapter.x.helper.dumpError(`[asyncSetZoneTimer_zoneOff]`, error);
543
- return;
544
- }
545
-
546
- }
547
-
548
-
549
- /**
550
- * Set timeout to switch devices of a zone off, if a motion sensor was triggered and switch off time (duration) is provided.
551
- * @param {string} zoneName - Zone Name
552
- */
553
- async asyncSetZoneTimer_motion(zoneName) {
554
-
555
- try {
556
-
557
- // Go out if no duration is set
558
- if (!this.motionDuration || this.motionDuration <= 0) throw (`No motion duration set for ${this.triggerName}.`);
559
-
560
- // Get current target devices info
561
- const targets = await this._asyncGetTargetDevicesInfoOfZone(zoneName); // {statePaths:[Array of state paths], stateValues: [Array of state values], deviceNames: [Array of device names]}
562
-
563
- if (!targets) {
564
- // No targets found for ${zoneName}
565
- return; // We already logged in _asyncGetTargetDevicesInfoOfZone()
566
- }
567
-
568
- // First: clear timers. Note: we use timeLeft since we need this anyways for log.
569
- if (this.motionTimer) {
570
- const timeLeft = this.adapter.x.helper.getTimeoutTimeLeft(this.motionTimer);
571
- if (timeLeft > -1) {
572
- this.adapter.log.debug(`Trigger [${this.triggerName}] Zone '${zoneName}': Timer for ${this.triggerName} still running ${(timeLeft / 1000).toFixed(0)} seconds but a new motion from this sensor detected, which is associated to same zone. Therefore, we stop timer and set new.`);
573
- clearTimeout(this.motionTimer);
574
- this.motionTimer = null;
575
- }
576
- }
577
-
578
- // Set timer
579
- this.motionTimer = setTimeout(() => {
580
- if (!this.motionDuration) return;
581
- this._asyncSetZoneTimer_doOnTimeout(zoneName, 'Motion', targets, this.motionDuration);
582
- }, this.motionDuration * 1000);
583
- this.adapter.x.helper.logExtendedInfo(`Trigger [${this.triggerName}] Motion sensor '${this.triggerName}', zone '${zoneName}': No more motion, so we set ${this.motionDuration}s timer.`);
584
-
585
- } catch (error) {
586
- this.adapter.x.helper.dumpError(`[asyncSetZoneTimer_motion]`, error);
587
- return;
588
- }
589
-
590
- }
591
-
592
- /**
593
- * Check if additional conditions are met (like Public Holiday, etc. -- as set in conditions table).
594
- *
595
- * @param {string} name - Any name, for logging only
596
- * @param {array} conditionNames - Array of condition names
597
- * @param {boolean} allMustMeet - if true: all conditions must be met, if false: one condition is enough
598
- * @param {boolean} [inverse] - if true: inverse results (true -> false, and vice versa)
599
- * @return {Promise<boolean>} True if condition(s) met, false if not. Also return true, if empty conditionNames array
600
- */
601
- async asyncAreScheduleConditionsMet(name, conditionNames, allMustMeet, inverse = false) {
602
-
603
- try {
604
-
605
- // If empty array, we return true, as we need to continue if no conditions are set in the options table.
606
- if (this.adapter.x.helper.isLikeEmpty(conditionNames)) {
607
- this.adapter.log.debug(`Trigger [${this.triggerName}], ${name} - no conditions defined, so we return "true" to continue.`);
608
- return true;
609
- }
610
-
611
- let hitCount = 0;
612
-
613
- this.adapter.log.debug(`Trigger [${this.triggerName}], ${name} - check if conditions met: '${JSON.stringify(conditionNames)}'`);
614
- const notMetConditionNames = [];
615
- for (const lpConditionName of conditionNames) {
616
-
617
- if (hitCount > 0 && allMustMeet == false) break;
618
-
619
- const lpConditionStatePath = this.adapter.getOptionTableValue('tableConditions', 'name', lpConditionName, 'conditionState');
620
- const lpConditionStateValue = this.adapter.getOptionTableValue('tableConditions', 'name', lpConditionName, 'conditionValue');
621
-
622
- if (!lpConditionStatePath) {
623
- this.adapter.log.error(`asyncAreScheduleConditionsMet(): condition details for '${lpConditionName}' could not be found.`);
624
- notMetConditionNames.push(lpConditionName);
625
- if (allMustMeet) { break; } else { continue; }
626
- }
627
-
628
- const lpStateVal = await this.adapter.x.helper.asyncGetForeignStateValue(lpConditionStatePath);
629
- if (lpStateVal == null) {
630
- notMetConditionNames.push(lpConditionName);
631
- if (allMustMeet) { break; } else { continue; }
632
- }
633
-
634
- /**
635
- * Finally, compare the config table state value with the actual state value
636
- */
637
- // First: do we have comparator
638
- const res = this.adapter.x.helper.isNumComparatorMatching(lpStateVal, lpConditionStateValue);
639
- if (res.isComparator && res.result) {
640
- this.adapter.log.debug(`Trigger [${this.triggerName}], ${name} - condition '${lpConditionName}' *met* (options val = '${lpConditionStateValue}', actual state val = '${lpStateVal}')`);
641
- hitCount++;
642
- if (allMustMeet) { continue; } else { break; }
643
-
644
- // Next: no comparator, so compare directly with ==
645
- } else if (lpConditionStateValue == lpStateVal) {
646
- this.adapter.log.debug(`Trigger [${this.triggerName}], ${name} - condition '${lpConditionName}' *met* (options val = '${lpConditionStateValue}', actual state val = '${lpStateVal}')`);
647
- hitCount++;
648
- if (allMustMeet) { continue; } else { break; }
649
- } else {
650
- // No hit, so go out!
651
- this.adapter.log.debug(`Trigger [${this.triggerName}], ${name} - condition '${lpConditionName}' *not* met (options val = '${lpConditionStateValue}', actual state val = '${lpStateVal}')`);
652
- notMetConditionNames.push(lpConditionName);
653
- if (allMustMeet) { break; } else { continue; }
654
- }
655
-
656
- }
657
-
658
- let result = false;
659
- if ((allMustMeet && (hitCount == conditionNames.length)) || (!allMustMeet && (hitCount > 0)))
660
- result = true;
661
-
662
- if (inverse) result = !result;
663
-
664
- if (result) {
665
- this.adapter.log.debug(`Trigger [${this.triggerName}], ${name} - final result: condition matching`);
666
- return true;
667
- } else {
668
- if (!inverse) this.adapter.log.debug(`Trigger [${this.triggerName}], ${name} - final result: *not* matching conditions: ${notMetConditionNames.toString()}`);
669
- if (inverse) this.adapter.log.debug(`Trigger [${this.triggerName}], ${name} - final result: *not* matching conditions`); // to avoid empty 'notMetConditionNames'
670
- return false;
671
- }
672
-
673
- } catch (error) {
674
- this.adapter.x.helper.dumpError('[asyncAreScheduleConditionsMet()]', error);
675
- return false;
676
- }
677
-
678
- }
679
-
680
- /**
681
- * Set/update zoneNames and zoneTargetNames.
682
- * Call once a trigger that was triggered
683
- * @return {Promise<boolean>} true if successful, false if errors
684
- */
685
- async _asyncUpdateCurrentActiveZones() {
686
-
687
- try {
688
-
689
- /**
690
- * Get zone names, and zone-specific target names and execution
691
- * Loop next iteration, if not successful.
692
- */
693
-
694
- this.zoneNames = Array(); // Zone names that were triggered and which match with a schedule row name
695
- this.zoneTargetNames = {}; // Target devices per zone, like {Hallway:['Hallway Light'], Bath:['Bath Light', 'Bath Radio']}
696
-
697
- for (const lpRowZones of this.adapter.config.tableZones) {
698
-
699
- // Loop next if item in table "Zones" is not containing any trigger name in column triggers
700
- if (!(lpRowZones.active && lpRowZones.triggers && Array.isArray(lpRowZones.triggers) && lpRowZones.triggers.includes(this.triggerName))) continue;
701
-
702
- // Add target devices
703
- this.zoneTargetNames[lpRowZones.name] = lpRowZones.targets;
704
-
705
- // Execution options
706
- //const executeAlways = this.adapter.config.execution[lpRowZones.name].executeAlways;
707
- const executeAlways = (lpRowZones.executeAlways) ? true : false;
708
- let tablesZoneExecution = [];
709
- if (executeAlways) {
710
- // we create a dummy to always execute
711
- tablesZoneExecution = [{
712
- active: true,
713
- executeAlways: true // This is a "dummy" key, so that we know to always execute
714
- }];
715
- } else {
716
- tablesZoneExecution = (lpRowZones.executionJson) ? JSON.parse(lpRowZones.executionJson) : [];
717
- }
718
-
719
- for (const lpRow of tablesZoneExecution) {
720
-
721
- if (lpRow.active) {
722
-
723
- this.adapter.log.debug(`Trigger [${this.triggerName}] === check schedule conditions ===`);
724
-
725
- if (lpRow.executeAlways) {
726
- this.adapter.log.debug(`Trigger [${this.triggerName}] Zone '${lpRowZones.name}' - 'Execute always is activated, so continue'`);
727
- this.zoneNames.push(lpRowZones.name);
728
- } else {
729
-
730
- // A few variables / constants
731
- const tsCurrent = Date.now(); // the current timestamp
732
- let doContinue = true; // flag if we can continue.
733
-
734
- // First – check if current time is within the schedule times
735
- if (doContinue) doContinue = this.adapter.x.helper.scheduleIsTimeStampWithinPeriod(tsCurrent, lpRow.start, lpRow.end, lpRowZones.name);
736
-
737
- // Next, check if current day is within the mon-sun options as set in schedules tables.
738
- if (doContinue) doContinue = this.adapter.x.helper.scheduleIsWeekdayMatching(lpRow, tsCurrent, lpRowZones.name);
739
-
740
- // Next, check additional conditions (like Public Holiday, etc. -- as set in conditions table)
741
- if (doContinue) doContinue = await this.asyncAreScheduleConditionsMet('Zone Execution: Additional Conditions', lpRow.additionalConditions, lpRow.additionalConditionsAll);
742
-
743
- // Next, check conditions "Never if"
744
- if (doContinue) doContinue = await this.asyncAreScheduleConditionsMet('Zone Execution: "never if" Conditions', lpRow.never, lpRow.neverAll, true);
745
-
746
- // All checks done.
747
- if (doContinue) {
748
- this.adapter.log.debug(`Trigger [${this.triggerName}] Zone '${lpRowZones.name}' - execution table row *is* meeting conditions`);
749
- /* isHit == true; */
750
- this.zoneNames.push(lpRowZones.name); // set matching zone name
751
- } else {
752
- this.adapter.log.debug(`Trigger [${this.triggerName}] Zone '${lpRowZones.name}' - execution table row is *not* meeting conditions`);
753
- }
754
- }
755
-
756
- }
757
-
758
- }
759
-
760
- }
761
-
762
- if (this.adapter.x.helper.isLikeEmpty(this.zoneNames) || this.adapter.x.helper.isLikeEmpty(this.zoneTargetNames)) {
763
- this.adapter.log.debug(`Trigger [${this.triggerName}] Zone(s) will not be activated since no zone found which meets all conditions.`);
764
- return false;
765
- } else {
766
- this.adapter.log.debug(`Trigger [${this.triggerName}] - (${this.zoneNames.length}) rows in Zones table found and assigned execution table rows fetched successfully.`);
767
- return true;
768
- }
769
-
770
-
771
- } catch (error) {
772
- this.adapter.x.helper.dumpError('[_asyncUpdateCurrentActiveZones]', error);
773
- return false;
774
- }
775
-
776
-
777
- }
778
-
779
-
780
- /**
781
- * @param {string} zoneName - Name of zone
782
- * @param {string} timerTitle - For logging only.
783
- * @param {object} targets - {statePaths:['x', 'y'], stateValues: ['m', 'n'], deviceNames: ['a','b']};
784
- * @param {number} secTimer - Number of seconds of the timer, that was set and now expired. For logging only.
785
- */
786
- async _asyncSetZoneTimer_doOnTimeout(zoneName, timerTitle, targets, secTimer) {
787
-
788
- try {
789
-
790
- // First check if tableZones 'Never switch off if...' is met
791
- const neverOffConditionNames = this.adapter.getOptionTableValue('tableZones', 'name', zoneName, 'neverOff');
792
- const allMustMeet = this.adapter.getOptionTableValue('tableZones', 'name', zoneName, 'neverOffAll');
793
- const switchOff = await this.asyncAreScheduleConditionsMet('Zones table - "never switch off if" condition', neverOffConditionNames, allMustMeet, true);
794
- if (!switchOff) {
795
- this.adapter.x.helper.logExtendedInfo(`Trigger [${this.triggerName}] Zone '${zoneName}': Timer '${timerTitle}' ended, but 'Never switch off if...' condition(s) true --> Zone will not be switched off.`);
796
- return; // go out
797
- }
798
-
799
- // Next, cancel all timers to ensure that another timer is not running.
800
- const timerObjIds = ['timersZoneOff', 'timersMimicMotionTrigger'];
801
- for (const lpTimerObjId of timerObjIds) {
802
- const lpTimeLeft = this.adapter.x.helper.getTimeoutTimeLeft(this.adapter.x[lpTimerObjId][zoneName]);
803
- if (this.triggerIsMotion && (lpTimeLeft > -1)) {
804
- clearTimeout(this.adapter.x[lpTimerObjId][zoneName]);
805
- this.adapter.x[lpTimerObjId][zoneName] = null;
806
- this.adapter.log.debug(`Trigger [${this.triggerName}] Zone '${zoneName}': Clearing timer '${lpTimerObjId}', which was still running for ${(lpTimeLeft / 1000).toFixed(0)} seconds.`);
807
- }
808
- }
809
-
810
-
811
- /* ================== START -- RESOLVING ISSUE #45 (https://github.com/Mic-M/ioBroker.smartcontrol/issues/45) */
812
-
813
- /**
814
- * Verify if there are other motion sensors in the same zone.
815
- * If yes and if a motion detection of one of these is still true: do not switch off zone.
816
- */
817
- // Get all motion sensor trigger names
818
- const allMotionNames = [];
819
- for (const lpMotionRow of this.adapter.config.tableTriggerMotion) {
820
- if (lpMotionRow.active) {
821
- allMotionNames.push(lpMotionRow.name);
822
- }
823
- }
824
- // Get all other motion triggers assigned to zone
825
- const confZoneOtherTriggersMotion = [];
826
- const confZoneTriggersAll = this.adapter.getOptionTableValue('tableZones', 'name', zoneName, 'triggers');
827
- for (const lpTriggerName of confZoneTriggersAll) {
828
- if (allMotionNames.includes(lpTriggerName)) {
829
- if (lpTriggerName !== this.triggerName) {
830
- // we have an additional motion sensor trigger
831
- confZoneOtherTriggersMotion.push(lpTriggerName);
832
- }
833
- }
834
- }
835
-
836
- // Now check if motion state of any other motion timer is still true
837
- if (confZoneOtherTriggersMotion.length > 0) {
838
- for (const lpName of confZoneOtherTriggersMotion) {
839
- const lpMotionObjId = this.adapter.getOptionTableValue('tableTriggerMotion', 'name', lpName, 'stateId');
840
- const lpMotionObj = await this.adapter.x.helper.asyncGetForeignStateValue(lpMotionObjId);
841
- if (lpMotionObj == true) {
842
- // We have another motion sensor in same zone with motion=true, so go out.
843
- this.adapter.x.helper.logExtendedInfo(`Trigger [${this.triggerName}] Zone '${zoneName}': Timer '${timerTitle}' ended, but another motion sensor '${lpName}' state value assigned to this zone is still true, so we will not switch off zone.' `);
844
- return; // go out
845
- }
846
- }
847
- }
848
-
849
- /* ================== END -- RESOLVING ISSUE #45 (https://github.com/Mic-M/ioBroker.smartcontrol/issues/45) */
850
-
851
-
852
- // Set "is Zone on" status to false
853
- this.adapter.x.zonesIsOn[zoneName] = false;
854
-
855
- // Clear timer 'timersZoneOn'
856
- clearTimeout(this.adapter.x.timersZoneOn[zoneName]);
857
- this.adapter.x.timersZoneOn[zoneName] = null;
858
-
859
- const lTargetDevicesSwitchedOff = []; // For Log
860
- const lManualOnDevices = []; // For log
861
- for (let i = 0; i < targets.statePaths.length; i++) {
862
-
863
- // All are having same length and association per each element
864
- const lpStatePath = targets.statePaths[i];
865
- const lpStateValToSet = targets.stateValues[i];
866
- const lpTargetName = targets.deviceNames[i];
867
-
868
- // Remove from this.adapter.x.motionTriggeredDevices
869
- if (this.motionNotIfManual) this.adapter.x.motionTriggeredDevices = this.adapter.x.helper.arrayRemoveElementByValue(this.adapter.x.motionTriggeredDevices, lpTargetName);
870
-
871
- // Check if current value != new value
872
- const targetOffStateValCurrent = await this.adapter.x.helper.asyncGetForeignStateValue(lpStatePath);
873
- if (targetOffStateValCurrent == null) {
874
- this.adapter.log.error(`Timer '${timerTitle}', trigger '${this.triggerName}', target ${lpTargetName}: - Timeout of '${secTimer}' seconds reached, but could not get current state value of '${lpStatePath}', so unable to turn device off.`);
875
- continue;
876
- }
877
- if (lpStateValToSet == targetOffStateValCurrent) {
878
- this.adapter.x.helper.logExtendedInfo(`Trigger [${this.triggerName}] Timer '${timerTitle}', target ${lpTargetName}: - Timeout of '${secTimer}' seconds reached, target is already turned off, so not turning off again.`);
879
- continue;
880
- }
881
-
882
- // All passed.
883
- await this.adapter.setForeignStateAsync(lpStatePath, { val: lpStateValToSet, ack: false });
884
- lTargetDevicesSwitchedOff.push(lpTargetName);
885
-
886
- }
887
-
888
- // Log
889
- if (lManualOnDevices.length > 0) {
890
- this.adapter.x.helper.logExtendedInfo(`Trigger [${this.triggerName}] Timer '${timerTitle}', target(s) '${lManualOnDevices.toString()}': - Timeout of '${secTimer}' seconds reached, target(s) manually turned on while timer was running, so do not turn off.`);
891
- }
892
- if (lTargetDevicesSwitchedOff.length > 0) {
893
- this.adapter.x.helper.logExtendedInfo(`Trigger [${this.triggerName}] Timer '${timerTitle}', target(s) '${lTargetDevicesSwitchedOff.toString()}': - Turned off per ${secTimer}s timer.`);
894
- }
895
-
896
-
897
- } catch (error) {
898
- this.adapter.x.helper.dumpError('[asyncSetZoneTimer_doOnTimeout]', error);
899
- return;
900
- }
901
-
902
- }
903
-
904
- /**
905
- * Get target device info for a given zone name.
906
- * @param {string} zoneName - Zone Name
907
- * @return {Promise<object|null>} - Object: {statePaths:[Array of state paths], stateValues: [Array of state values], deviceNames: [Array of device names]}. null if not found/errors.
908
- */
909
- async _asyncGetTargetDevicesInfoOfZone(zoneName) {
910
-
911
- try {
912
-
913
- if (!this.zoneTargetNames || !this.zoneTargetNames[zoneName] || this.adapter.x.helper.isLikeEmpty(this.zoneTargetNames[zoneName])) {
914
- this.adapter.log.debug(`Trigger [${this.triggerName}] Zone '${zoneName}': No current target devices found for timer to switch devices off, likely because all were turned on manually before`);
915
- return null;
916
- }
917
- const targetDevices = this.zoneTargetNames[zoneName];
918
- //const targetDevices = this.adapter.getOptionTableValue('tableZones', 'name', zoneName, 'targets');
919
-
920
- // Get all target device state paths and values
921
- const targets = {
922
- statePaths: Array(), // Would use [] instead of Array(), but see: https://stackoverflow.com/a/56394664
923
- stateValues: Array(),
924
- deviceNames: Array(),
925
- };
926
-
927
- for (const lpTargetName of targetDevices) {
928
- // Get target device information
929
- const targetOffState = this.adapter.getOptionTableValue('tableTargetDevices', 'name', lpTargetName, 'offState');
930
- const targetOffVal = this.adapter.getOptionTableValue('tableTargetDevices', 'name', lpTargetName, 'offValue');
931
-
932
- if (targetOffState == undefined || targetOffVal == undefined) {
933
- throw (`Unable to retrieve target off state/value for target device '${lpTargetName}' from adapter config.`);
934
- }
935
-
936
- // Target Off State
937
- if (await this.adapter.getForeignObjectAsync(targetOffState)) {
938
- // State is existing
939
- targets.statePaths.push(targetOffState);
940
- targets.stateValues.push(targetOffVal);
941
- targets.deviceNames.push(lpTargetName);
942
- } else {
943
- // State is not existing
944
- this.adapter.log.error(`State '${targetOffState}' of device '${lpTargetName}' does not exist.`);
945
- }
946
- }
947
-
948
- // Go out if we actually have no devices to turn off
949
- if (this.adapter.x.helper.isLikeEmpty(targets.statePaths)) {
950
- throw (`Zone '${zoneName}': --> No target states found in adapter settings, so no timer will be set to turn off.`);
951
- }
952
-
953
- return targets;
954
-
955
- } catch (error) {
956
- this.adapter.x.helper.dumpError(`[asyncGetTargetDevicesInfoOfZone]`, error);
957
- return null;
958
- }
959
-
960
- }
961
-
962
-
963
-
964
- }
1
+ 'use strict';
2
+ /* eslint-disable no-inner-declarations -- // cite: *prior to ES6*, a function declaration is only allowed in the first level of a program or the body of another function */
3
+
4
+ /**
5
+ * @class Trigger
6
+ * @desc For handling of triggers and their associated target devices.
7
+ * Every instance of this class is a specific trigger (motion sensor/'other device'/time trigger)
8
+ * @author Mic-M <https://github.com/Mic-M/ioBroker.smartcontrol>
9
+ * @license MIT
10
+ *
11
+ * Initial Properties:
12
+ * ---Generic Properties---
13
+ * {string} triggerName Name of Trigger
14
+ * {string} triggerTableId table name: 'tableTriggerDevices', 'tableTriggerMotion', or 'tableTriggerTimes'
15
+ * {string} triggerStatePath State Path of Trigger, if a state
16
+ * {string} triggerStateVal Trigger state value from Options Table
17
+ * {string} triggerIsToggle Trigger is a toggle, so isToggle is true in tableTriggerDevices
18
+ * {boolean} targetOff If true, targets will be switched off, and not on.
19
+ * ---Motion Trigger---
20
+ * {boolean} triggerIsMotion Is trigger a motion sensor?
21
+ * {boolean} motionNotIfManual if true: motion trigger should not set timeout if target device was turned on previously without a motion trigger.
22
+ * {number} motionDuration Duration (timer) in seconds for motion sensor
23
+ * {string} motionBriStatePath State Path of brightness state
24
+ * {number} motionBriThreshold Threshold of brightness
25
+ * {object} motionTimer Timer object for motion to switch targets off
26
+ * {boolean} mimicMotion For trigger devices linked/associated with a motion sensor (tableTriggerMotion -> motionLinkedTrigger)
27
+ * {string} mimicMotionTriggerName Trigger name of device linked to motion sensor
28
+ * {boolean} mimicMotionIgnoreMotionOn Ignore motion if motion sensor is set to true
29
+ * ---Time Trigger---
30
+ * {boolean} triggerIsTime Is trigger a time trigger?
31
+ * {string} triggerTime If time trigger: time like '42 * * * *' or 'sunset+30'
32
+ * {array} triggerTmAdditionCond Array of additional condition names for "Must be fulfilled"
33
+ * {boolean} triggerTmAddCondAll if true: all conditions must be met, if false: at least one condition must be met
34
+ * {string} triggerTmNever Array of additional condition names for "Never" which shall not be
35
+ * {boolean} triggerTmNeverAll if true: all conditions must be met, if false: at least one condition must be met
36
+ *
37
+ * Properties set by this._asyncUpdateCurrentActiveZones()
38
+ * {array} zoneNames All zone names that were triggered and meet all conditions
39
+ * {object} zoneTargetNames All target device names per zone, like {Hallway:['Hallway Light'], Bath:['Light', 'Radio Bath']}
40
+ * NOTE: Motion Trigger - If target was already turned on previously by a non-motion trigger:
41
+ * We will remove that device to not schedule timer, if motionNotIfManual
42
+ *
43
+ */
44
+ class Trigger {
45
+
46
+ /**
47
+ * Constructor
48
+ *
49
+ * @param {object} adapter - ioBroker adapter instance object
50
+ * @param {string} triggerName - Name of trigger.
51
+ */
52
+ constructor(adapter, triggerName) {
53
+ this.adapter = adapter;
54
+ this.triggerName = triggerName;
55
+ this.zoneOffTimer = null;
56
+ this._init();
57
+ }
58
+
59
+ /**
60
+ * Set properties (retrieving from adapter configuration)
61
+ */
62
+ _init() {
63
+
64
+ try {
65
+
66
+ this.triggerStatePath = undefined; // set below accordingly if state
67
+ this.triggerStateVal = undefined; // set below accordingly if state
68
+ this.triggerIsMotion = false; // set to true below, if motion
69
+ this.triggerIsToggle = false; // set to true below, if tableTriggerDevices.isToggle=true
70
+ this.targetOff = false; // set to true below, if activated in other devices or time trigger table
71
+ this.mimicMotion = false; // set accordingly in main.js
72
+ this.mimicMotionTriggerName = undefined; // set accordingly in main.js
73
+ this.mimicMotionIgnoreMotionOn = false; // set to true below, if tableTriggerMotion.ignoreMotionOn is true
74
+
75
+ /**
76
+ * Get all triggered table rows and set properties accordingly.
77
+ */
78
+ const result = { row: {}, tableId: '' };
79
+ for (const lpTable of ['tableTriggerDevices', 'tableTriggerMotion', 'tableTriggerTimes']) {
80
+ for (const lpRow of this.adapter.config[lpTable]) {
81
+ if (lpRow.active && lpRow.name == this.triggerName) {
82
+ result.row = lpRow;
83
+ result.tableId = lpTable;
84
+ break;
85
+ }
86
+ }
87
+ if (result.index > -1) break;
88
+ }
89
+
90
+ switch (result.tableId) {
91
+
92
+ case 'tableTriggerDevices':
93
+ this.triggerTableId = result.tableId;
94
+ this.triggerStatePath = result.row.stateId;
95
+ this.triggerStateVal = result.row.stateVal;
96
+ this.triggerIsToggle = result.row.isToggle;
97
+ this.targetOff = result.row.targetOff;
98
+ break;
99
+
100
+ case 'tableTriggerMotion':
101
+ this.triggerTableId = result.tableId;
102
+ this.triggerIsMotion = true;
103
+ this.motionTimer = null;
104
+ this.triggerStatePath = result.row.stateId;
105
+ this.triggerStateVal = true; // is always true for motion sensors to indicate if on
106
+ this.motionNotIfManual = result.row.notIfManual;
107
+ this.mimicMotionIgnoreMotionOn = result.row.ignoreMotionOn;
108
+
109
+ if (result.row.duration && parseInt(result.row.duration) > 0) {
110
+ this.motionDuration = parseInt(result.row.duration);
111
+ } else {
112
+ this.motionDuration = 0;
113
+ }
114
+ if (result.row.briThreshold && parseInt(result.row.briThreshold) > 0 && result.row.briStateId && result.row.briStateId.length > 5) {
115
+ this.motionBriStatePath = result.row.briStateId;
116
+ this.motionBriThreshold = result.row.briThreshold;
117
+ } else {
118
+ this.motionBriStatePath = '';
119
+ this.motionBriThreshold = 0;
120
+ }
121
+ break;
122
+
123
+ case 'tableTriggerTimes':
124
+ this.triggerTableId = result.tableId;
125
+ this.triggerIsTime = true;
126
+ this.targetOff = result.row.targetOff;
127
+ this.triggerTime = result.row.time;
128
+ this.triggerTmAdditionCond = result.row.additionalConditions;
129
+ this.triggerTmAddCondAll = result.row.additionalConditionsAll;
130
+ this.triggerTmNever = result.row.never;
131
+ this.triggerTmNeverAll = result.row.neverAll;
132
+ break;
133
+
134
+ default:
135
+ throw (`No active trigger '${this.triggerName}' found in any trigger table.`);
136
+ }
137
+
138
+ } catch (error) {
139
+ this.adapter.x.helper.dumpError('_init()]', error);
140
+ }
141
+
142
+ }
143
+
144
+ /**
145
+ * Set all target devices for all zones
146
+ * Note: No need to remove duplicates, this is being taken care of by asyncVerifyConfig() function.
147
+ * @fires _asyncSetTargetDevices_processZone()
148
+ */
149
+ async asyncSetTargetDevices() {
150
+
151
+ try {
152
+
153
+ await this._asyncUpdateCurrentActiveZones(); // update current active zone properties
154
+ if (!this.zoneNames || !this.zoneTargetNames) return;
155
+
156
+ // Timer zoneOn (delay for switching zone on)
157
+ for (const lpZoneName of this.zoneNames) {
158
+ clearTimeout(this.adapter.x.timersZoneOn[lpZoneName]);
159
+ this.adapter.x.timersZoneOn[lpZoneName] = null;
160
+ const zoneOnSecs = parseInt(this.adapter.getOptionTableValue('tableZones', 'name', lpZoneName, 'onAfter'));
161
+ if (!zoneOnSecs || zoneOnSecs < 1) {
162
+ this.adapter.log.debug(`Trigger [${this.triggerName}] Zone '${lpZoneName}' No 'On after x sec' time is set, so we do not set such delay (timer).`);
163
+ this._asyncSetTargetDevices_processZone(lpZoneName);
164
+ } else {
165
+ this.adapter.x.timersZoneOn[lpZoneName] = setTimeout(() => {
166
+ this._asyncSetTargetDevices_processZone(lpZoneName);
167
+ }, zoneOnSecs * 1000);
168
+ }
169
+ }
170
+
171
+ } catch (error) {
172
+ this.adapter.x.helper.dumpError('[asyncSetTargetDevices]', error);
173
+ }
174
+
175
+ }
176
+
177
+
178
+ /**
179
+ * Set all target devices: Process zone - Start
180
+ * @param {string} zoneName - Name of zone
181
+ */
182
+ async _asyncSetTargetDevices_processZone(zoneName) {
183
+
184
+ try {
185
+
186
+ if (!this.zoneNames || !this.zoneTargetNames) return;
187
+
188
+ /**
189
+ * Prepare: If Motion Sensor triggered - verify brightness if bri is set
190
+ */
191
+ if (!this.mimicMotion && this.triggerIsMotion && !this.adapter.x.helper.isLikeEmpty(this.motionBriStatePath) && this.adapter.x.helper.isNumber(this.motionBriThreshold) && parseInt(this.motionBriThreshold) > 0) {
192
+
193
+ if (this.adapter.config.motionIgnoreBriIfZoneOn && this.adapter.x.zonesIsOn[zoneName]) {
194
+ // Disregard Brightness if zone is on (if this.adapter.config.motionIgnoreBriIfZoneOn == true)
195
+ this.adapter.log.debug(`Trigger [${this.triggerName}] Zone '${zoneName}' is on and new motion detected, therefore, we disregard any current brightness.`);
196
+ } else {
197
+ // Verify brightness
198
+ const briStateObjCurr = await this.adapter.x.helper.asyncGetForeignState(this.motionBriStatePath); // {val: false, ack: true, ts: 1591117034451, …}
199
+ const briStateValCurrent = briStateObjCurr.val;
200
+ if (this.adapter.x.helper.isLikeEmpty(briStateValCurrent) || !this.adapter.x.helper.isNumber(briStateValCurrent) || parseInt(briStateValCurrent) < 0) {
201
+ // Bri not valid, so disregard bri and continue
202
+ this.adapter.log.debug(`Trigger [${this.triggerName}] Brightness of ${briStateValCurrent} of ${this.motionBriStatePath} is not valid. State Value: [${briStateValCurrent}]. Therefore, bri will be disregarded and we continue.`);
203
+ } else if (parseInt(briStateValCurrent) < parseInt(this.motionBriThreshold)) {
204
+ // continue
205
+ this.adapter.log.debug(`Trigger [${this.triggerName}] Brightness of ${briStateValCurrent} is < threshold of ${this.motionBriThreshold}, so we continue.`);
206
+ } else {
207
+ // Brightness condition is not met!
208
+ this.adapter.x.helper.logExtendedInfo(`Trigger [${this.triggerName}] activated but current brightness of ${briStateValCurrent} is >= threshold of ${this.motionBriThreshold} -> Motion disregarded.`);
209
+ return; // go out
210
+ }
211
+ }
212
+ } else if (!this.mimicMotion && this.triggerIsMotion) {
213
+ this.adapter.log.debug(`Trigger [${this.triggerName}] - no brightness defined for this motion sensor, so continue and do not use bri as an additional criterion.`);
214
+ }
215
+
216
+ /**
217
+ * Ignore motion sensor triggered motion=true, if mimicMotionIgnoreMotionOn set to true
218
+ */
219
+ const timeLeft = this.adapter.x.helper.getTimeoutTimeLeft(this.adapter.x.timersMimicMotionTrigger[zoneName]);
220
+ if (!this.mimicMotion && this.triggerStateVal && this.triggerIsMotion && this.mimicMotionIgnoreMotionOn) {
221
+ if (timeLeft > -1) {
222
+ this.adapter.log.debug(`Trigger [${this.triggerName}] - Zone ${zoneName}: 'Mimic motion' is active, so we take over`);
223
+ // timer will be canceled below
224
+ } else {
225
+ this.adapter.log.info(`Trigger [${this.triggerName}] - Zone ${zoneName}: No execution due to activated zone option 'ignore motion on'.`);
226
+ return;
227
+ }
228
+ }
229
+
230
+ // Clear "linked devices" (mimic motion) timer for motion trigger
231
+ if (this.triggerIsMotion && (timeLeft > -1)) {
232
+ clearTimeout(this.adapter.x.timersMimicMotionTrigger[zoneName]);
233
+ this.adapter.x.timersMimicMotionTrigger[zoneName] = null;
234
+ this.adapter.log.debug(`Clearing timer 'Linked device to motion', which was still running for ${(timeLeft / 1000).toFixed(0)} seconds.`);
235
+ }
236
+
237
+
238
+
239
+ /**
240
+ * -- Main --
241
+ * Loop thru the target device names and switch accordingly.
242
+ * Code supports delay, therefore, implementation is different as if we would not have this support (like processing all devices, then call finalize(), etc.)
243
+ */
244
+ const lSwitchedDevices = [];
245
+ const lAlreadyOnDevices = [];
246
+ const lDelayedDevices = [];
247
+ const lDelaySecs = []; // for each device, delay to turn on, e.g. [0, 10]
248
+ let onOff = 'on'; // for toggle
249
+
250
+ // get delay ('onAfter')
251
+ const targetsOverwrite = this.adapter.getOptionTableValue('tableZones', 'name', zoneName, 'targetsOverwrite'); // like: {'Hallway.Light':{val:'new val', delay:10}, 'Hallway.Radio':{val:'Radio XYZ'}}
252
+
253
+ let counterDevicesProcessed = 0; // Once all processed, we will call a function
254
+ for (const lpTargetDeviceName of this.zoneTargetNames[zoneName]) {
255
+
256
+ let delay = this.adapter.getOptionTableValue('tableTargetDevices', 'name', lpTargetDeviceName, 'onAfter');
257
+ if (delay !== undefined && this.adapter.x.helper.isNumber(delay) && parseInt(delay) > 0) {
258
+ delay = parseInt(delay);
259
+ } else {
260
+ delay = 0;
261
+ }
262
+ lDelaySecs.push(delay);
263
+
264
+ // Targets overwrite: state value, and delay
265
+ let overwriteValue = null;
266
+ if (targetsOverwrite && targetsOverwrite[lpTargetDeviceName]) {
267
+ if (!this.adapter.x.helper.isLikeEmpty(targetsOverwrite[lpTargetDeviceName].val)) {
268
+ overwriteValue = targetsOverwrite[lpTargetDeviceName].val;
269
+ }
270
+ if (targetsOverwrite[lpTargetDeviceName].delay!==undefined
271
+ && this.adapter.x.helper.isNumber(targetsOverwrite[lpTargetDeviceName].delay)
272
+ && parseInt(targetsOverwrite[lpTargetDeviceName].delay) > -1) {
273
+ delay = parseInt(targetsOverwrite[lpTargetDeviceName].delay);
274
+ }
275
+ }
276
+
277
+
278
+ /**
279
+ * let's call function switchTargetDevice()
280
+ */
281
+ // Timer (delay) to switch device on
282
+ if (delay > 0) lDelayedDevices.push(lpTargetDeviceName);
283
+ clearTimeout(this.adapter.x.timersZoneDeviceOnDelay[zoneName+'_'+ lpTargetDeviceName]);
284
+ this.adapter.x.timersZoneDeviceOnDelay[zoneName+'_'+ lpTargetDeviceName] = null;
285
+
286
+ if (delay > 0) {
287
+ // set timeout
288
+ this.adapter.x.timersZoneDeviceOnDelay[zoneName+'_'+ lpTargetDeviceName] = setTimeout(()=>{ switchTargetDeviceAsync(this); }, delay * 1000);
289
+ } else {
290
+ // call right away
291
+ await switchTargetDeviceAsync(this);
292
+ }
293
+
294
+ /**
295
+ * Function switchTargetDevice
296
+ * @param {object} that - this
297
+ */
298
+ async function switchTargetDeviceAsync(that) {
299
+
300
+ try {
301
+
302
+ if (!that.zoneTargetNames) return;
303
+
304
+ counterDevicesProcessed++; // +1
305
+
306
+ // If target device should be switched off, and not on, per config in trigger table
307
+ // Will be overwritten later if toggle is activated
308
+ if (that.targetOff) onOff = 'off';
309
+
310
+ // Toggle
311
+ if (that.triggerIsToggle) {
312
+ // If we have Toggle, we are using the ON state/value to check.
313
+ const onState = that.adapter.getOptionTableValue('tableTargetDevices', 'name', lpTargetDeviceName, 'onState');
314
+ const onVal = that.adapter.getOptionTableValue('tableTargetDevices', 'name', lpTargetDeviceName, 'onValue');
315
+ const currentStateVal = await that.adapter.x.helper.asyncGetForeignStateValue(onState);
316
+ if (currentStateVal == null) throw (`Could not get current state value for '${onState}' of device '${lpTargetDeviceName}'`);
317
+ if (onVal == currentStateVal) {
318
+ onOff = 'off';
319
+ } else {
320
+ onOff = 'on';
321
+ }
322
+ }
323
+
324
+ // Get option values.
325
+ const lpTargetState = that.adapter.getOptionTableValue('tableTargetDevices', 'name', lpTargetDeviceName, onOff + 'State');
326
+ let lpTargetVal = that.adapter.getOptionTableValue('tableTargetDevices', 'name', lpTargetDeviceName, onOff + 'Value');
327
+ const noTargetCheckStr = (onOff == 'on') ? 'noTargetOnCheck' : 'noTargetOffCheck';
328
+ const doNotCheckTarget = that.adapter.getOptionTableValue('tableTargetDevices', 'name', lpTargetDeviceName, noTargetCheckStr);
329
+
330
+ if (lpTargetState == undefined || lpTargetVal == undefined) {
331
+ throw (`Unable to retrieve target '${onOff}' state/value for target device '${lpTargetDeviceName}'`);
332
+ }
333
+
334
+ // Overwrite target values if according value is set in Zones table
335
+ if (onOff == 'on' && overwriteValue !== null) {
336
+ lpTargetVal = overwriteValue;
337
+ }
338
+
339
+ // Let's get current state value
340
+ let currentStateVal;
341
+ if (!doNotCheckTarget) {
342
+ currentStateVal = await that.adapter.x.helper.asyncGetForeignStateValue(lpTargetState);
343
+ if (currentStateVal == null) {
344
+ throw (`Could not get current state value for '${lpTargetState}' of device '${lpTargetDeviceName}'`);
345
+ }
346
+ }
347
+
348
+ // Set target state.
349
+ // Note: Verification of the state value and conversion as needed was performed already by asyncVerifyConfig()
350
+ // Check if device is already on.
351
+ if (doNotCheckTarget || (!doNotCheckTarget && (currentStateVal != lpTargetVal))) {
352
+
353
+ // Set state
354
+ await that.adapter.setForeignStateAsync(lpTargetState, { val: lpTargetVal, ack: false });
355
+ //if (delay == 0) lSwitchedDevices.push(lpTargetDeviceName);
356
+ lSwitchedDevices.push(lpTargetDeviceName);
357
+ if (that.motionNotIfManual) {
358
+ if (that.triggerIsMotion) {
359
+ // triggered by motion, so add to that.adapter.x.motionTriggeredDevices
360
+ if (that.adapter.x.motionTriggeredDevices.indexOf(lpTargetDeviceName) == -1) {
361
+ that.adapter.x.motionTriggeredDevices.push(lpTargetDeviceName);
362
+ }
363
+ } else {
364
+ //Triggered by NON-motion, so remove from that.adapter.x.motionTriggeredDevices
365
+ that.adapter.x.motionTriggeredDevices = that.adapter.x.helper.arrayRemoveElementByValue(that.adapter.x.motionTriggeredDevices, lpTargetDeviceName);
366
+ }
367
+ }
368
+ // set json log to smartcontrol.x.info.log.switchedTargetDevices.json
369
+ that.adapter.x.helper.setJsonLog('switchedTargetDevices', {
370
+ time: that.adapter.x.helper.dateToLocalIsoString(new Date()),
371
+ name: lpTargetDeviceName,
372
+ objectId: lpTargetState,
373
+ value: lpTargetVal,
374
+ triggerName: that.triggerName,
375
+ ts: Date.now(),
376
+ });
377
+
378
+ } else {
379
+ // do not set target state
380
+ // if (delay == 0) lAlreadyOnDevices.push(lpTargetDeviceName);
381
+ lAlreadyOnDevices.push(lpTargetDeviceName);
382
+ }
383
+
384
+ if (counterDevicesProcessed == that.zoneTargetNames[zoneName].length) {
385
+
386
+ /**
387
+ * All devices processed, so we continue here
388
+ */
389
+ if (!that.zoneTargetNames || !that.zoneNames) return;
390
+
391
+ /**
392
+ * Motion Trigger: If target was already turned on previously by a non-motion trigger: do not schedule timer.
393
+ * Also, provide some log info in logMotion
394
+ */
395
+ let logMotion = '';
396
+ if (!that.mimicMotion && that.triggerIsMotion && that.motionDuration && that.motionDuration > 0) {
397
+ const lRemovedDevices = [];
398
+ if (that.motionNotIfManual) {
399
+ for (const lpTargetDevice of lAlreadyOnDevices) {
400
+ if (that.adapter.x.motionTriggeredDevices.indexOf(lpTargetDevice) > -1) {
401
+ // Device was already on and motion triggered before.
402
+ } else {
403
+ // Device was already on, but NO motion triggered before.
404
+ // Therefore, we will exclude device from the timer
405
+ that.zoneTargetNames[zoneName] = that.adapter.x.helper.arrayRemoveElementByValue(that.zoneTargetNames[zoneName], lpTargetDevice);
406
+ lRemovedDevices.push(lpTargetDevice);
407
+ }
408
+ }
409
+ }
410
+ if (that.zoneTargetNames[zoneName].length < 1) {
411
+ logMotion = `No motion timer will be set to turn off since device(s) turned on manually before.`;
412
+ } else {
413
+ if (lRemovedDevices.length == 0) {
414
+ logMotion = `Timer of ${that.motionDuration}s will be set to turn off once no more motion recognized.`;
415
+ } else {
416
+ logMotion = `Timer of ${that.motionDuration}s will be set to turn off once no more motion recognized. Limited to '${that.zoneTargetNames[zoneName].toString()}'. ${lRemovedDevices.toString()} were turned on manually before.`;
417
+ }
418
+ }
419
+ }
420
+
421
+
422
+ /**
423
+ * Set "always off after" timer if set in Table Zones.
424
+ */
425
+ if (that.triggerIsToggle && onOff == 'off') {
426
+ // Toggle is activated and zone is turned off, so kill/delete the timer.
427
+ const zoneOffTimeLeft = that.adapter.x.helper.getTimeoutTimeLeft(that.adapter.x.timersZoneOff[zoneName]);
428
+ if (zoneOffTimeLeft > -1) {
429
+ that.adapter.log.debug(`Trigger [${that.triggerName}] Zone '${zoneName}': Turn off 'always off' timer, since still running ${(zoneOffTimeLeft / 1000).toFixed(0)} seconds and toggle trigger triggered to turn off.`);
430
+ clearTimeout(that.adapter.x.timersZoneOff[zoneName]);
431
+ that.adapter.x.timersZoneOff[zoneName] = null;
432
+ }
433
+
434
+ } else {
435
+ if (that.triggerIsMotion && (that.zoneTargetNames[zoneName].length < 1)) {
436
+ that.adapter.x.helper.logExtendedInfo(`Trigger [${that.triggerName}], Zone '${that.zoneNames.toString()}': no 'always off after' timer set since device(s) turned on manually before.`);
437
+ } else {
438
+ const zoneOffSecs = parseInt(that.adapter.getOptionTableValue('tableZones', 'name', zoneName, 'offAfter'));
439
+ that.asyncSetZoneTimer_zoneOff('timersZoneOff', zoneName, zoneOffSecs);
440
+ }
441
+ }
442
+
443
+ /**
444
+ * If "mimic motion": set off timer for zone
445
+ */
446
+ if (that.mimicMotion) {
447
+ const zoneOffSecs = parseInt(that.adapter.getOptionTableValue('tableTriggerMotion', 'name', that.triggerName, 'motionLinkedDuration'));
448
+ that.asyncSetZoneTimer_zoneOff('timersMimicMotionTrigger', zoneName, zoneOffSecs);
449
+ }
450
+
451
+
452
+ // Set "Zone is on" status
453
+ that.adapter.x.zonesIsOn[zoneName] = true;
454
+
455
+ /**
456
+ * JSON log for info.log.zoneActivations.json
457
+ */
458
+ const alwaysOff = parseInt(that.adapter.getOptionTableValue('tableZones', 'name', zoneName, 'offAfter'));
459
+ that.adapter.x.helper.setJsonLog('zoneActivations', {
460
+ ts: Date.now(),
461
+ time: that.adapter.x.helper.dateToLocalIsoString(new Date()),
462
+ zone: zoneName,
463
+ trigger: (!that.mimicMotion) ? that.triggerName : that.mimicMotionTriggerName,
464
+ targetsAll: that.zoneTargetNames[zoneName].toString(),
465
+ targetsAllDelays: JSON.stringify(lDelaySecs),
466
+ targetsSet: lSwitchedDevices.toString(),
467
+ targetsSkipped: lAlreadyOnDevices.toString(),
468
+ motionTimer: (that.motionDuration) ? that.motionDuration : 0,
469
+ alwaysOffTimer: (isNaN(alwaysOff)) ? 0 : alwaysOff,
470
+ });
471
+
472
+ // Finalize
473
+ if (lSwitchedDevices.length > 0) {
474
+ if (lAlreadyOnDevices.length < 1) {
475
+ that.adapter.x.helper.logExtendedInfo(`Trigger [${that.triggerName}] activated Zone '${zoneName}'. Turned ${onOff}: ${lSwitchedDevices.toString()}.`);
476
+ } else {
477
+ that.adapter.x.helper.logExtendedInfo(`Trigger [${that.triggerName}] activated Zone '${zoneName}'. Turned ${onOff}: ${lSwitchedDevices.toString()}. Not turned ${onOff} (as already ${onOff}): '${lAlreadyOnDevices.toString()}'`);
478
+ }
479
+ } else {
480
+ if (lAlreadyOnDevices.length > 0) that.adapter.x.helper.logExtendedInfo(`Trigger [${that.triggerName}] activated Zone '${zoneName}'. However, device(s) '${lAlreadyOnDevices.toString()}' not turned ${onOff} as these are already ${onOff}.`);
481
+ }
482
+ if (lDelayedDevices.length > 0) that.adapter.x.helper.logExtendedInfo(`Trigger [${that.triggerName}] Following device(s) will be switched ${onOff} later, since a delay was set: ${lDelayedDevices.toString()}.`);
483
+ if (logMotion) that.adapter.x.helper.logExtendedInfo(`Trigger [${that.triggerName}] Zone '${zoneName}': ${logMotion}`);
484
+
485
+ }
486
+
487
+ } catch (error) {
488
+ that.adapter.x.helper.dumpError(`[switchTargetDevice]`, error);
489
+ return;
490
+ }
491
+
492
+ }
493
+
494
+ }
495
+
496
+
497
+ } catch (error) {
498
+ this.adapter.x.helper.dumpError(`[_asyncSetTargetDevices_processZone]`, error);
499
+ return;
500
+ }
501
+ }
502
+
503
+
504
+ /**
505
+ * Set timeout to switch devices of a zone off for zoneOff timer
506
+ * @param {string} timerObjectKey - e.g. 'timersZoneOff' or 'timersMimicMotionTrigger'
507
+ * @param {string} zoneName - Zone Name
508
+ * @param {number} zoneOffAfter - Switch zone off after this number of seconds
509
+ */
510
+ async asyncSetZoneTimer_zoneOff(timerObjectKey, zoneName, zoneOffAfter) {
511
+
512
+ try {
513
+
514
+ if (!zoneOffAfter || zoneOffAfter < 1) {
515
+ this.adapter.log.debug(`Trigger [${this.triggerName}] Zone '${zoneName}' No 'Always off after' time is set, so we do not set such timer.`);
516
+ return;
517
+ }
518
+
519
+ // Get current target devices info
520
+ const targets = await this._asyncGetTargetDevicesInfoOfZone(zoneName);
521
+
522
+ // First: clear timers. Note: we use timeLeft since we need this anyways for log.
523
+ const timeLeft = this.adapter.x.helper.getTimeoutTimeLeft(this.adapter.x[timerObjectKey][zoneName]);
524
+ if (timeLeft > -1) {
525
+ clearTimeout(this.adapter.x[timerObjectKey][zoneName]);
526
+ this.adapter.x[timerObjectKey][zoneName] = null;
527
+ }
528
+
529
+ // Set timer
530
+ this.adapter.x[timerObjectKey][zoneName] = setTimeout(() => {
531
+ this._asyncSetZoneTimer_doOnTimeout(zoneName, timerObjectKey, targets, zoneOffAfter);
532
+ }, zoneOffAfter * 1000);
533
+
534
+ // Some log
535
+ if (timeLeft > -1) {
536
+ this.adapter.x.helper.logExtendedInfo(`Trigger [${this.triggerName}] 'zoneOff' ${zoneOffAfter}s timer still running ${(timeLeft / 1000).toFixed(0)}s. We stop it and set new to ${zoneOffAfter}s.`);
537
+ } else {
538
+ this.adapter.x.helper.logExtendedInfo(`Trigger [${this.triggerName}] 'zoneOff' ${zoneOffAfter}s timer for zone '${zoneName}' initially started.`);
539
+ }
540
+
541
+ } catch (error) {
542
+ this.adapter.x.helper.dumpError(`[asyncSetZoneTimer_zoneOff]`, error);
543
+ return;
544
+ }
545
+
546
+ }
547
+
548
+
549
+ /**
550
+ * Set timeout to switch devices of a zone off, if a motion sensor was triggered and switch off time (duration) is provided.
551
+ * @param {string} zoneName - Zone Name
552
+ */
553
+ async asyncSetZoneTimer_motion(zoneName) {
554
+
555
+ try {
556
+
557
+ // Go out if no duration is set
558
+ if (!this.motionDuration || this.motionDuration <= 0) throw (`No motion duration set for ${this.triggerName}.`);
559
+
560
+ // Get current target devices info
561
+ const targets = await this._asyncGetTargetDevicesInfoOfZone(zoneName); // {statePaths:[Array of state paths], stateValues: [Array of state values], deviceNames: [Array of device names]}
562
+
563
+ if (!targets) {
564
+ // No targets found for ${zoneName}
565
+ return; // We already logged in _asyncGetTargetDevicesInfoOfZone()
566
+ }
567
+
568
+ // First: clear timers. Note: we use timeLeft since we need this anyways for log.
569
+ if (this.motionTimer) {
570
+ const timeLeft = this.adapter.x.helper.getTimeoutTimeLeft(this.motionTimer);
571
+ if (timeLeft > -1) {
572
+ this.adapter.log.debug(`Trigger [${this.triggerName}] Zone '${zoneName}': Timer for ${this.triggerName} still running ${(timeLeft / 1000).toFixed(0)} seconds but a new motion from this sensor detected, which is associated to same zone. Therefore, we stop timer and set new.`);
573
+ clearTimeout(this.motionTimer);
574
+ this.motionTimer = null;
575
+ }
576
+ }
577
+
578
+ // Set timer
579
+ this.motionTimer = setTimeout(() => {
580
+ if (!this.motionDuration) return;
581
+ this._asyncSetZoneTimer_doOnTimeout(zoneName, 'Motion', targets, this.motionDuration);
582
+ }, this.motionDuration * 1000);
583
+ this.adapter.x.helper.logExtendedInfo(`Trigger [${this.triggerName}] Motion sensor '${this.triggerName}', zone '${zoneName}': No more motion, so we set ${this.motionDuration}s timer.`);
584
+
585
+ } catch (error) {
586
+ this.adapter.x.helper.dumpError(`[asyncSetZoneTimer_motion]`, error);
587
+ return;
588
+ }
589
+
590
+ }
591
+
592
+ /**
593
+ * Check if additional conditions are met (like Public Holiday, etc. -- as set in conditions table).
594
+ *
595
+ * @param {string} name - Any name, for logging only
596
+ * @param {array} conditionNames - Array of condition names
597
+ * @param {boolean} allMustMeet - if true: all conditions must be met, if false: one condition is enough
598
+ * @param {boolean} [inverse] - if true: inverse results (true -> false, and vice versa)
599
+ * @return {Promise<boolean>} True if condition(s) met, false if not. Also return true, if empty conditionNames array
600
+ */
601
+ async asyncAreScheduleConditionsMet(name, conditionNames, allMustMeet, inverse = false) {
602
+
603
+ try {
604
+
605
+ // If empty array, we return true, as we need to continue if no conditions are set in the options table.
606
+ if (this.adapter.x.helper.isLikeEmpty(conditionNames)) {
607
+ this.adapter.log.debug(`Trigger [${this.triggerName}], ${name} - no conditions defined, so we return "true" to continue.`);
608
+ return true;
609
+ }
610
+
611
+ let hitCount = 0;
612
+
613
+ this.adapter.log.debug(`Trigger [${this.triggerName}], ${name} - check if conditions met: '${JSON.stringify(conditionNames)}'`);
614
+ const notMetConditionNames = [];
615
+ for (const lpConditionName of conditionNames) {
616
+
617
+ if (hitCount > 0 && allMustMeet == false) break;
618
+
619
+ const lpConditionStatePath = this.adapter.getOptionTableValue('tableConditions', 'name', lpConditionName, 'conditionState');
620
+ const lpConditionStateValue = this.adapter.getOptionTableValue('tableConditions', 'name', lpConditionName, 'conditionValue');
621
+
622
+ if (!lpConditionStatePath) {
623
+ this.adapter.log.error(`asyncAreScheduleConditionsMet(): condition details for '${lpConditionName}' could not be found.`);
624
+ notMetConditionNames.push(lpConditionName);
625
+ if (allMustMeet) { break; } else { continue; }
626
+ }
627
+
628
+ const lpStateVal = await this.adapter.x.helper.asyncGetForeignStateValue(lpConditionStatePath);
629
+ if (lpStateVal == null) {
630
+ notMetConditionNames.push(lpConditionName);
631
+ if (allMustMeet) { break; } else { continue; }
632
+ }
633
+
634
+ /**
635
+ * Finally, compare the config table state value with the actual state value
636
+ */
637
+ // First: do we have comparator
638
+ const res = this.adapter.x.helper.isNumComparatorMatching(lpStateVal, lpConditionStateValue);
639
+ if (res.isComparator && res.result) {
640
+ this.adapter.log.debug(`Trigger [${this.triggerName}], ${name} - condition '${lpConditionName}' *met* (options val = '${lpConditionStateValue}', actual state val = '${lpStateVal}')`);
641
+ hitCount++;
642
+ if (allMustMeet) { continue; } else { break; }
643
+
644
+ // Next: no comparator, so compare directly with ==
645
+ } else if (lpConditionStateValue == lpStateVal) {
646
+ this.adapter.log.debug(`Trigger [${this.triggerName}], ${name} - condition '${lpConditionName}' *met* (options val = '${lpConditionStateValue}', actual state val = '${lpStateVal}')`);
647
+ hitCount++;
648
+ if (allMustMeet) { continue; } else { break; }
649
+ } else {
650
+ // No hit, so go out!
651
+ this.adapter.log.debug(`Trigger [${this.triggerName}], ${name} - condition '${lpConditionName}' *not* met (options val = '${lpConditionStateValue}', actual state val = '${lpStateVal}')`);
652
+ notMetConditionNames.push(lpConditionName);
653
+ if (allMustMeet) { break; } else { continue; }
654
+ }
655
+
656
+ }
657
+
658
+ let result = false;
659
+ if ((allMustMeet && (hitCount == conditionNames.length)) || (!allMustMeet && (hitCount > 0)))
660
+ result = true;
661
+
662
+ if (inverse) result = !result;
663
+
664
+ if (result) {
665
+ this.adapter.log.debug(`Trigger [${this.triggerName}], ${name} - final result: condition matching`);
666
+ return true;
667
+ } else {
668
+ if (!inverse) this.adapter.log.debug(`Trigger [${this.triggerName}], ${name} - final result: *not* matching conditions: ${notMetConditionNames.toString()}`);
669
+ if (inverse) this.adapter.log.debug(`Trigger [${this.triggerName}], ${name} - final result: *not* matching conditions`); // to avoid empty 'notMetConditionNames'
670
+ return false;
671
+ }
672
+
673
+ } catch (error) {
674
+ this.adapter.x.helper.dumpError('[asyncAreScheduleConditionsMet()]', error);
675
+ return false;
676
+ }
677
+
678
+ }
679
+
680
+ /**
681
+ * Set/update zoneNames and zoneTargetNames.
682
+ * Call once a trigger that was triggered
683
+ * @return {Promise<boolean>} true if successful, false if errors
684
+ */
685
+ async _asyncUpdateCurrentActiveZones() {
686
+
687
+ try {
688
+
689
+ /**
690
+ * Get zone names, and zone-specific target names and execution
691
+ * Loop next iteration, if not successful.
692
+ */
693
+
694
+ this.zoneNames = Array(); // Zone names that were triggered and which match with a schedule row name
695
+ this.zoneTargetNames = {}; // Target devices per zone, like {Hallway:['Hallway Light'], Bath:['Bath Light', 'Bath Radio']}
696
+
697
+ for (const lpRowZones of this.adapter.config.tableZones) {
698
+
699
+ // Loop next if item in table "Zones" is not containing any trigger name in column triggers
700
+ if (!(lpRowZones.active && lpRowZones.triggers && Array.isArray(lpRowZones.triggers) && lpRowZones.triggers.includes(this.triggerName))) continue;
701
+
702
+ // Add target devices
703
+ this.zoneTargetNames[lpRowZones.name] = lpRowZones.targets;
704
+
705
+ // Execution options
706
+ //const executeAlways = this.adapter.config.execution[lpRowZones.name].executeAlways;
707
+ const executeAlways = (lpRowZones.executeAlways) ? true : false;
708
+ let tablesZoneExecution = [];
709
+ if (executeAlways) {
710
+ // we create a dummy to always execute
711
+ tablesZoneExecution = [{
712
+ active: true,
713
+ executeAlways: true // This is a "dummy" key, so that we know to always execute
714
+ }];
715
+ } else {
716
+ tablesZoneExecution = (lpRowZones.executionJson) ? JSON.parse(lpRowZones.executionJson) : [];
717
+ }
718
+
719
+ for (const lpRow of tablesZoneExecution) {
720
+
721
+ if (lpRow.active) {
722
+
723
+ this.adapter.log.debug(`Trigger [${this.triggerName}] === check schedule conditions ===`);
724
+
725
+ if (lpRow.executeAlways) {
726
+ this.adapter.log.debug(`Trigger [${this.triggerName}] Zone '${lpRowZones.name}' - 'Execute always is activated, so continue'`);
727
+ this.zoneNames.push(lpRowZones.name);
728
+ } else {
729
+
730
+ // A few variables / constants
731
+ const tsCurrent = Date.now(); // the current timestamp
732
+ let doContinue = true; // flag if we can continue.
733
+
734
+ // First – check if current time is within the schedule times
735
+ if (doContinue) doContinue = this.adapter.x.helper.scheduleIsTimeStampWithinPeriod(tsCurrent, lpRow.start, lpRow.end, lpRowZones.name);
736
+
737
+ // Next, check if current day is within the mon-sun options as set in schedules tables.
738
+ if (doContinue) doContinue = this.adapter.x.helper.scheduleIsWeekdayMatching(lpRow, tsCurrent, lpRowZones.name);
739
+
740
+ // Next, check additional conditions (like Public Holiday, etc. -- as set in conditions table)
741
+ if (doContinue) doContinue = await this.asyncAreScheduleConditionsMet('Zone Execution: Additional Conditions', lpRow.additionalConditions, lpRow.additionalConditionsAll);
742
+
743
+ // Next, check conditions "Never if"
744
+ if (doContinue) doContinue = await this.asyncAreScheduleConditionsMet('Zone Execution: "never if" Conditions', lpRow.never, lpRow.neverAll, true);
745
+
746
+ // All checks done.
747
+ if (doContinue) {
748
+ this.adapter.log.debug(`Trigger [${this.triggerName}] Zone '${lpRowZones.name}' - execution table row *is* meeting conditions`);
749
+ /* isHit == true; */
750
+ this.zoneNames.push(lpRowZones.name); // set matching zone name
751
+ } else {
752
+ this.adapter.log.debug(`Trigger [${this.triggerName}] Zone '${lpRowZones.name}' - execution table row is *not* meeting conditions`);
753
+ }
754
+ }
755
+
756
+ }
757
+
758
+ }
759
+
760
+ }
761
+
762
+ if (this.adapter.x.helper.isLikeEmpty(this.zoneNames) || this.adapter.x.helper.isLikeEmpty(this.zoneTargetNames)) {
763
+ this.adapter.log.debug(`Trigger [${this.triggerName}] Zone(s) will not be activated since no zone found which meets all conditions.`);
764
+ return false;
765
+ } else {
766
+ this.adapter.log.debug(`Trigger [${this.triggerName}] - (${this.zoneNames.length}) rows in Zones table found and assigned execution table rows fetched successfully.`);
767
+ return true;
768
+ }
769
+
770
+
771
+ } catch (error) {
772
+ this.adapter.x.helper.dumpError('[_asyncUpdateCurrentActiveZones]', error);
773
+ return false;
774
+ }
775
+
776
+
777
+ }
778
+
779
+
780
+ /**
781
+ * @param {string} zoneName - Name of zone
782
+ * @param {string} timerTitle - For logging only.
783
+ * @param {object} targets - {statePaths:['x', 'y'], stateValues: ['m', 'n'], deviceNames: ['a','b']};
784
+ * @param {number} secTimer - Number of seconds of the timer, that was set and now expired. For logging only.
785
+ */
786
+ async _asyncSetZoneTimer_doOnTimeout(zoneName, timerTitle, targets, secTimer) {
787
+
788
+ try {
789
+
790
+ // First check if tableZones 'Never switch off if...' is met
791
+ const neverOffConditionNames = this.adapter.getOptionTableValue('tableZones', 'name', zoneName, 'neverOff');
792
+ const allMustMeet = this.adapter.getOptionTableValue('tableZones', 'name', zoneName, 'neverOffAll');
793
+ const switchOff = await this.asyncAreScheduleConditionsMet('Zones table - "never switch off if" condition', neverOffConditionNames, allMustMeet, true);
794
+ if (!switchOff) {
795
+ this.adapter.x.helper.logExtendedInfo(`Trigger [${this.triggerName}] Zone '${zoneName}': Timer '${timerTitle}' ended, but 'Never switch off if...' condition(s) true --> Zone will not be switched off.`);
796
+ return; // go out
797
+ }
798
+
799
+ // Next, cancel all timers to ensure that another timer is not running.
800
+ const timerObjIds = ['timersZoneOff', 'timersMimicMotionTrigger'];
801
+ for (const lpTimerObjId of timerObjIds) {
802
+ const lpTimeLeft = this.adapter.x.helper.getTimeoutTimeLeft(this.adapter.x[lpTimerObjId][zoneName]);
803
+ if (this.triggerIsMotion && (lpTimeLeft > -1)) {
804
+ clearTimeout(this.adapter.x[lpTimerObjId][zoneName]);
805
+ this.adapter.x[lpTimerObjId][zoneName] = null;
806
+ this.adapter.log.debug(`Trigger [${this.triggerName}] Zone '${zoneName}': Clearing timer '${lpTimerObjId}', which was still running for ${(lpTimeLeft / 1000).toFixed(0)} seconds.`);
807
+ }
808
+ }
809
+
810
+
811
+ /* ================== START -- RESOLVING ISSUE #45 (https://github.com/Mic-M/ioBroker.smartcontrol/issues/45) */
812
+
813
+ /**
814
+ * Verify if there are other motion sensors in the same zone.
815
+ * If yes and if a motion detection of one of these is still true: do not switch off zone.
816
+ */
817
+ // Get all motion sensor trigger names
818
+ const allMotionNames = [];
819
+ for (const lpMotionRow of this.adapter.config.tableTriggerMotion) {
820
+ if (lpMotionRow.active) {
821
+ allMotionNames.push(lpMotionRow.name);
822
+ }
823
+ }
824
+ // Get all other motion triggers assigned to zone
825
+ const confZoneOtherTriggersMotion = [];
826
+ const confZoneTriggersAll = this.adapter.getOptionTableValue('tableZones', 'name', zoneName, 'triggers');
827
+ for (const lpTriggerName of confZoneTriggersAll) {
828
+ if (allMotionNames.includes(lpTriggerName)) {
829
+ if (lpTriggerName !== this.triggerName) {
830
+ // we have an additional motion sensor trigger
831
+ confZoneOtherTriggersMotion.push(lpTriggerName);
832
+ }
833
+ }
834
+ }
835
+
836
+ // Now check if motion state of any other motion timer is still true
837
+ if (confZoneOtherTriggersMotion.length > 0) {
838
+ for (const lpName of confZoneOtherTriggersMotion) {
839
+ const lpMotionObjId = this.adapter.getOptionTableValue('tableTriggerMotion', 'name', lpName, 'stateId');
840
+ const lpMotionObj = await this.adapter.x.helper.asyncGetForeignStateValue(lpMotionObjId);
841
+ if (lpMotionObj == true) {
842
+ // We have another motion sensor in same zone with motion=true, so go out.
843
+ this.adapter.x.helper.logExtendedInfo(`Trigger [${this.triggerName}] Zone '${zoneName}': Timer '${timerTitle}' ended, but another motion sensor '${lpName}' state value assigned to this zone is still true, so we will not switch off zone.' `);
844
+ return; // go out
845
+ }
846
+ }
847
+ }
848
+
849
+ /* ================== END -- RESOLVING ISSUE #45 (https://github.com/Mic-M/ioBroker.smartcontrol/issues/45) */
850
+
851
+
852
+ // Set "is Zone on" status to false
853
+ this.adapter.x.zonesIsOn[zoneName] = false;
854
+
855
+ // Clear timer 'timersZoneOn'
856
+ clearTimeout(this.adapter.x.timersZoneOn[zoneName]);
857
+ this.adapter.x.timersZoneOn[zoneName] = null;
858
+
859
+ const lTargetDevicesSwitchedOff = []; // For Log
860
+ const lManualOnDevices = []; // For log
861
+ for (let i = 0; i < targets.statePaths.length; i++) {
862
+
863
+ // All are having same length and association per each element
864
+ const lpStatePath = targets.statePaths[i];
865
+ const lpStateValToSet = targets.stateValues[i];
866
+ const lpTargetName = targets.deviceNames[i];
867
+
868
+ // Remove from this.adapter.x.motionTriggeredDevices
869
+ if (this.motionNotIfManual) this.adapter.x.motionTriggeredDevices = this.adapter.x.helper.arrayRemoveElementByValue(this.adapter.x.motionTriggeredDevices, lpTargetName);
870
+
871
+ // Check if current value != new value
872
+ const targetOffStateValCurrent = await this.adapter.x.helper.asyncGetForeignStateValue(lpStatePath);
873
+ if (targetOffStateValCurrent == null) {
874
+ this.adapter.log.error(`Timer '${timerTitle}', trigger '${this.triggerName}', target ${lpTargetName}: - Timeout of '${secTimer}' seconds reached, but could not get current state value of '${lpStatePath}', so unable to turn device off.`);
875
+ continue;
876
+ }
877
+ if (lpStateValToSet == targetOffStateValCurrent) {
878
+ this.adapter.x.helper.logExtendedInfo(`Trigger [${this.triggerName}] Timer '${timerTitle}', target ${lpTargetName}: - Timeout of '${secTimer}' seconds reached, target is already turned off, so not turning off again.`);
879
+ continue;
880
+ }
881
+
882
+ // All passed.
883
+ await this.adapter.setForeignStateAsync(lpStatePath, { val: lpStateValToSet, ack: false });
884
+ lTargetDevicesSwitchedOff.push(lpTargetName);
885
+
886
+ }
887
+
888
+ // Log
889
+ if (lManualOnDevices.length > 0) {
890
+ this.adapter.x.helper.logExtendedInfo(`Trigger [${this.triggerName}] Timer '${timerTitle}', target(s) '${lManualOnDevices.toString()}': - Timeout of '${secTimer}' seconds reached, target(s) manually turned on while timer was running, so do not turn off.`);
891
+ }
892
+ if (lTargetDevicesSwitchedOff.length > 0) {
893
+ this.adapter.x.helper.logExtendedInfo(`Trigger [${this.triggerName}] Timer '${timerTitle}', target(s) '${lTargetDevicesSwitchedOff.toString()}': - Turned off per ${secTimer}s timer.`);
894
+ }
895
+
896
+
897
+ } catch (error) {
898
+ this.adapter.x.helper.dumpError('[asyncSetZoneTimer_doOnTimeout]', error);
899
+ return;
900
+ }
901
+
902
+ }
903
+
904
+ /**
905
+ * Get target device info for a given zone name.
906
+ * @param {string} zoneName - Zone Name
907
+ * @return {Promise<object|null>} - Object: {statePaths:[Array of state paths], stateValues: [Array of state values], deviceNames: [Array of device names]}. null if not found/errors.
908
+ */
909
+ async _asyncGetTargetDevicesInfoOfZone(zoneName) {
910
+
911
+ try {
912
+
913
+ if (!this.zoneTargetNames || !this.zoneTargetNames[zoneName] || this.adapter.x.helper.isLikeEmpty(this.zoneTargetNames[zoneName])) {
914
+ this.adapter.log.debug(`Trigger [${this.triggerName}] Zone '${zoneName}': No current target devices found for timer to switch devices off, likely because all were turned on manually before`);
915
+ return null;
916
+ }
917
+ const targetDevices = this.zoneTargetNames[zoneName];
918
+ //const targetDevices = this.adapter.getOptionTableValue('tableZones', 'name', zoneName, 'targets');
919
+
920
+ // Get all target device state paths and values
921
+ const targets = {
922
+ statePaths: Array(), // Would use [] instead of Array(), but see: https://stackoverflow.com/a/56394664
923
+ stateValues: Array(),
924
+ deviceNames: Array(),
925
+ };
926
+
927
+ for (const lpTargetName of targetDevices) {
928
+ // Get target device information
929
+ const targetOffState = this.adapter.getOptionTableValue('tableTargetDevices', 'name', lpTargetName, 'offState');
930
+ const targetOffVal = this.adapter.getOptionTableValue('tableTargetDevices', 'name', lpTargetName, 'offValue');
931
+
932
+ if (targetOffState == undefined || targetOffVal == undefined) {
933
+ throw (`Unable to retrieve target off state/value for target device '${lpTargetName}' from adapter config.`);
934
+ }
935
+
936
+ // Target Off State
937
+ if (await this.adapter.getForeignObjectAsync(targetOffState)) {
938
+ // State is existing
939
+ targets.statePaths.push(targetOffState);
940
+ targets.stateValues.push(targetOffVal);
941
+ targets.deviceNames.push(lpTargetName);
942
+ } else {
943
+ // State is not existing
944
+ this.adapter.log.error(`State '${targetOffState}' of device '${lpTargetName}' does not exist.`);
945
+ }
946
+ }
947
+
948
+ // Go out if we actually have no devices to turn off
949
+ if (this.adapter.x.helper.isLikeEmpty(targets.statePaths)) {
950
+ throw (`Zone '${zoneName}': --> No target states found in adapter settings, so no timer will be set to turn off.`);
951
+ }
952
+
953
+ return targets;
954
+
955
+ } catch (error) {
956
+ this.adapter.x.helper.dumpError(`[asyncGetTargetDevicesInfoOfZone]`, error);
957
+ return null;
958
+ }
959
+
960
+ }
961
+
962
+
963
+
964
+ }
965
965
  module.exports = Trigger;