iobroker.smartcontrol 2.0.1 → 2.1.0

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.
package/main.js CHANGED
@@ -6,7 +6,7 @@
6
6
  * @forum https://forum.iobroker.net/topic/36728/
7
7
  * @author Mic-M <https://github.com/Mic-M/ioBroker.smartcontrol>
8
8
  * @license MIT
9
- *
9
+ *
10
10
  * Developer Notes:
11
11
  * - A few ASCII blocks are being used for ease of code section identification. I've used
12
12
  * http://patorjk.com/software/taag/#p=display&v=3&f=ANSI%20Regular&t=smart%20control%20adapter
@@ -14,54 +14,54 @@
14
14
 
15
15
  // ioBroker Adapter core module
16
16
  const utils = require('@iobroker/adapter-core');
17
+ const { MIDNIGHT_RESCHEDULE_DELAY_MS } = require('./lib/midnight-reschedule');
17
18
 
18
19
  /**
19
20
  * Main Adapter Class
20
- * @class SmartControl
21
+ *
21
22
  */
22
23
  class SmartControl extends utils.Adapter {
23
-
24
24
  /**
25
25
  * Constructor
26
- * @param {Partial<utils.AdapterOptions>} [options={}] Adapter Options
26
+ *
27
+ * @param {Partial<utils.AdapterOptions>} [options] Adapter Options
27
28
  */
28
29
  constructor(options) {
29
-
30
- super( {...options, name: 'smartcontrol'} ); // to access the object's parent
31
-
32
- this.on('ready', this._asyncOnReady.bind(this));
33
- this.on('stateChange', this._asyncOnStateChange.bind(this));
34
- this.on('message', this._asyncOnMessage.bind(this));
35
- this.on('unload', this._onUnload.bind(this));
30
+ super({ ...options, name: 'smartcontrol' }); // to access the object's parent
36
31
 
32
+ this.on('ready', this._asyncOnReady.bind(this));
33
+ this.on('stateChange', this._asyncOnStateChange.bind(this));
34
+ this.on('message', this._asyncOnMessage.bind(this));
35
+ this.on('unload', this._onUnload.bind(this));
37
36
 
38
37
  // adapter-specific objects being set here for global availability in adapter.x
39
38
  // We are using 'x' to avoid potential namespace conflicts
40
39
  this.x = {
41
-
42
40
  /**
43
41
  * Load Modules
44
42
  * VS Code: For all NPM modules, open console, change dir to "C:\iobroker\node_modules\ioBroker.<AdapterName>",
45
43
  * and execute "npm install <module name>", ex: npm install suncalc2
46
44
  */
47
- constants: require('./lib/constants.js'), // Adapter constants
48
- helper: require('./lib/helper.js')(this), // Generic JavaScript and ioBroker Adapter methods - https://forum.iobroker.net/post/484620
49
- Trigger: require('./lib/trigger-class.js'), // Class for Triggers and Target devices handling
50
- mSuncalc: require('suncalc2'), // https://github.com/andiling/suncalc2
51
- mSchedule: require('node-schedule'), // https://github.com/node-schedule/node-schedule
52
- axios: require('axios').default,
45
+ constants: require('./lib/constants.js'), // Adapter constants
46
+ helper: require('./lib/helper.js')(this), // Generic JavaScript and ioBroker Adapter methods - https://forum.iobroker.net/post/484620
47
+ Trigger: require('./lib/trigger-class.js'), // Class for Triggers and Target devices handling
48
+ mSuncalc: require('suncalc2'), // https://github.com/andiling/suncalc2
49
+ mSchedule: require('node-schedule'), // https://github.com/node-schedule/node-schedule
50
+ axios: require('axios').default,
53
51
  // {object} timers - All timer objects.
54
- timersZoneOn: {}, // for option "onAfter" in Zones table
55
- timersZoneOff: {}, // for option "offAfter" in Zones table
52
+ timersZoneOn: {}, // for option "onAfter" in Zones table
53
+ timersZoneOff: {}, // for option "offAfter" in Zones table
56
54
  timersMimicMotionTrigger: {}, // for "motion linked trigger", to turn off after x sec if no motion
57
55
  timersZoneDeviceOnDelay: {}, // for Zones devices, target overwrite delay
56
+ timersMotionOff: {}, // motion off-timer once per zone (not per PIR), see #147
58
57
 
59
58
  // {object} schedules - All schedules (node-schedule)
60
59
  // NOTE: different level as in 'timers', key value holds the schedule object.
61
60
  schedules: {
62
61
  midnight: null,
63
62
  // more schedule keys added later, as key: name of row of tableTriggerTimes
64
- },
63
+ },
64
+ midnightRescheduleTimer: null, // Delay nach 00:00, damit Nutzer-Cron `0 0 * * *` zuerst feuert (#8)
65
65
 
66
66
  // Motion trigger should not set timeout if target device was turned on previously without a motion trigger.
67
67
  // Ref. https://forum.iobroker.net/post/433871 | https://forum.iobroker.net/post/437803
@@ -69,7 +69,7 @@ class SmartControl extends utils.Adapter {
69
69
 
70
70
  // ioBroker system configuration object (the common object of it), set in _asyncOnReady()
71
71
  // Has key names like: city, country, longitude, latitude, language, tempUnit, currency, dateFormat, isFloatComma, licenseConfirmed, defaultHistory, activeRepo, diag
72
- systemConfig: {},
72
+ systemConfig: {},
73
73
 
74
74
  // Keep triggerName and timestamp for checking for limitTriggerInterval to not switch more than x secs
75
75
  onStateChangeTriggers: {},
@@ -83,38 +83,40 @@ class SmartControl extends utils.Adapter {
83
83
 
84
84
  // Logs of smartcontrol.x.info.log.xxxxxx.json
85
85
  jsonLogs: {},
86
-
87
86
  };
88
-
89
87
  }
90
88
 
91
89
  /**
92
90
  * Called once ioBroker databases are connected and adapter received configuration.
93
91
  */
94
92
  async _asyncOnReady() {
95
-
96
93
  try {
97
-
98
94
  // Get system configuration
99
95
  const sysConf = await this.getForeignObjectAsync('system.config');
100
96
  if (sysConf && sysConf.common) {
101
97
  this.x.systemConfig = sysConf.common;
102
98
  } else {
103
- throw(`ioBroker system configuration not found.`);
99
+ throw `ioBroker system configuration not found.`;
104
100
  }
105
-
101
+
106
102
  // Get room and function enumerations (for tableTargetEnums) and set to tableTargetDevices. Also update tableZones.
107
103
  const convertEnums = await this._asyncConvertEnumTargetsToTargetDevices();
108
104
  if (!convertEnums) {
109
- this.log.error(`[User Error (Anwenderfehler)] - Tab 'TARGETS', table 'Enum functions': active row(s) found, but no corresponding states found for the enum function(s) selected.`);
110
- this.log.error(`Please check the previous warn log for details and then correct your configuration accordingly. You must fix these issue(s) to use this adapter.`);
105
+ this.log.error(
106
+ `[User Error (Anwenderfehler)] - Tab 'TARGETS', table 'Enum functions': active row(s) found, but no corresponding states found for the enum function(s) selected.`,
107
+ );
108
+ this.log.error(
109
+ `Please check the previous warn log for details and then correct your configuration accordingly. You must fix these issue(s) to use this adapter.`,
110
+ );
111
111
  this.setState('info.connection', false, true); // change to yellow
112
- return; // Go out.
113
- }
112
+ return; // Go out.
113
+ }
114
114
 
115
115
  // Warning if latitude / longitude not defined
116
116
  if (!this.x.systemConfig.latitude || !this.x.systemConfig.longitude) {
117
- this.log.warn('Latitude/Longitude is not defined in your ioBroker main configuration, so you will not be able to use Astro functionality for schedules!');
117
+ this.log.warn(
118
+ 'Latitude/Longitude is not defined in your ioBroker main configuration, so you will not be able to use Astro functionality for schedules!',
119
+ );
118
120
  }
119
121
 
120
122
  /**
@@ -122,31 +124,44 @@ class SmartControl extends utils.Adapter {
122
124
  */
123
125
  await this.x.helper.asyncCreateStates(this.x.constants.testStates);
124
126
 
125
-
126
127
  /**
127
128
  * Create smartcontrol.x.info.astroTimes states.
128
129
  */
129
130
  if (this.x.systemConfig.latitude && this.x.systemConfig.longitude) {
130
-
131
131
  const statesToBeCreated = [];
132
132
  for (let i = 0; i < this.x.constants.astroTimes.length; i++) {
133
133
  const lpAstro = this.x.constants.astroTimes[i];
134
- const statePathMain = `${this.namespace}.info.astroTimes.${this.x.helper.zeroPad(i+1, 2)}_${lpAstro}`;
135
- const commonMain = { name: `${lpAstro} – ${this.x.constants.astroTimesGerman[i]}`, type: 'string', read: true, write: false, role: 'value', def: '' };
136
- statesToBeCreated.push({statePath:statePathMain, commonObject:commonMain});
137
-
134
+ const statePathMain = `${this.namespace}.info.astroTimes.${this.x.helper.zeroPad(i + 1, 2)}_${lpAstro}`;
135
+ const commonMain = {
136
+ name: `${lpAstro} – ${this.x.constants.astroTimesGerman[i]}`,
137
+ type: 'string',
138
+ read: true,
139
+ write: false,
140
+ role: 'value',
141
+ def: '',
142
+ };
143
+ statesToBeCreated.push({ statePath: statePathMain, commonObject: commonMain });
144
+
138
145
  // Also, create timestamps
139
146
  const statePathTs = `${this.namespace}.info.astroTimes.timeStamps.${lpAstro}`;
140
- const commonTs = { name: `${lpAstro} – ${this.x.constants.astroTimesGerman[i]}`, type: 'number', read: true, write: false, role: 'value', def: 0 };
141
- statesToBeCreated.push({statePath:statePathTs, commonObject:commonTs});
147
+ const commonTs = {
148
+ name: `${lpAstro} – ${this.x.constants.astroTimesGerman[i]}`,
149
+ type: 'number',
150
+ read: true,
151
+ write: false,
152
+ role: 'value',
153
+ def: 0,
154
+ };
155
+ statesToBeCreated.push({ statePath: statePathTs, commonObject: commonTs });
142
156
  }
143
157
  // Now create the states
144
158
  const createStatesResult = await this.x.helper.asyncCreateStates(statesToBeCreated);
145
- if (!createStatesResult) throw (`Certain error(s) occurred in asyncCreateStates().`);
146
-
159
+ if (!createStatesResult) {
160
+ throw `Certain error(s) occurred in asyncCreateStates().`;
161
+ }
162
+
147
163
  // Set current astro values
148
164
  await this._asyncOnReady_asyncRefreshAstroStates();
149
-
150
165
  }
151
166
 
152
167
  /**
@@ -155,25 +170,23 @@ class SmartControl extends utils.Adapter {
155
170
  * - smartcontrol.x.info.log.switchedTargetDevices.json
156
171
  */
157
172
  const toCreate = [
158
- {id:'zoneActivations', name:'JSON of recent zone activations'},
159
- {id:'switchedTargetDevices', name: 'JSON of recent switched target devices'}
173
+ { id: 'zoneActivations', name: 'JSON of recent zone activations' },
174
+ { id: 'switchedTargetDevices', name: 'JSON of recent switched target devices' },
160
175
  ];
161
176
 
162
177
  for (const lpObj of toCreate) {
163
-
164
- await this.x.helper.asyncCreateStates({
165
- statePath: `${this.namespace}.info.log.${lpObj.id}.json`,
166
- commonObject: {name:lpObj.name, type:'string', read:true, write:false, role:'json', def:'' }
178
+ await this.x.helper.asyncCreateStates({
179
+ statePath: `${this.namespace}.info.log.${lpObj.id}.json`,
180
+ commonObject: { name: lpObj.name, type: 'string', read: true, write: false, role: 'json', def: '' },
167
181
  });
168
- // Note: above will not overwrite existing states and values.
182
+ // Note: above will not overwrite existing states and values.
169
183
  // Now get state value and set into global variable
170
184
  const lpState = await this.getStateAsync(`info.log.${lpObj.id}.json`);
171
185
  if (lpState && lpState.val && typeof lpState.val == 'string') {
172
186
  this.x.jsonLogs[lpObj.id] = JSON.parse(lpState.val);
173
187
  } else {
174
188
  this.log.debug(`State value of 'info.log.${lpObj.id}.json' is empty.`);
175
- }
176
-
189
+ }
177
190
  }
178
191
 
179
192
  /**
@@ -183,47 +196,72 @@ class SmartControl extends utils.Adapter {
183
196
  for (const lpRow of this.config.tableTriggerDevices) {
184
197
  const statePath = `userstates.${lpRow.stateId}`;
185
198
  const statePathFull = `${this.namespace}.${statePath}`;
186
- if(lpRow.userState) { // We also create states for inactive rows, since user likely deactivates temporarily.
199
+ if (lpRow.userState) {
200
+ // We also create states for inactive rows, since user likely deactivates temporarily.
187
201
  if (this.x.helper.isStateIdValid(`${this.namespace}.${statePath}`)) {
188
-
189
- const stateCommonString = {name:`User trigger '${lpRow.name}' of 'Other Devices' in Zones table`, type:'string', read:true, write:true, role:'state', def:'' };
190
- const stateCommonBoolean = {name:`User trigger '${lpRow.name}' of 'Other Devices' in Zones table`, type:'boolean', read:true, write:true, role:'state', def:false };
202
+ const stateCommonString = {
203
+ name: `User trigger '${lpRow.name}' of 'Other Devices' in Zones table`,
204
+ type: 'string',
205
+ read: true,
206
+ write: true,
207
+ role: 'state',
208
+ def: '',
209
+ };
210
+ const stateCommonBoolean = {
211
+ name: `User trigger '${lpRow.name}' of 'Other Devices' in Zones table`,
212
+ type: 'boolean',
213
+ read: true,
214
+ write: true,
215
+ role: 'state',
216
+ def: false,
217
+ };
191
218
 
192
219
  const lpStateObject = await this.getObjectAsync(statePath);
193
220
  if (!lpStateObject) {
194
221
  // State does not exist
195
222
  let stateObj = {};
196
- if(lpRow.stateVal=='true' || lpRow.stateVal=='false') {
197
- stateObj = {statePath:statePath, commonObject:stateCommonBoolean};
223
+ if (lpRow.stateVal == 'true' || lpRow.stateVal == 'false') {
224
+ stateObj = { statePath: statePath, commonObject: stateCommonBoolean };
198
225
  } else {
199
- stateObj = {statePath:statePath, commonObject:stateCommonString};
226
+ stateObj = { statePath: statePath, commonObject: stateCommonString };
200
227
  }
201
228
  await this.x.helper.asyncCreateStates(stateObj, false); // Create state
202
229
  this.log.debug(`User state '${statePathFull}' created per option table 'Other Devices'.`);
203
230
  } else {
204
231
  // State exists. Now let's check if the "type" changed from boolean to string or vice versa.
205
- const isStateConfValBoolean = (lpRow.stateVal=='true' || lpRow.stateVal=='false') ? true : false;
206
- const isStateRealValBoolean = (lpStateObject.common.type == 'boolean' || lpStateObject.common.type == 'switch') ? true : false;
232
+ const isStateConfValBoolean =
233
+ lpRow.stateVal == 'true' || lpRow.stateVal == 'false' ? true : false;
234
+ const isStateRealValBoolean =
235
+ lpStateObject.common.type == 'boolean' || lpStateObject.common.type == 'switch'
236
+ ? true
237
+ : false;
207
238
  if (isStateConfValBoolean != isStateRealValBoolean) {
208
- const newCommon = (isStateConfValBoolean) ? stateCommonBoolean : stateCommonString;
209
- this.log.debug(`User state '${statePathFull}' - state type changed, so delete old state and create new one.`);
210
- await this.delObjectAsync(statePath); // Delete state.
211
- await this.x.helper.asyncCreateStates({statePath:statePath, commonObject:newCommon}, false);
239
+ const newCommon = isStateConfValBoolean ? stateCommonBoolean : stateCommonString;
240
+ this.log.debug(
241
+ `User state '${statePathFull}' - state type changed, so delete old state and create new one.`,
242
+ );
243
+ await this.delObjectAsync(statePath); // Delete state.
244
+ await this.x.helper.asyncCreateStates(
245
+ { statePath: statePath, commonObject: newCommon },
246
+ false,
247
+ );
212
248
  }
213
249
  }
214
250
  statePathsUsed.push(statePathFull);
215
251
  } else {
216
- throw(`State path '${this.namespace}.${statePath}' is not valid.`);
252
+ throw `State path '${this.namespace}.${statePath}' is not valid.`;
217
253
  }
218
254
  }
219
255
  }
220
256
  // Delete states no longer needed
221
257
  const allUserStates = await this.getStatesOfAsync('userstates');
222
- if (allUserStates == undefined) throw (`Could not get adapter instance state paths for 'userstates'.`);
223
-
258
+ if (allUserStates == undefined) {
259
+ throw `Could not get adapter instance state paths for 'userstates'.`;
260
+ }
261
+
224
262
  for (const lpState of allUserStates) {
225
263
  const existingStatePath = lpState._id; // like: 'smartcontrol.0.userstates.Coffeemaker'
226
- if ( statePathsUsed.indexOf(existingStatePath) == -1 ) {
264
+ if (statePathsUsed.indexOf(existingStatePath) == -1) {
227
265
  // State is no longer used.
228
266
  await this.delObjectAsync(existingStatePath); // Delete object and its state
229
267
  this.log.debug(`State '${existingStatePath}' deleted, since trigger does no longer exist.'`);
@@ -239,7 +277,9 @@ class SmartControl extends utils.Adapter {
239
277
  this.log.info('Adapter admin configuration successfully validated...');
240
278
  } else {
241
279
  // Error(s) occurred.
242
- this.log.error(`[User Error (Anwenderfehler)] - ${configVerificationResult.issues.length} error(s) found in adapter configuration. You must fix these issue(s) to use this adapter.`);
280
+ this.log.error(
281
+ `[User Error (Anwenderfehler)] - ${configVerificationResult.issues.length} error(s) found in adapter configuration. You must fix these issue(s) to use this adapter.`,
282
+ );
243
283
  let counter = 0;
244
284
  for (const lpMsg of configVerificationResult.issues) {
245
285
  counter++;
@@ -261,65 +301,109 @@ class SmartControl extends utils.Adapter {
261
301
  const statePaths = [];
262
302
  // A - smartcontrol.x.targetDevices.xxx states.
263
303
  for (const lpRow of this.config.tableTargetDevices) {
264
- if (!lpRow.active) continue;
265
- if ('isTargetURL' in lpRow) continue; // do not create states for TargetURLs, since we create separately anyway.
266
- if(/_enum-\d{1,3}$/.test(lpRow.name)) continue; // don't add enums
304
+ if (!lpRow.active) {
305
+ continue;
306
+ }
307
+ if ('isTargetURL' in lpRow) {
308
+ continue;
309
+ } // do not create states for TargetURLs, since we create separately anyway.
310
+ if (/_enum-\d{1,3}$/.test(lpRow.name)) {
311
+ continue;
312
+ } // don't add enums
267
313
  const lpStatePath = `${this.namespace}.targetDevices.${lpRow.name.trim()}`;
268
- if (! this.x.helper.isStateIdValid(lpStatePath) ) throw(`Invalid state name portion provided in table 'Target Devices': '${lpRow.name}'`);
269
- const lpCommon = { name: lpRow.name, type: 'boolean', read: true, write: true, role: 'switch', def: false };
270
- statesToBeCreated.push({statePath:lpStatePath, commonObject:lpCommon});
314
+ if (!this.x.helper.isStateIdValid(lpStatePath)) {
315
+ throw `Invalid state name portion provided in table 'Target Devices': '${lpRow.name}'`;
316
+ }
317
+ const lpCommon = {
318
+ name: lpRow.name,
319
+ type: 'boolean',
320
+ read: true,
321
+ write: true,
322
+ role: 'switch',
323
+ def: false,
324
+ };
325
+ statesToBeCreated.push({ statePath: lpStatePath, commonObject: lpCommon });
271
326
  statePaths.push(lpStatePath);
272
327
  }
273
328
  // B - smartcontrol.x.targetURLs.xxx states.
274
329
  for (const lpRow of this.config.tableTargetURLs) {
275
- if (!lpRow.active) continue;
330
+ if (!lpRow.active) {
331
+ continue;
332
+ }
276
333
 
277
334
  const lpBaseStatePath = lpRow.stateId; // ${this.namespace} was already added in asyncVerifyConfig()
278
335
 
279
336
  const statesToProcess = {
280
337
  // state | common object to set
281
- 'call_on': { name: `Call '${lpRow.urlOn}'`, type: 'boolean', read: true, write: true, role: 'button', def: false },
282
- 'response': { name: `Response from '${lpRow.urlOn}'`, type: 'string', read: true, write: false, role: 'state', def: '' },
338
+ call_on: {
339
+ name: `Call '${lpRow.urlOn}'`,
340
+ type: 'boolean',
341
+ read: true,
342
+ write: true,
343
+ role: 'button',
344
+ def: false,
345
+ },
346
+ response: {
347
+ name: `Response from '${lpRow.urlOn}'`,
348
+ type: 'string',
349
+ read: true,
350
+ write: false,
351
+ role: 'state',
352
+ def: '',
353
+ },
283
354
  };
284
355
 
285
356
  if (lpRow.urlOff && !this.x.helper.isLikeEmpty(lpRow.urlOff)) {
286
- statesToProcess.call_off = { name: `Call '${lpRow.urlOff}'`, type: 'boolean', read: true, write: true, role: 'button', def: false };
357
+ statesToProcess.call_off = {
358
+ name: `Call '${lpRow.urlOff}'`,
359
+ type: 'boolean',
360
+ read: true,
361
+ write: true,
362
+ role: 'button',
363
+ def: false,
364
+ };
287
365
  //statesToProcess.response_off = { name: `Response from '${lpRow.urlOff}'`, type: 'string', read: true, write: false, role: 'state', def: '' };
288
366
  }
289
367
 
290
368
  for (const lpKeyName in statesToProcess) {
291
- const obj = await this.getObjectAsync(lpBaseStatePath + '.' + lpKeyName);
369
+ const obj = await this.getObjectAsync(`${lpBaseStatePath}.${lpKeyName}`);
292
370
  if (obj) {
293
371
  // Object exists, so we just update the name in common.
294
372
  // https://discordapp.com/channels/743167951875604501/743171252377616476/762360203878072391
295
- await this.extendObjectAsync(lpBaseStatePath + '.' + lpKeyName, {common:{name:statesToProcess[lpKeyName].name}});
373
+ await this.extendObjectAsync(`${lpBaseStatePath}.${lpKeyName}`, {
374
+ common: { name: statesToProcess[lpKeyName].name },
375
+ });
296
376
  } else {
297
377
  statesToBeCreated.push({
298
- statePath:lpBaseStatePath + '.' + lpKeyName,
299
- commonObject:statesToProcess[lpKeyName]
378
+ statePath: `${lpBaseStatePath}.${lpKeyName}`,
379
+ commonObject: statesToProcess[lpKeyName],
300
380
  });
301
381
  }
302
- statePaths.push(lpBaseStatePath + '.' + lpKeyName,);
303
-
382
+ statePaths.push(`${lpBaseStatePath}.${lpKeyName}`);
304
383
  }
305
- statePaths.push(lpBaseStatePath + '.response');
306
-
384
+ statePaths.push(`${lpBaseStatePath}.response`);
307
385
  }
308
386
 
309
387
  // Create all states
310
388
  const createStatesResult = await this.x.helper.asyncCreateStates(statesToBeCreated);
311
- if (!createStatesResult) throw (`Certain error(s) occurred in asyncCreateStates().`);
389
+ if (!createStatesResult) {
390
+ throw `Certain error(s) occurred in asyncCreateStates().`;
391
+ }
312
392
 
313
393
  // Delete all states which are no longer used.
314
394
  const allTargetDevicesStates = await this.getStatesOfAsync('targetDevices');
315
- if (allTargetDevicesStates == undefined) throw (`getStatesOfAsync(): Could not get adapter instance state paths for 'targetDevices'.`);
395
+ if (allTargetDevicesStates == undefined) {
396
+ throw `getStatesOfAsync(): Could not get adapter instance state paths for 'targetDevices'.`;
397
+ }
316
398
  const allTargetURLsStates = await this.getStatesOfAsync('targetURLs');
317
- if (allTargetURLsStates == undefined) throw (`getStatesOfAsync(): Could not get adapter instance state paths for 'targetURLs'.`);
399
+ if (allTargetURLsStates == undefined) {
400
+ throw `getStatesOfAsync(): Could not get adapter instance state paths for 'targetURLs'.`;
401
+ }
318
402
  for (const lpState of allTargetDevicesStates.concat(allTargetURLsStates)) {
319
403
  const statePath = lpState._id; // like: 'smartcontrol.0.targetDevices.Coffeemaker'
320
- if ( statePaths.indexOf(statePath) == -1 ) {
404
+ if (statePaths.indexOf(statePath) == -1) {
321
405
  // State is no longer used.
322
- await this.delObjectAsync(statePath); // Delete state.
406
+ await this.delObjectAsync(statePath); // Delete state.
323
407
  this.log.debug(`State '${statePath}' deleted, since option does no longer exist.'`);
324
408
  }
325
409
  }
@@ -329,32 +413,43 @@ class SmartControl extends utils.Adapter {
329
413
  */
330
414
  const statesFull = []; // with common objects
331
415
  const statePathsOnly = [];
332
-
333
- const tablesToProcess = ['tableTriggerMotion', 'tableTriggerDevices', 'tableTriggerTimes', 'tableTargetDevices', 'tableZones', 'tableConditions'];
416
+
417
+ const tablesToProcess = [
418
+ 'tableTriggerMotion',
419
+ 'tableTriggerDevices',
420
+ 'tableTriggerTimes',
421
+ 'tableTargetDevices',
422
+ 'tableZones',
423
+ 'tableConditions',
424
+ ];
334
425
  let errorCounter = 0;
335
426
  for (let i = 0; i < tablesToProcess.length; i++) {
336
-
337
427
  for (let k = 0; k < this.config[tablesToProcess[i]].length; k++) {
338
-
339
428
  const lpRow = this.config[tablesToProcess[i]][k];
340
429
  const lpTableName = tablesToProcess[i]; // Table name from config, like 'tableTargetDevices';
341
430
  const lpStateSubSection = lpTableName.substr(5); // 'tableTargetDevices' => 'TargetDevices'
342
-
431
+
343
432
  // Get the name of the table row and convert to a valid state portion.
344
- const lpRowNameStatePortion = lpRow.name; // like: 'Motion Bathroom' or 'At 04:05 every Sunday'
345
- if (this.x.helper.isLikeEmpty(lpRow.name.trim())) continue; // We do not add rows with blank name
346
- if (lpTableName == 'tableTargetDevices' && /_enum-\d{1,3}$/.test(lpRow.name)) continue; // Don't add enums
433
+ const lpRowNameStatePortion = lpRow.name; // like: 'Motion Bathroom' or 'At 04:05 every Sunday'
434
+ if (this.x.helper.isLikeEmpty(lpRow.name.trim())) {
435
+ continue;
436
+ } // We do not add rows with blank name
437
+ if (lpTableName == 'tableTargetDevices' && /_enum-\d{1,3}$/.test(lpRow.name)) {
438
+ continue;
439
+ } // Don't add enums
347
440
 
348
- for (const fieldName in lpRow){
349
-
441
+ for (const fieldName in lpRow) {
350
442
  const lpFieldEntry = lpRow[fieldName]; // like 'smartcontrol.0.Test.light.Bathroom' or true, etc.
351
443
 
352
- if (! ((['active', 'name'].indexOf(fieldName) !== -1)
353
- || (lpTableName == 'tableTriggerMotion' && (['duration', 'briThreshold'].indexOf(fieldName) !== -1))
354
- )) continue;
355
-
444
+ if (!(
445
+ ['active', 'name'].indexOf(fieldName) !== -1 ||
446
+ (lpTableName == 'tableTriggerMotion' &&
447
+ ['duration', 'briThreshold'].indexOf(fieldName) !== -1)
448
+ )) {
449
+ continue;
450
+ }
356
451
 
357
- // Define the common object to create the state
452
+ // Define the common object to create the state
358
453
  const lpCommonObject = {};
359
454
  lpCommonObject.read = true;
360
455
  lpCommonObject.write = true;
@@ -362,54 +457,64 @@ class SmartControl extends utils.Adapter {
362
457
 
363
458
  // Apply different types.
364
459
  if (fieldName == 'active') {
365
- lpCommonObject.name = 'Please note: Changing this state restarts the adapter instance for being able to apply the change.';
460
+ lpCommonObject.name =
461
+ 'Please note: Changing this state restarts the adapter instance for being able to apply the change.';
366
462
  lpCommonObject.type = 'boolean';
367
- lpCommonObject.def = lpFieldEntry;
463
+ lpCommonObject.def = lpFieldEntry;
368
464
  }
369
465
  if (fieldName == 'name') {
370
466
  lpCommonObject.name = fieldName;
371
467
  lpCommonObject.write = false; // Don't allow to change the 'name'
372
468
  lpCommonObject.type = 'string';
373
- lpCommonObject.def = (typeof lpFieldEntry != 'string') ? JSON.stringify(lpFieldEntry) : lpFieldEntry;
469
+ lpCommonObject.def =
470
+ typeof lpFieldEntry != 'string' ? JSON.stringify(lpFieldEntry) : lpFieldEntry;
374
471
  }
375
- if (lpTableName == 'tableTriggerMotion' && (['duration', 'briThreshold'].indexOf(fieldName) !== -1)) {
376
- lpCommonObject.name = 'Please note: Changing this state restarts the adapter instance for being able to apply the change.';
472
+ if (
473
+ lpTableName == 'tableTriggerMotion' &&
474
+ ['duration', 'briThreshold'].indexOf(fieldName) !== -1
475
+ ) {
476
+ lpCommonObject.name =
477
+ 'Please note: Changing this state restarts the adapter instance for being able to apply the change.';
377
478
  lpCommonObject.type = 'number';
378
- lpCommonObject.def = parseInt(lpFieldEntry);
479
+ lpCommonObject.def = parseInt(lpFieldEntry);
379
480
  }
380
481
 
381
482
  const lpStatePath = `${this.namespace}.options.${lpStateSubSection}.${lpRowNameStatePortion}.${fieldName}`; // Like: 'options.TargetDevices.Bathroom Light'
382
- if (! this.x.helper.isStateIdValid(`${this.namespace}.${lpStatePath}`) ) {
383
- this.log.error(`[${tablesToProcess[i]}] We were not able to generate a valid state path. This is what was determined to be not valid: [${lpStatePath}].`);
483
+ if (!this.x.helper.isStateIdValid(`${this.namespace}.${lpStatePath}`)) {
484
+ this.log.error(
485
+ `[${tablesToProcess[i]}] We were not able to generate a valid state path. This is what was determined to be not valid: [${lpStatePath}].`,
486
+ );
384
487
  errorCounter++;
385
488
  continue;
386
489
  }
387
- statesFull.push({statePath:lpStatePath, commonObject:lpCommonObject });
490
+ statesFull.push({ statePath: lpStatePath, commonObject: lpCommonObject });
388
491
  statePathsOnly.push(lpStatePath);
389
-
390
492
  }
391
493
  }
392
494
  }
393
-
495
+
394
496
  if (errorCounter > 0) {
395
- throw(`${errorCounter} error(s) occurred while processing state generation of options.`);
497
+ throw `${errorCounter} error(s) occurred while processing state generation of options.`;
396
498
  } else if (statesFull.length == 0) {
397
- throw(`No states to be created determined while processing state generation of options.`);
499
+ throw `No states to be created determined while processing state generation of options.`;
398
500
  }
399
501
 
400
502
  // Create states
401
503
  const res = await this.x.helper.asyncCreateStates(statesFull, false);
402
504
  if (!res) {
403
- throw(`Certain error(s) occurred in asyncCreateStates().`);
505
+ throw `Certain error(s) occurred in asyncCreateStates().`;
404
506
  }
405
507
  // Delete all states which are no longer used.
406
508
  const allAdapterStates = await this.getStatesOfAsync('options');
407
509
  if (allAdapterStates != undefined) {
408
510
  for (const lpState of allAdapterStates) {
409
511
  const statePath = lpState._id; // like: 'smartcontrol.0.options.Zones.Hallway.name'
410
- if ( (statePathsOnly.indexOf(statePath) == -1) && (statePath.endsWith('active') || (statePath.endsWith('name') ) ) ) {
512
+ if (
513
+ statePathsOnly.indexOf(statePath) == -1 &&
514
+ (statePath.endsWith('active') || statePath.endsWith('name'))
515
+ ) {
411
516
  // State is no longer used.
412
- await this.delObjectAsync(statePath); // Delete state.
517
+ await this.delObjectAsync(statePath); // Delete state.
413
518
  this.x.helper.logExtendedInfo(`State ${statePath} deleted, since option does no longer exist.`);
414
519
  }
415
520
  }
@@ -417,26 +522,23 @@ class SmartControl extends utils.Adapter {
417
522
 
418
523
  // Update option states. Required if admin options were changed and saved (which restarts adapter).
419
524
  for (const lpStatePath of statePathsOnly) {
420
-
421
525
  // {name:'Hallway', index:2, table:'tableZones', field:'active', row:{.....} }
422
526
  const optionObj = await this._asyncGetOptionForOptionStatePath(lpStatePath);
423
527
 
424
528
  // Set the state
425
529
  let val;
426
- if(typeof optionObj.row[optionObj.field] == 'object') {
530
+ if (typeof optionObj.row[optionObj.field] == 'object') {
427
531
  val = JSON.stringify(optionObj.row[optionObj.field]);
428
532
  } else {
429
533
  if (lpStatePath.endsWith('briThreshold')) {
430
534
  val = parseInt(optionObj.row[optionObj.field]);
431
- }
432
- else if (lpStatePath.endsWith('duration')) {
535
+ } else if (lpStatePath.endsWith('duration')) {
433
536
  val = parseInt(optionObj.row[optionObj.field]);
434
- }
435
- else {
537
+ } else {
436
538
  val = optionObj.row[optionObj.field];
437
539
  }
438
540
  }
439
- await this.setStateAsync(lpStatePath, {val:val, ack:true});
541
+ await this.setStateAsync(lpStatePath, { val: val, ack: true });
440
542
  }
441
543
 
442
544
  /**
@@ -446,14 +548,16 @@ class SmartControl extends utils.Adapter {
446
548
  if (lpZoneRow.active) {
447
549
  this.x.zonesIsOn[lpZoneRow.name] = false;
448
550
  }
449
- }
450
-
551
+ }
451
552
 
452
553
  /**
453
554
  * Init Trigger instances of Trigger class for each trigger
454
555
  */
455
- // @ts-ignore No overload matches this call -> https://github.com/microsoft/TypeScript/issues/36769
456
- const allTriggerRows = this.config.tableTriggerMotion.concat(this.config.tableTriggerDevices, this.config.tableTriggerTimes);
556
+ // @ts-expect-error No overload matches this call -> https://github.com/microsoft/TypeScript/issues/36769
557
+ const allTriggerRows = this.config.tableTriggerMotion.concat(
558
+ this.config.tableTriggerDevices,
559
+ this.config.tableTriggerTimes,
560
+ );
457
561
  for (const lpTriggerRow of allTriggerRows) {
458
562
  if (lpTriggerRow.active) {
459
563
  const triggerName = lpTriggerRow.name;
@@ -461,8 +565,6 @@ class SmartControl extends utils.Adapter {
461
565
  }
462
566
  }
463
567
 
464
-
465
-
466
568
  /**
467
569
  * STATE SUBSCRIPTIONS
468
570
  */
@@ -477,29 +579,29 @@ class SmartControl extends utils.Adapter {
477
579
  await this.subscribeForeignStatesAsync(lpRow.offState);
478
580
  }
479
581
  }
480
-
582
+
481
583
  // STATE SUBSCRIPTION: to all smartcontrol.x.targetURLs states
482
584
  for (const lpRow of this.config.tableTargetURLs) {
483
585
  if (lpRow.active) {
484
- await this.subscribeStatesAsync(lpRow.stateId + '.call_on');
586
+ await this.subscribeStatesAsync(`${lpRow.stateId}.call_on`);
485
587
  if (lpRow.urlOff && !this.x.helper.isLikeEmpty(lpRow.urlOff)) {
486
- await this.subscribeStatesAsync(lpRow.stateId + '.call_off');
588
+ await this.subscribeStatesAsync(`${lpRow.stateId}.call_off`);
487
589
  }
488
590
  }
489
591
  }
490
-
592
+
491
593
  // STATE SUBSCRIPTION: to all 'smartcontrol.0.options.TriggerMotion.xxx.<duration|briThreshold>'
492
594
  await this.subscribeStatesAsync('smartcontrol.0.options.TriggerMotion.*.duration');
493
595
  await this.subscribeStatesAsync('smartcontrol.0.options.TriggerMotion.*.briThreshold');
494
596
 
495
597
  // STATE SUBSCRIPTION: to all 'smartcontrol.x.options.x.x.active'
496
- await this.subscribeStatesAsync('options.*.active');
598
+ await this.subscribeStatesAsync('options.*.active');
497
599
 
498
600
  // STATE SUBSCRIPTION: to Triggers: Motion and Devices
499
- // @ts-ignore -> https://github.com/microsoft/TypeScript/issues/36769
601
+ // @ts-expect-error -> https://github.com/microsoft/TypeScript/issues/36769
500
602
  for (const lpRow of this.config.tableTriggerMotion.concat(this.config.tableTriggerDevices)) {
501
603
  if (lpRow.active) {
502
- const statePath = lpRow.stateId; // like '0_userdata.0.motion-sensor.Bathroom.motion'
604
+ const statePath = lpRow.stateId; // like '0_userdata.0.motion-sensor.Bathroom.motion'
503
605
  await this.subscribeForeignStatesAsync(statePath); // Info: we already validated in asyncVerifyConfig() if state exists
504
606
  }
505
607
  }
@@ -512,80 +614,91 @@ class SmartControl extends utils.Adapter {
512
614
  /**
513
615
  * Re-schedule all trigger times every midnight. Also, refresh astro states.
514
616
  * This is required since we are supporting astro times (suncalc)
515
- */
617
+ */
516
618
  this.x.schedules.midnight = this.x.mSchedule.scheduleJob('0 0 * * *', () => {
517
- this._asyncOnReady_asyncScheduleTriggerTimes();
518
- if (this.x.systemConfig.latitude && this.x.systemConfig.longitude) this._asyncOnReady_asyncRefreshAstroStates();
519
- this.x.helper.logExtendedInfo(`Re-scheduling time triggers for updating astro times and updating 'info.astroTimes.' states.`);
619
+ // Nicht sofort re-schedulen: cancel() in derselben Sekunde verschluckt 00:00-Auslöser (#8).
620
+ if (this.x.midnightRescheduleTimer) {
621
+ clearTimeout(this.x.midnightRescheduleTimer);
622
+ }
623
+ this.x.midnightRescheduleTimer = setTimeout(() => {
624
+ this.x.midnightRescheduleTimer = null;
625
+ this._asyncOnReady_asyncScheduleTriggerTimes();
626
+ if (this.x.systemConfig.latitude && this.x.systemConfig.longitude) {
627
+ this._asyncOnReady_asyncRefreshAstroStates();
628
+ }
629
+ this.x.helper.logExtendedInfo(
630
+ `Re-scheduling time triggers for updating astro times and updating 'info.astroTimes.' states.`,
631
+ );
632
+ }, MIDNIGHT_RESCHEDULE_DELAY_MS);
520
633
  });
521
634
 
522
- this.log.info(`Subscribing to all target devices and trigger states. ${numTriggers} trigger schedules activated...`);
635
+ this.log.info(
636
+ `Subscribing to all target devices and trigger states. ${numTriggers} trigger schedules activated...`,
637
+ );
523
638
  this.setState('info.connection', true, true); // change to green
524
-
525
639
  } catch (error) {
526
640
  this.x.helper.dumpError('[_asyncOnReady()]', error);
527
641
  this.setState('info.connection', false, true); // change to yellow
528
642
  return;
529
643
  }
530
-
531
644
  }
532
645
 
533
-
534
646
  /**
535
647
  * Get messages from Adapter Configuration UI
536
648
  * Using this method requires "common.message" property to be set to true in io-package.json
649
+ *
537
650
  * @param {ioBroker.Message} obj
538
651
  */
539
652
  async _asyncOnMessage(obj) {
540
-
541
653
  try {
542
-
543
- if (typeof obj !== 'object') throw (`Verify input object: object is not defined.`);
544
- if (!obj.message) throw (`Verify input object: object.message is not defined.`);
545
- if (!obj.callback) throw (`Verify input object: object.callback is not defined.`);
654
+ if (typeof obj !== 'object') {
655
+ throw `Verify input object: object is not defined.`;
656
+ }
657
+ if (!obj.message) {
658
+ throw `Verify input object: object.message is not defined.`;
659
+ }
660
+ if (!obj.callback) {
661
+ throw `Verify input object: object.callback is not defined.`;
662
+ }
546
663
 
547
664
  /**********************************
548
665
  * Verify the configuration from admin/index_m.html, once user hits the save button.
549
666
  *********************************/
550
667
  if (obj.command == 'verifyConfig') {
551
-
552
- this.log.debug(`[_asyncOnMessage] command 'Verify Adapter Configuration' received from admin/index_m.html. Verifying the configuration and sending the result back to index_m.html...`);
668
+ this.log.debug(
669
+ `[_asyncOnMessage] command 'Verify Adapter Configuration' received from admin/index_m.html. Verifying the configuration and sending the result back to index_m.html...`,
670
+ );
553
671
 
554
672
  // Verify and send the result back to admin/index_m.html
555
- const configVerificationResult = await this._asyncVerifyConfig(obj.message);
673
+ const configVerificationResult = await this._asyncVerifyConfig(obj.message);
556
674
  this.sendTo(obj.from, obj.command, configVerificationResult, obj.callback);
557
675
  // Some log
558
676
  if (configVerificationResult.passed) {
559
677
  this.log.debug(`[_asyncOnMessage] Configuration successfully verified, no issues found.`);
560
678
  } else {
561
- this.log.debug(`[_asyncOnMessage] Configuration verification failed, ${configVerificationResult.issues.length} issue(s) found.`);
679
+ this.log.debug(
680
+ `[_asyncOnMessage] Configuration verification failed, ${configVerificationResult.issues.length} issue(s) found.`,
681
+ );
562
682
  }
563
-
564
683
  } else {
565
- throw (`[_asyncOnMessage] sendTo() received object, but command '${obj.command}' is not defined in this method.`);
684
+ throw `[_asyncOnMessage] sendTo() received object, but command '${obj.command}' is not defined in this method.`;
566
685
  }
567
-
568
686
  } catch (error) {
569
687
  this.x.helper.dumpError('[_asyncOnMessage()]', error);
570
688
  }
571
689
  }
572
-
573
-
574
690
 
575
691
  /**
576
692
  * Schedule all trigger times of Trigger Times table
577
- *
578
- * @return {Promise<number>} number of schedules activated.
579
- * @fires trigger.asyncSetTargetDevices()
693
+ *
694
+ * @returns {Promise<number>} number of schedules activated.
695
+ * @fires trigger.asyncSetTargetDevices()
580
696
  */
581
697
  async _asyncOnReady_asyncScheduleTriggerTimes() {
582
-
583
698
  try {
584
-
585
699
  let counter = 0;
586
700
  for (const lpRow of this.config.tableTriggerTimes) {
587
701
  if (lpRow.active) {
588
-
589
702
  // Convert non-crons to cron
590
703
  let cron = '';
591
704
  if (this.x.helper.isCronScheduleValid(lpRow.time.trim())) {
@@ -601,75 +714,80 @@ class SmartControl extends utils.Adapter {
601
714
  }
602
715
 
603
716
  // Cancel schedule first. See issue https://github.com/Mic-M/ioBroker.smartcontrol/issues/43
604
- if(this.x.schedules[lpRow.name] !== undefined && this.x.schedules[lpRow.name] !== null) {
717
+ if (this.x.schedules[lpRow.name] !== undefined && this.x.schedules[lpRow.name] !== null) {
605
718
  this.x.schedules[lpRow.name].cancel();
606
719
  this.x.schedules[lpRow.name] = null; // just in case.
607
720
  }
608
721
  this.x.schedules[lpRow.name] = this.x.mSchedule.scheduleJob(cron, async () => {
609
-
610
722
  const triggerName = lpRow.name;
611
723
  const trigger = this.x.triggers[triggerName]; // Trigger class instance
612
- this.log.debug(`--- Trigger [${triggerName}] was triggered per schedule (time: ${trigger.triggerTime}) ---`);
724
+ this.log.debug(
725
+ `--- Trigger [${triggerName}] was triggered per schedule (time: ${trigger.triggerTime}) ---`,
726
+ );
613
727
 
614
728
  // First check if additional conditions are met or "never if"
615
- let doContinue = await trigger.asyncAreScheduleConditionsMet('Trigger: Additional Conditions', trigger.triggerTmAdditionCond, trigger.triggerTmAddCondAll);
616
- if (doContinue) doContinue = await trigger.asyncAreScheduleConditionsMet('Trigger: "Never if" Conditions', trigger.triggerTmNever, trigger.triggerTmNeverAll, true);
617
- if(!doContinue) {
618
- this.x.helper.logExtendedInfo(`Trigger [${triggerName}] (time: ${trigger.triggerTime}) triggered, but condition(s) not met.`);
729
+ let doContinue = await trigger.asyncAreScheduleConditionsMet(
730
+ 'Trigger: Additional Conditions',
731
+ trigger.triggerTmAdditionCond,
732
+ trigger.triggerTmAddCondAll,
733
+ );
734
+ if (doContinue) {
735
+ doContinue = await trigger.asyncAreScheduleConditionsMet(
736
+ 'Trigger: "Never if" Conditions',
737
+ trigger.triggerTmNever,
738
+ trigger.triggerTmNeverAll,
739
+ true,
740
+ );
741
+ }
742
+ if (!doContinue) {
743
+ this.x.helper.logExtendedInfo(
744
+ `Trigger [${triggerName}] (time: ${trigger.triggerTime}) triggered, but condition(s) not met.`,
745
+ );
619
746
  return;
620
747
  }
621
748
  trigger.asyncSetTargetDevices();
622
749
  });
623
750
  counter++;
624
-
625
751
  }
626
752
  }
627
753
  return counter;
628
-
629
754
  } catch (error) {
630
755
  this.x.helper.dumpError('[_asyncOnReady_asyncScheduleTriggerTimes]', error);
631
756
  return 0;
632
- }
633
-
757
+ }
634
758
  }
635
759
 
636
760
  /**
637
761
  * Refresh the astro states under smartcontrol.x.info.astroTimes
638
762
  */
639
763
  async _asyncOnReady_asyncRefreshAstroStates() {
640
-
641
764
  try {
642
-
643
765
  for (let i = 0; i < this.x.constants.astroTimes.length; i++) {
644
766
  const lpAstro = this.x.constants.astroTimes[i];
645
767
 
646
768
  const ts = this.x.helper.getAstroNameTs(lpAstro);
647
769
  const astroTimeStr = this.x.helper.timestampToTimeString(ts, true);
648
- await this.setStateAsync(`info.astroTimes.${this.x.helper.zeroPad(i+1, 2)}_${lpAstro}`, {val: astroTimeStr, ack: true });
649
-
650
- await this.setStateAsync(`info.astroTimes.timeStamps.${lpAstro}`, {val: ts, ack: true });
770
+ await this.setStateAsync(`info.astroTimes.${this.x.helper.zeroPad(i + 1, 2)}_${lpAstro}`, {
771
+ val: astroTimeStr,
772
+ ack: true,
773
+ });
651
774
 
775
+ await this.setStateAsync(`info.astroTimes.timeStamps.${lpAstro}`, { val: ts, ack: true });
652
776
  }
653
-
654
777
  } catch (error) {
655
778
  this.x.helper.dumpError('[_asyncOnReady_asyncRefreshAstroStates()]', error);
656
- return false;
779
+ return false;
657
780
  }
658
-
659
781
  }
660
782
 
661
-
662
-
663
783
  /**
664
784
  * Initialized by Class constructor and called once a subscribed state changes
665
- *
785
+ *
666
786
  * @param {string} statePath State Path
667
787
  * @param {ioBroker.State | null | undefined} stateObject State object
668
788
  */
669
789
  async _asyncOnStateChange(statePath, stateObject) {
670
-
671
790
  try {
672
-
673
791
  let stateChangeCounter = 0;
674
792
 
675
793
  if (!stateObject) {
@@ -681,13 +799,18 @@ class SmartControl extends utils.Adapter {
681
799
 
682
800
  // Check acknowledge (ack)
683
801
  const ackPassingResult = await this.x.helper.isAckPassing(statePath, stateObject);
684
- if ( ! ackPassingResult.passing ) {
685
- if (!statePath.startsWith(this.namespace)) // no log needed for smartcontrol.x states
686
- this.log.debug(`State Change: IGNORED – state '${statePath}' change: ack '${stateObject.ack}' - ${ackPassingResult.msg}`);
802
+ if (!ackPassingResult.passing) {
803
+ if (!statePath.startsWith(this.namespace)) {
804
+ // no log needed for smartcontrol.x states
805
+ this.log.debug(
806
+ `State Change: IGNORED – state '${statePath}' change: ack '${stateObject.ack}' - ${ackPassingResult.msg}`,
807
+ );
808
+ }
687
809
  return;
688
- } else {
689
- this.log.debug(`State Change: ACCEPTED – state '${statePath}' change: ack '${stateObject.ack}' - ${ackPassingResult.msg}`);
690
810
  }
811
+ this.log.debug(
812
+ `State Change: ACCEPTED – state '${statePath}' change: ack '${stateObject.ack}' - ${ackPassingResult.msg}`,
813
+ );
691
814
 
692
815
  /**
693
816
  * State Change: smartcontrol.0.options.XXX.XXX.active
@@ -698,24 +821,29 @@ class SmartControl extends utils.Adapter {
698
821
 
699
822
  // {name:'Hallway', index:2, table:'tableZones', field:'active', row:{.....} }
700
823
  const optionObj = await this._asyncGetOptionForOptionStatePath(statePath);
701
-
824
+
702
825
  // Check if new value != old value
703
826
  if (optionObj.row[optionObj.field] == stateObject.val) {
704
- this.log.info(`Smart Control Adapter State '${statePath}' changed to '${stateObject.val}', but is equal to old state val, so no action at this point.`);
827
+ this.log.info(
828
+ `Smart Control Adapter State '${statePath}' changed to '${stateObject.val}', but is equal to old state val, so no action at this point.`,
829
+ );
705
830
  } else {
831
+ this.x.helper.logExtendedInfo(
832
+ `Smart Control Adapter State '${statePath}' changed to '${stateObject.val}'.`,
833
+ );
834
+ await this.setStateAsync(statePath, { val: stateObject.val, ack: true }); // Acknowledge State Change
706
835
 
707
- this.x.helper.logExtendedInfo(`Smart Control Adapter State '${statePath}' changed to '${stateObject.val}'.`);
708
- await this.setStateAsync(statePath, {val:stateObject.val, ack: true}); // Acknowledge State Change
709
-
710
836
  // Set config change into adapter configuration. This will also restart the adapter instance by intention.
711
837
  // Restart is required since an activation or deactivation of a table row has multiple effects.
712
- this.log.info(`State change of '${statePath}' to '${stateObject.val}' now executes an adapter instance restart to put the change into effect.`);
838
+ this.log.info(
839
+ `State change of '${statePath}' to '${stateObject.val}' now executes an adapter instance restart to put the change into effect.`,
840
+ );
713
841
  const resultObject = await this.getForeignObjectAsync(`system.adapter.${this.namespace}`);
714
842
  if (resultObject) {
715
843
  resultObject.native[optionObj.table][optionObj.index][optionObj.field] = stateObject.val;
716
844
  await this.setForeignObjectAsync(`system.adapter.${this.namespace}`, resultObject);
717
845
  } else {
718
- throw('getForeignObjectAsync(): No object provided from function.');
846
+ throw 'getForeignObjectAsync(): No object provided from function.';
719
847
  }
720
848
  }
721
849
  }
@@ -723,181 +851,237 @@ class SmartControl extends utils.Adapter {
723
851
  /**
724
852
  * State Change: smartcontrol.0.options.TriggerMotion.xxx.duration and .briThreshold
725
853
  */
726
- if (statePath.startsWith(`${this.namespace}.options.TriggerMotion.`) && (statePath.endsWith('.duration') || (statePath.endsWith('.briThreshold') ))) {
854
+ if (
855
+ statePath.startsWith(`${this.namespace}.options.TriggerMotion.`) &&
856
+ (statePath.endsWith('.duration') || statePath.endsWith('.briThreshold'))
857
+ ) {
727
858
  stateChangeCounter++;
728
- this.log.debug(`smartcontrol options.TriggerMotion<duration|briThreshold> - Subscribed state '${statePath}' changed.`);
859
+ this.log.debug(
860
+ `smartcontrol options.TriggerMotion<duration|briThreshold> - Subscribed state '${statePath}' changed.`,
861
+ );
729
862
 
730
863
  // {name:'Motion.Bathroom', index:2, table:'tableTriggerMotion', field:'active', row:{.....} }
731
864
  const optionObj = await this._asyncGetOptionForOptionStatePath(statePath);
732
-
865
+
733
866
  // Check if new value != old value
734
867
  if (optionObj.row[optionObj.field] == stateObject.val) {
735
- this.x.helper.logExtendedInfo(`Smart Control Adapter State '${statePath}' changed to '${stateObject.val}', but is equal to old state val, so no action at this point.`);
868
+ this.x.helper.logExtendedInfo(
869
+ `Smart Control Adapter State '${statePath}' changed to '${stateObject.val}', but is equal to old state val, so no action at this point.`,
870
+ );
736
871
  } else {
872
+ this.x.helper.logExtendedInfo(
873
+ `Smart Control Adapter State '${statePath}' changed to '${stateObject.val}'.`,
874
+ );
875
+ await this.setStateAsync(statePath, { val: stateObject.val, ack: true }); // Acknowledge State Change
737
876
 
738
- this.x.helper.logExtendedInfo(`Smart Control Adapter State '${statePath}' changed to '${stateObject.val}'.`);
739
- await this.setStateAsync(statePath, {val:stateObject.val, ack: true}); // Acknowledge State Change
740
-
741
877
  // Set config change into adapter configuration. This will also restart the adapter instance by intention.
742
878
  // Restart is required since an activation or deactivation of a table row has multiple effects.
743
- this.log.info(`State change of '${statePath}' to '${stateObject.val}' now executes an adapter instance restart to put the change into effect.`);
879
+ this.log.info(
880
+ `State change of '${statePath}' to '${stateObject.val}' now executes an adapter instance restart to put the change into effect.`,
881
+ );
744
882
  const resultObject = await this.getForeignObjectAsync(`system.adapter.${this.namespace}`);
745
883
  if (resultObject) {
746
- const stateVal = (!stateObject.val) ? '' : stateObject.val.toString(); // the number is a string in adapter config
884
+ const stateVal = !stateObject.val ? '' : stateObject.val.toString(); // the number is a string in adapter config
747
885
  resultObject.native[optionObj.table][optionObj.index][optionObj.field] = stateVal;
748
886
  await this.setForeignObjectAsync(`system.adapter.${this.namespace}`, resultObject);
749
887
  } else {
750
- throw('getForeignObjectAsync(): No object provided from function.');
888
+ throw 'getForeignObjectAsync(): No object provided from function.';
751
889
  }
752
890
  }
753
891
  }
754
892
 
755
-
756
893
  /**
757
894
  * State Change: smartcontrol.x.targetDevices.xxx
758
- */
895
+ */
759
896
  if (statePath.startsWith(`${this.namespace}.targetDevices.`)) {
760
897
  stateChangeCounter++;
761
898
  this.log.debug(`smartcontrol targetDevices - Subscribed state '${statePath}' changed.`);
762
899
 
763
900
  let targetDevicesRow = {};
764
901
  for (const lpRow of this.config.tableTargetDevices) {
765
- if (!lpRow.active) continue;
902
+ if (!lpRow.active) {
903
+ continue;
904
+ }
766
905
  if (`${this.namespace}.targetDevices.${lpRow.name}` == statePath) {
767
906
  targetDevicesRow = lpRow;
768
907
  break;
769
908
  }
770
909
  }
771
- if(this.x.helper.isLikeEmpty(targetDevicesRow)) throw (`Table 'Target Devices': No row found for state path ${statePath}`);
772
-
910
+ if (this.x.helper.isLikeEmpty(targetDevicesRow)) {
911
+ throw `Table 'Target Devices': No row found for state path ${statePath}`;
912
+ }
913
+
773
914
  // Set target states.
774
915
  // Note: Verification of the state value and conversion as needed was performed already by asyncVerifyConfig()
775
- const w = (stateObject.val) ? 'on' : 'off';
776
- await this.setForeignStateAsync(targetDevicesRow[w+'State'], {val: targetDevicesRow[w+'Value'], ack: false });
777
-
778
- // confirm by ack:true
779
- await this.setStateAsync(statePath, {val: stateObject.val, ack: true });
916
+ const w = stateObject.val ? 'on' : 'off';
917
+ await this.setForeignStateAsync(targetDevicesRow[`${w}State`], {
918
+ val: targetDevicesRow[`${w}Value`],
919
+ ack: false,
920
+ });
780
921
 
781
- }
922
+ // confirm by ack:true
923
+ await this.setStateAsync(statePath, { val: stateObject.val, ack: true });
924
+ }
782
925
 
783
926
  /**
784
927
  * State Change: smartcontrol.0.targetURLs.xxx.call_on / smartcontrol.0.targetURLs.xxx.call_off
785
- */
786
- if (statePath.startsWith(`${this.namespace}.targetURLs.`) && (statePath.endsWith('.call_on') || statePath.endsWith('.call_off')) && stateObject.val === true) {
928
+ */
929
+ if (
930
+ statePath.startsWith(`${this.namespace}.targetURLs.`) &&
931
+ (statePath.endsWith('.call_on') || statePath.endsWith('.call_off')) &&
932
+ stateObject.val === true
933
+ ) {
787
934
  stateChangeCounter++;
788
935
  this.log.debug(`smartcontrol targetURLs - Subscribed state '${statePath}' changed.`);
789
936
 
790
- // Prefix 'smartcontrol.0.targetURLs.' was already added in asyncVerifyConfig() to name and
937
+ // Prefix 'smartcontrol.0.targetURLs.' was already added in asyncVerifyConfig() to name and
791
938
  // available as "stateId" is table rows
792
939
  let stateMainObjectId;
793
940
  let what = ''; // on or off
794
941
  if (statePath.endsWith('.call_on')) {
795
942
  what = 'On';
796
- stateMainObjectId = statePath.substring(0, statePath.length-8); // remove '.call_on'
943
+ stateMainObjectId = statePath.substring(0, statePath.length - 8); // remove '.call_on'
797
944
  } else {
798
945
  what = 'Off';
799
- stateMainObjectId = statePath.substring(0, statePath.length-9); // remove '.call_off'
946
+ stateMainObjectId = statePath.substring(0, statePath.length - 9); // remove '.call_off'
800
947
  }
801
-
948
+
802
949
  const name = this.getOptionTableValue('tableTargetURLs', 'stateId', stateMainObjectId, 'name');
803
- const url = this.getOptionTableValue('tableTargetURLs', 'stateId', stateMainObjectId, 'url' + what);
950
+ const url = this.getOptionTableValue('tableTargetURLs', 'stateId', stateMainObjectId, `url${what}`);
804
951
 
805
952
  if (name && url) {
806
-
807
953
  try {
808
954
  this.log.debug(`Trying to call target URL (name: '${name}', URL: '${url}')`);
809
- // @ts-ignore This expression is not callable.
955
+ // @ts-expect-error This expression is not callable.
810
956
  const response = await this.x.axios.get(url);
811
957
  this.log.debug(`Calling target URL was successful (name: '${name}', URL: '${url}')`);
812
958
  // Set response to state smartcontrol.x.targetURLs.xxxxxxx.response
813
959
  if (this.x.helper.isLikeEmpty(response.body)) {
814
- this.setState(stateMainObjectId + '.response', {val: '(no response text provided)', ack: true }); // no async needed here
960
+ this.setState(`${stateMainObjectId}.response`, {
961
+ val: '(no response text provided)',
962
+ ack: true,
963
+ }); // no async needed here
815
964
  this.log.info(`No 'response.body' as URL call response for name: '${name}', URL: '${url}'`);
816
965
  } else {
817
- const responseVal = (typeof response.body === 'string') ? response.body : JSON.stringify(response.body);
818
- this.setState(stateMainObjectId + '.response', {val: responseVal, ack: true }); // no async needed here
966
+ const responseVal =
967
+ typeof response.body === 'string' ? response.body : JSON.stringify(response.body);
968
+ this.setState(`${stateMainObjectId}.response`, { val: responseVal, ack: true }); // no async needed here
819
969
  this.log.debug(`URL call response: [${responseVal}]`);
820
970
  }
821
971
  } catch (error) {
822
- this.setState(stateMainObjectId + '.response', {val: 'Error: ' + error.response.body, ack: true }); // no async needed here
972
+ this.setState(`${stateMainObjectId}.response`, {
973
+ val: `Error: ${error.response.body}`,
974
+ ack: true,
975
+ }); // no async needed here
823
976
  this.x.helper.dumpError(`Error calling target URL - name: '${name}', URL: '${url}'`);
824
977
  this.x.helper.dumpError('Message: ', error.response.body);
825
978
  }
826
-
827
979
  } else {
828
- this.log.error(`State Change '${statePath}': Could not get name and/or URL from Table 'Targets: URLs'`);
980
+ this.log.error(
981
+ `State Change '${statePath}': Could not get name and/or URL from Table 'Targets: URLs'`,
982
+ );
829
983
  }
830
- }
984
+ }
831
985
 
832
986
  /**
833
987
  * State Change: tableTargetDevices: on/off states
834
988
  */
835
989
  if (
836
- (this.getOptionTableValue('tableTargetDevices', 'onState', statePath, 'name') != undefined)
837
- || (this.getOptionTableValue('tableTargetDevices', 'offState', statePath, 'name') != undefined)
838
- ) {
990
+ this.getOptionTableValue('tableTargetDevices', 'onState', statePath, 'name') != undefined ||
991
+ this.getOptionTableValue('tableTargetDevices', 'offState', statePath, 'name') != undefined
992
+ ) {
839
993
  stateChangeCounter++;
840
- this.log.debug(`State Change: tableTargetDevices: on/off states - Subscribed state '${statePath}' changed.`);
994
+ this.log.debug(
995
+ `State Change: tableTargetDevices: on/off states - Subscribed state '${statePath}' changed.`,
996
+ );
841
997
  for (const lpTargetDeviceRow of this.config.tableTargetDevices) {
842
- if (!lpTargetDeviceRow.active) continue;
843
- if (lpTargetDeviceRow.onState != statePath || lpTargetDeviceRow.offState != statePath) continue;
844
-
845
- if (lpTargetDeviceRow.onState == statePath && lpTargetDeviceRow.onValue == stateObject.val) {
998
+ if (!lpTargetDeviceRow.active) {
999
+ continue;
1000
+ }
1001
+ if (lpTargetDeviceRow.onState != statePath || lpTargetDeviceRow.offState != statePath) {
1002
+ continue;
1003
+ }
846
1004
 
1005
+ if (lpTargetDeviceRow.onState == statePath && lpTargetDeviceRow.onValue == stateObject.val) {
847
1006
  // Set "linked" state.
848
1007
  if (/_enum-\d{1,3}$/.test(lpTargetDeviceRow.name)) {
849
1008
  this.log.debug('enum identified. No state set.');
850
1009
  } else {
851
1010
  this.log.debug('enum not identified');
852
- await this.setStateAsync(`targetDevices.${lpTargetDeviceRow.name}`, {val: true, ack: true });
1011
+ await this.setStateAsync(`targetDevices.${lpTargetDeviceRow.name}`, {
1012
+ val: true,
1013
+ ack: true,
1014
+ });
853
1015
  }
854
- this.log.debug(`State '${statePath}' changed to '${stateObject.val}' -> '${this.namespace}.targetDevices.${lpTargetDeviceRow.name}' set to true.`);
855
-
856
- } else if (lpTargetDeviceRow.offState == statePath && lpTargetDeviceRow.offValue == stateObject.val) {
857
-
1016
+ this.log.debug(
1017
+ `State '${statePath}' changed to '${stateObject.val}' -> '${this.namespace}.targetDevices.${lpTargetDeviceRow.name}' set to true.`,
1018
+ );
1019
+ } else if (
1020
+ lpTargetDeviceRow.offState == statePath &&
1021
+ lpTargetDeviceRow.offValue == stateObject.val
1022
+ ) {
858
1023
  /**
859
1024
  * First: Set "is Zone on" status to false if - with this new state change - all targets of the zone will be off.
860
1025
  */
861
1026
  for (const lpZoneRow of this.config.tableZones) {
862
- if (!lpZoneRow.active) continue;
863
- if (!lpZoneRow.targets.includes(lpTargetDeviceRow.name)) continue;
1027
+ if (!lpZoneRow.active) {
1028
+ continue;
1029
+ }
1030
+ if (!lpZoneRow.targets.includes(lpTargetDeviceRow.name)) {
1031
+ continue;
1032
+ }
864
1033
  let counter = 0;
865
1034
 
866
1035
  for (const lpZoneTargetName of lpZoneRow.targets) {
867
-
868
- if (!lpZoneRow.active) continue;
869
-
1036
+ if (!lpZoneRow.active) {
1037
+ continue;
1038
+ }
1039
+
870
1040
  if (lpTargetDeviceRow.name == lpZoneTargetName) {
871
1041
  // No need to re-check current state value
872
1042
  counter++;
873
1043
  continue;
874
1044
  } else {
875
- const configOffStateId = this.getOptionTableValue('tableTargetDevices', 'name', lpZoneTargetName, 'offState');
876
- const configOffStateVal = this.getOptionTableValue('tableTargetDevices', 'name', lpZoneTargetName, 'offValue');
877
- const actualStateVal = await this.x.helper.asyncGetForeignStateValue(configOffStateId);
878
- if (actualStateVal === configOffStateVal) counter++;
1045
+ const configOffStateId = this.getOptionTableValue(
1046
+ 'tableTargetDevices',
1047
+ 'name',
1048
+ lpZoneTargetName,
1049
+ 'offState',
1050
+ );
1051
+ const configOffStateVal = this.getOptionTableValue(
1052
+ 'tableTargetDevices',
1053
+ 'name',
1054
+ lpZoneTargetName,
1055
+ 'offValue',
1056
+ );
1057
+ const actualStateVal =
1058
+ await this.x.helper.asyncGetForeignStateValue(configOffStateId);
1059
+ if (actualStateVal === configOffStateVal) {
1060
+ counter++;
1061
+ }
879
1062
  }
880
1063
  }
881
1064
  if (counter === lpZoneRow.targets.length) {
882
-
883
1065
  // Set "is Zone on" status to false since all target devices do have the 'off' state now.
884
1066
  this.x.zonesIsOn[lpZoneRow.name] = false;
885
-
886
- // Cancel timers
887
- // NOTE: We cannot cancel trigger timer 'motionTimer' since it may also trigger other zones.
888
- // TODO: We should address motion timers as well.
889
- const timerObjIds = ['timersZoneOff', 'timersMimicMotionTrigger'];
1067
+
1068
+ // Cancel timers (motion off is per zone, so it is safe to clear here — #147)
1069
+ const timerObjIds = ['timersZoneOff', 'timersMimicMotionTrigger', 'timersMotionOff'];
890
1070
  let timerCounter = 0;
891
1071
  for (const lpTimerObjId of timerObjIds) {
892
- const lpTimeLeft = this.x.helper.getTimeoutTimeLeft(this.x[lpTimerObjId][lpZoneRow.name]);
1072
+ const lpTimeLeft = this.x.helper.getTimeoutTimeLeft(
1073
+ this.x[lpTimerObjId][lpZoneRow.name],
1074
+ );
893
1075
  if (lpTimeLeft > -1) {
894
1076
  clearTimeout(this.x[lpTimerObjId][lpZoneRow.name]);
895
1077
  this.x[lpTimerObjId][lpZoneRow.name] = null;
896
1078
  timerCounter++;
897
1079
  }
898
- }
1080
+ }
899
1081
  if (timerCounter > 0) {
900
- this.log.debug(`All targets of zone switched off. Therefore, ${timerCounter} running timers canceled..`);
1082
+ this.log.debug(
1083
+ `All targets of zone switched off. Therefore, ${timerCounter} running timers canceled..`,
1084
+ );
901
1085
  } else {
902
1086
  this.log.debug(`All targets of zone switched off, but no active timers to cancel.`);
903
1087
  }
@@ -911,22 +1095,29 @@ class SmartControl extends utils.Adapter {
911
1095
  this.log.debug('Second: Set "linked" state. enum identified. No state set.');
912
1096
  } else {
913
1097
  this.log.debug('Second: Set "linked" state. enum not identified');
914
- await this.setStateAsync(`targetDevices.${lpTargetDeviceRow.name}`, {val: false, ack: true });
1098
+ await this.setStateAsync(`targetDevices.${lpTargetDeviceRow.name}`, {
1099
+ val: false,
1100
+ ack: true,
1101
+ });
915
1102
  }
916
- this.log.debug(`State '${statePath}' changed to '${stateObject.val}' -> '${this.namespace}.targetDevices.${lpTargetDeviceRow.name}' set to false.`);
1103
+ this.log.debug(
1104
+ `State '${statePath}' changed to '${stateObject.val}' -> '${this.namespace}.targetDevices.${lpTargetDeviceRow.name}' set to false.`,
1105
+ );
917
1106
  }
918
1107
  }
919
1108
  }
920
1109
 
921
1110
  /**
922
1111
  * State Change: Trigger of tableTriggerMotion or tableTriggerDevices
923
- */
1112
+ */
924
1113
  if (
925
- (this.getOptionTableValue('tableTriggerMotion', 'stateId', statePath, 'name') != undefined)
926
- || (this.getOptionTableValue('tableTriggerDevices', 'stateId', statePath, 'name') != undefined)
1114
+ this.getOptionTableValue('tableTriggerMotion', 'stateId', statePath, 'name') != undefined ||
1115
+ this.getOptionTableValue('tableTriggerDevices', 'stateId', statePath, 'name') != undefined
927
1116
  ) {
928
1117
  stateChangeCounter++;
929
- this.log.debug(`State Change: Trigger of tableTriggerMotion or tableTriggerDevices - Subscribed state '${statePath}' changed.`);
1118
+ this.log.debug(
1119
+ `State Change: Trigger of tableTriggerMotion or tableTriggerDevices - Subscribed state '${statePath}' changed.`,
1120
+ );
930
1121
  this.asyncDoOnTriggerActivated(statePath, stateObject);
931
1122
  }
932
1123
 
@@ -934,50 +1125,42 @@ class SmartControl extends utils.Adapter {
934
1125
  * State Change: Everything else
935
1126
  */
936
1127
  if (stateChangeCounter == 0) {
937
- this.log.debug(`State '${statePath}' is subscribed and currently changed, but no action defined in this function to proceed with this state change, which is most likely fine!`);
1128
+ this.log.debug(
1129
+ `State '${statePath}' is subscribed and currently changed, but no action defined in this function to proceed with this state change, which is most likely fine!`,
1130
+ );
938
1131
  } else {
939
1132
  this.log.debug(`State change '${statePath}': ${stateChangeCounter} state change actions identified.`);
940
1133
  }
941
-
942
1134
  } catch (error) {
943
1135
  this.x.helper.dumpError('[_asyncOnStateChange]', error);
944
1136
  }
945
-
946
1137
  }
947
1138
 
948
-
949
1139
  /**
950
1140
  * Called once adapter shuts down; initialized by Class constructor.
1141
+ *
951
1142
  * @param {() => void} callback
952
1143
  */
953
1144
  _onUnload(callback) {
954
-
955
1145
  try {
956
-
957
1146
  /**
958
1147
  * Clear all timeouts
959
1148
  */
960
-
1149
+
961
1150
  // Zone and zone device timers
962
1151
  let timeoutCounter = 0;
963
1152
 
964
-
965
1153
  timeoutCounter += this._clearZoneTimeouts({
966
- 'timersZoneOn': 'zone on-timer',
967
- 'timersZoneOff': 'zone off-timer',
968
- 'timersMimicMotionTrigger': 'zone off-timer for linked trigger',
969
- 'timersZoneDeviceOnDelay': 'zone device on-timer',
1154
+ timersZoneOn: 'zone on-timer',
1155
+ timersZoneOff: 'zone off-timer',
1156
+ timersMimicMotionTrigger: 'zone off-timer for linked trigger',
1157
+ timersZoneDeviceOnDelay: 'zone device on-timer',
1158
+ timersMotionOff: 'zone motion off-timer',
970
1159
  });
971
-
972
- // Motion timers
973
- for (const triggerName in this.x.triggers) {
974
- const timeLeft = this.x.helper.getTimeoutTimeLeft(this.x.triggers[triggerName].motionTimer);
975
- if (timeLeft > -1) {
976
- this.x.helper.logExtendedInfo('Clearing currently running motion timer: ' + triggerName);
977
- clearTimeout(this.x.triggers[triggerName].motionTimer);
978
- this.x.triggers[triggerName].motionTimer = null;
979
- timeoutCounter++;
980
- }
1160
+ if (this.x.midnightRescheduleTimer) {
1161
+ clearTimeout(this.x.midnightRescheduleTimer);
1162
+ this.x.midnightRescheduleTimer = null;
1163
+ timeoutCounter++;
981
1164
  }
982
1165
  this.log.info(`(${timeoutCounter}) timers were active and have been cleared...`);
983
1166
 
@@ -986,8 +1169,8 @@ class SmartControl extends utils.Adapter {
986
1169
  */
987
1170
  let scheduleCounter = 0;
988
1171
  for (const lpScheduleName in this.x.schedules) {
989
- if(this.x.schedules[lpScheduleName]) {
990
- this.log.debug('Cancelling schedule: ' + lpScheduleName);
1172
+ if (this.x.schedules[lpScheduleName]) {
1173
+ this.log.debug(`Cancelling schedule: ${lpScheduleName}`);
991
1174
  this.x.schedules[lpScheduleName].cancel();
992
1175
  scheduleCounter++;
993
1176
  }
@@ -999,7 +1182,6 @@ class SmartControl extends utils.Adapter {
999
1182
  */
1000
1183
  this.log.info('Stopping adapter instance successfully proceeded...');
1001
1184
  callback(); // Callback must be called under any circumstances!
1002
-
1003
1185
  } catch (error) {
1004
1186
  this.x.helper.dumpError('Error while stopping adapter instance', error);
1005
1187
  callback(); // Callback must be called under any circumstances!
@@ -1008,6 +1190,7 @@ class SmartControl extends utils.Adapter {
1008
1190
 
1009
1191
  /**
1010
1192
  * Clear Timeouts
1193
+ *
1011
1194
  * @param {object} timerKeys - Like {'timersZoneOn': 'Zone on-timer', 'timersZoneOff': 'Zone off-timer'}
1012
1195
  */
1013
1196
  _clearZoneTimeouts(timerKeys) {
@@ -1023,101 +1206,125 @@ class SmartControl extends utils.Adapter {
1023
1206
  this.x[lpKey][timerName] = null;
1024
1207
  timeoutCounter++;
1025
1208
  }
1026
- }
1209
+ }
1027
1210
  }
1028
1211
  return timeoutCounter;
1029
1212
  }
1030
1213
 
1214
+ /**
1215
+ * Bewegungs-Aus-Timer aller Zonen löschen, in denen dieser Melder vorkommt.
1216
+ * Warum: Bewegung an BWM2 muss den von BWM1 gestarteten Zonen-Timer stoppen (#147).
1217
+ *
1218
+ * @param {string} triggerName
1219
+ */
1220
+ _clearMotionOffTimersForTrigger(triggerName) {
1221
+ if (!this.config.tableZones) {
1222
+ return;
1223
+ }
1224
+ for (const lpZoneRow of this.config.tableZones) {
1225
+ if (
1226
+ !lpZoneRow ||
1227
+ !lpZoneRow.active ||
1228
+ !Array.isArray(lpZoneRow.triggers) ||
1229
+ !lpZoneRow.triggers.includes(triggerName)
1230
+ ) {
1231
+ continue;
1232
+ }
1233
+ const timeLeft = this.x.helper.getTimeoutTimeLeft(this.x.timersMotionOff[lpZoneRow.name]);
1234
+ if (timeLeft > -1) {
1235
+ this.log.debug(
1236
+ `Clearing zone motion off-timer '${lpZoneRow.name}' (${(timeLeft / 1000).toFixed(0)}s left) because motion on '${triggerName}'.`,
1237
+ );
1238
+ clearTimeout(this.x.timersMotionOff[lpZoneRow.name]);
1239
+ this.x.timersMotionOff[lpZoneRow.name] = null;
1240
+ }
1241
+ }
1242
+ }
1031
1243
 
1032
1244
  /**
1033
1245
  * Get the table option for a given option state
1246
+ *
1034
1247
  * @param {string} statePath like 'smartcontrol.0.options.Zones.Hallway.active'
1035
1248
  * or 'smartcontrol.0.options.Zones.Flur EG.Lichter.Wandlicht 1.active'
1036
- * @return {Promise<object>} { name:'Hallway',
1249
+ * @returns {Promise<object>} { name:'Hallway',
1037
1250
  * index:2, // index of the table
1038
1251
  * table:'tableZones',
1039
1252
  * tableName:'Zones
1040
1253
  * field:'active'
1041
1254
  * row:{} // The full row }
1042
- // */
1255
+ //
1256
+ */
1043
1257
  async _asyncGetOptionForOptionStatePath(statePath) {
1044
-
1045
1258
  try {
1046
-
1047
- if ( statePath.startsWith(`options.`) ) {
1259
+ if (statePath.startsWith(`options.`)) {
1048
1260
  statePath = `${this.namespace}.${statePath}`;
1049
1261
  }
1050
1262
  const statePathSplit = statePath.split('.');
1051
1263
  const stOptionTable = statePathSplit[3]; // Like 'Zones'
1052
- const stOptionName = statePathSplit.slice(4, statePathSplit.length-1).join('.'); // Like 'Hallway' or '.Zones.Flur EG.Lichter.Wandlicht 1'
1053
- const stOptionField = statePathSplit[statePathSplit.length-1]; // Like 'active'
1264
+ const stOptionName = statePathSplit.slice(4, statePathSplit.length - 1).join('.'); // Like 'Hallway' or '.Zones.Flur EG.Lichter.Wandlicht 1'
1265
+ const stOptionField = statePathSplit[statePathSplit.length - 1]; // Like 'active'
1054
1266
  let cName; // The final Option name from state 'smartcontrol.0.options.Zones.Hallway.name'
1055
1267
  try {
1056
1268
  const state = await this.getStateAsync(`options.${stOptionTable}.${stOptionName}.name`);
1057
1269
  if (state) {
1058
1270
  cName = state.val;
1059
1271
  } else {
1060
- throw(`Unable to get state value of statePath '${statePath}'`);
1272
+ throw `Unable to get state value of statePath '${statePath}'`;
1061
1273
  }
1062
- } catch (error) {
1274
+ } catch (error) {
1063
1275
  this.x.helper.dumpError(`Error getting state 'options.${stOptionTable}.${stOptionName}.name'`, error);
1064
1276
  return {};
1065
1277
  }
1066
-
1278
+
1067
1279
  // Find option table index
1068
1280
  let index = -1;
1069
- if(stOptionTable == 'Schedules') {
1281
+ if (stOptionTable == 'Schedules') {
1070
1282
  // Different handling for "tabSchedules" since we have '01_xxx', '02_xxx', etc. as name.
1071
- const num = parseInt(stOptionName.substr(0,2));
1072
- if(this.x.helper.isNumber(num)) {
1073
- index = num-1;
1283
+ const num = parseInt(stOptionName.substr(0, 2));
1284
+ if (this.x.helper.isNumber(num)) {
1285
+ index = num - 1;
1074
1286
  } else {
1075
- throw(`We were not able to convert leading 'xx_' of '${stOptionField}' to a number.`);
1287
+ throw `We were not able to convert leading 'xx_' of '${stOptionField}' to a number.`;
1076
1288
  }
1077
-
1078
1289
  } else {
1079
- for (let i = 0; i < this.config['table' + stOptionTable].length; i++) {
1080
- if (this.config['table' + stOptionTable][i].name == cName) {
1290
+ for (let i = 0; i < this.config[`table${stOptionTable}`].length; i++) {
1291
+ if (this.config[`table${stOptionTable}`][i].name == cName) {
1081
1292
  // We have a hit.
1082
1293
  index = i;
1083
1294
  break;
1084
1295
  }
1085
1296
  }
1086
1297
  if (index == -1) {
1087
- throw(`Unable to find option name '${cName}' in adapter settings, table '${'table' + stOptionTable}'.`);
1298
+ throw `Unable to find option name '${cName}' in adapter settings, table '${`table${stOptionTable}`}'.`;
1088
1299
  }
1089
1300
  }
1090
1301
 
1091
1302
  // Check if the actual key, like 'active', exists in adapter options object
1092
- if (! (stOptionField in this.config['table'+stOptionTable][index]) ) {
1093
- throw(`Key '${stOptionField}' not found in adapter settings, table '${'table' + stOptionTable}'.`);
1303
+ if (!(stOptionField in this.config[`table${stOptionTable}`][index])) {
1304
+ throw `Key '${stOptionField}' not found in adapter settings, table '${`table${stOptionTable}`}'.`;
1094
1305
  }
1095
1306
 
1096
1307
  return {
1097
- name: cName,
1098
- index: index,
1099
- table: 'table' + stOptionTable,
1100
- tableName: stOptionTable,
1101
- field: stOptionField,
1102
- row: this.config['table' + stOptionTable][index]
1308
+ name: cName,
1309
+ index: index,
1310
+ table: `table${stOptionTable}`,
1311
+ tableName: stOptionTable,
1312
+ field: stOptionField,
1313
+ row: this.config[`table${stOptionTable}`][index],
1103
1314
  };
1104
-
1105
1315
  } catch (error) {
1106
1316
  this.x.helper.dumpError('Error', error);
1107
1317
  }
1108
-
1109
1318
  }
1110
1319
 
1111
-
1112
1320
  /**
1113
1321
  * Verify adapter configuration table
1322
+ *
1114
1323
  * @param {object} configObject - configuration object, typically this.config
1115
- * @return {Promise<{passed:boolean, obj:object, issues:array}>} passed: true if successful, false if not. obj: the altered configObject. issues: array of all issue string messages
1324
+ * @returns {Promise<{passed: boolean, obj: object, issues: Array}>} passed: true if successful, false if not. obj: the altered configObject. issues: array of all issue string messages
1116
1325
  */
1117
1326
  async _asyncVerifyConfig(configObject) {
1118
-
1119
1327
  try {
1120
-
1121
1328
  let errors = 0;
1122
1329
  let validTriggerCounter = 0;
1123
1330
  let validTargetDevicesCounter = 0;
@@ -1125,7 +1332,6 @@ class SmartControl extends utils.Adapter {
1125
1332
 
1126
1333
  // FIRST: Check the config array
1127
1334
  for (const functionConfigObj of this.x.constants.configTableValidation) {
1128
-
1129
1335
  /**
1130
1336
  * Prepare the table(s). Typically we only have one table to check, however, 'tableZoneExecution' requires
1131
1337
  * multiple tables (per each row of Table Zones)
@@ -1133,14 +1339,19 @@ class SmartControl extends utils.Adapter {
1133
1339
  const tablesToCheck = []; // Array holding all tables to check. Will be just one element, except to 'tableZoneExecution'
1134
1340
  if (!(functionConfigObj.tableId == 'tableZoneExecution')) {
1135
1341
  // settings of adapter config table, like of 'tableTargetDevices'
1136
- tablesToCheck.push({table: configObject[functionConfigObj.tableId]});
1342
+ tablesToCheck.push({ table: configObject[functionConfigObj.tableId] });
1137
1343
  } else {
1138
-
1139
1344
  let counter = 0;
1140
1345
  for (const lpZoneRow of configObject.tableZones) {
1141
1346
  if (lpZoneRow.active) {
1142
- const tbl = (this.x.helper.isLikeEmpty(lpZoneRow.executionJson)) ? [] : JSON.parse(lpZoneRow.executionJson);
1143
- tablesToCheck.push({zoneTableRowNo:counter, executeAlways:lpZoneRow.executeAlways, table:tbl});
1347
+ const tbl = this.x.helper.isLikeEmpty(lpZoneRow.executionJson)
1348
+ ? []
1349
+ : JSON.parse(lpZoneRow.executionJson);
1350
+ tablesToCheck.push({
1351
+ zoneTableRowNo: counter,
1352
+ executeAlways: lpZoneRow.executeAlways,
1353
+ table: tbl,
1354
+ });
1144
1355
  }
1145
1356
  counter++;
1146
1357
  }
@@ -1150,68 +1361,74 @@ class SmartControl extends utils.Adapter {
1150
1361
  * Handle each table
1151
1362
  */
1152
1363
  for (const lpTable of tablesToCheck) {
1153
- if (lpTable.executeAlways) continue; // Skip if executeAlways is activated
1364
+ if (lpTable.executeAlways) {
1365
+ continue;
1366
+ } // Skip if executeAlways is activated
1154
1367
 
1155
1368
  // For Zone Table Execution only: set "better" table name for log
1156
- if(lpTable.zoneTableRowNo != undefined) {
1369
+ if (lpTable.zoneTableRowNo != undefined) {
1157
1370
  functionConfigObj.tableName = `Zone: ${configObject.tableZones[lpTable.zoneTableRowNo].name}, Execution`;
1158
1371
  }
1159
1372
 
1160
1373
  // Active status of each row; We simply push true or false in loop, same index as table rows (lpTable.table)
1161
1374
  const rowActiveStatus = [];
1162
-
1375
+
1163
1376
  if (this.x.helper.isLikeEmpty(lpTable.table)) {
1164
- if(functionConfigObj.tableMustHaveActiveRows) {
1165
- issues.push('[Config Table \'' + functionConfigObj.tableName + '\'] No rows defined.');
1377
+ if (functionConfigObj.tableMustHaveActiveRows) {
1378
+ issues.push(`[Config Table '${functionConfigObj.tableName}'] No rows defined.`);
1166
1379
  errors++;
1167
1380
  }
1168
1381
  continue;
1169
- }
1170
-
1171
- for (let i = 0; i < lpTable.table.length; i++) {
1382
+ }
1172
1383
 
1173
- if (!lpTable.table[i].active && !configObject.validateDeactivatedRows) continue;
1384
+ for (let i = 0; i < lpTable.table.length; i++) {
1385
+ if (!lpTable.table[i].active && !configObject.validateDeactivatedRows) {
1386
+ continue;
1387
+ }
1174
1388
 
1175
1389
  // Returns all object keys starting with 'check_' as array, like ['check_1','check_2']. Or empty array, if not found.
1176
- const lpCriteriaToCheck = (Object.keys(functionConfigObj).filter(str => str.includes('check_')));
1177
-
1178
- for (const lpCheckKey of lpCriteriaToCheck) {
1390
+ const lpCriteriaToCheck = Object.keys(functionConfigObj).filter(str => str.includes('check_'));
1179
1391
 
1180
- // lpCheckKey = check_1, or check_2, etc.
1392
+ for (const lpCheckKey of lpCriteriaToCheck) {
1393
+ // lpCheckKey = check_1, or check_2, etc.
1181
1394
  // lpFcnConfigCheckObj = like {id: 'triggers', type:'name', deactivateIfError:true, removeForbidden:true }
1182
- const lpFcnConfigCheckObj = functionConfigObj[lpCheckKey];
1395
+ const lpFcnConfigCheckObj = functionConfigObj[lpCheckKey];
1183
1396
 
1184
1397
  // Special for tableTriggerDevices - userState
1185
- const isUserState = ((functionConfigObj.tableId == 'tableTriggerDevices') && lpTable.table[i].userState) ? true : false;
1398
+ const isUserState =
1399
+ functionConfigObj.tableId == 'tableTriggerDevices' && lpTable.table[i].userState
1400
+ ? true
1401
+ : false;
1186
1402
 
1187
1403
  // Config table: the string from config table row, like '0.userdata.0.abc.def', 'true', 'false', 'Play Music', etc.
1188
1404
  let lpConfigString = lpTable.table[i][lpFcnConfigCheckObj.id];
1189
1405
 
1190
1406
  // +++++++ VALIDATION TYPE: a state path like "0_userdata.0.teststate" +++++++
1191
1407
  if (lpFcnConfigCheckObj.type == 'statePath') {
1192
-
1193
1408
  lpConfigString = lpConfigString.trim();
1194
1409
 
1195
- if ( this.x.helper.isLikeEmpty(lpConfigString) && lpFcnConfigCheckObj.optional) {
1410
+ if (this.x.helper.isLikeEmpty(lpConfigString) && lpFcnConfigCheckObj.optional) {
1196
1411
  // Skip if empty state and field is optional
1197
1412
  continue;
1198
1413
  }
1199
1414
 
1200
1415
  // Special treatment for tableTriggerDevices, User States
1201
1416
  if (isUserState) {
1202
- if(!lpConfigString.startsWith(this.namespace + '.userstates.')) {
1203
- lpConfigString = this.namespace + '.userstates.' + lpConfigString;
1417
+ if (!lpConfigString.startsWith(`${this.namespace}.userstates.`)) {
1418
+ lpConfigString = `${this.namespace}.userstates.${lpConfigString}`;
1204
1419
  }
1205
1420
  }
1206
1421
 
1207
1422
  if (!this.x.helper.isStateIdValid(lpConfigString)) {
1208
1423
  // State path is not valid
1209
- issues.push(`[Config Table '${functionConfigObj.tableName}'] ${lpFcnConfigCheckObj.id} - State '${lpConfigString}' is not valid.`);
1424
+ issues.push(
1425
+ `[Config Table '${functionConfigObj.tableName}'] ${lpFcnConfigCheckObj.id} - State '${lpConfigString}' is not valid.`,
1426
+ );
1210
1427
  if (lpFcnConfigCheckObj.deactivateIfError) {
1211
1428
  lpTable.table[i].active = false;
1212
1429
  rowActiveStatus[i] = false;
1213
1430
  }
1214
- errors++;
1431
+ errors++;
1215
1432
  continue;
1216
1433
  }
1217
1434
 
@@ -1219,29 +1436,34 @@ class SmartControl extends utils.Adapter {
1219
1436
  const lpStateObject = await this.getForeignObjectAsync(lpConfigString);
1220
1437
  if (!lpStateObject) {
1221
1438
  // State does not exist
1222
- issues.push(`[Config Table '${functionConfigObj.tableName}'] State '${lpConfigString}' does not exist.`);
1439
+ issues.push(
1440
+ `[Config Table '${functionConfigObj.tableName}'] State '${lpConfigString}' does not exist.`,
1441
+ );
1223
1442
  if (lpFcnConfigCheckObj.deactivateIfError) {
1224
1443
  lpTable.table[i].active = false;
1225
1444
  rowActiveStatus[i] = false;
1226
1445
  }
1227
- errors++;
1446
+ errors++;
1228
1447
  continue;
1229
1448
  }
1230
1449
  }
1231
1450
 
1232
1451
  // We altered lpConfigString, so set to adapter config.
1233
1452
  lpTable.table[i][lpFcnConfigCheckObj.id] = lpConfigString;
1234
-
1235
1453
 
1236
- // +++++++ VALIDATION TYPE: stateValue -- a value to be set to a certain state +++++++
1454
+ // +++++++ VALIDATION TYPE: stateValue -- a value to be set to a certain state +++++++
1237
1455
  } else if (lpFcnConfigCheckObj.type == 'stateValue') {
1238
-
1239
- const lpStatePath = lpTable.table[i][lpFcnConfigCheckObj.stateValueStatePath];
1240
- const lpStateVal = lpConfigString;
1241
- const lpIsOptional = lpFcnConfigCheckObj.optional;
1456
+ const lpStatePath = lpTable.table[i][lpFcnConfigCheckObj.stateValueStatePath];
1457
+ const lpStateVal = lpConfigString;
1458
+ const lpIsOptional = lpFcnConfigCheckObj.optional;
1242
1459
  const lpConfigTableName = functionConfigObj.tableName;
1243
-
1244
- const stateValueResult = await this._asyncVerifyConfig_verifyStateValue(lpStatePath, lpStateVal, lpIsOptional, lpConfigTableName);
1460
+
1461
+ const stateValueResult = await this._asyncVerifyConfig_verifyStateValue(
1462
+ lpStatePath,
1463
+ lpStateVal,
1464
+ lpIsOptional,
1465
+ lpConfigTableName,
1466
+ );
1245
1467
 
1246
1468
  if (stateValueResult.validationFailed) {
1247
1469
  if (lpFcnConfigCheckObj.deactivateIfError) {
@@ -1249,20 +1471,21 @@ class SmartControl extends utils.Adapter {
1249
1471
  rowActiveStatus[i] = false;
1250
1472
  }
1251
1473
  issues.push(stateValueResult.issue);
1252
- errors++;
1474
+ errors++;
1253
1475
  continue;
1254
1476
  } else {
1255
1477
  if ('newStateVal' in stateValueResult) {
1256
- configObject[functionConfigObj.tableId][i][lpFcnConfigCheckObj.id] = stateValueResult.newStateVal;
1478
+ configObject[functionConfigObj.tableId][i][lpFcnConfigCheckObj.id] =
1479
+ stateValueResult.newStateVal;
1257
1480
  }
1258
1481
  }
1259
1482
 
1260
- // +++++++ VALIDATION TYPE: URL +++++++
1483
+ // +++++++ VALIDATION TYPE: URL +++++++
1261
1484
  } else if (lpFcnConfigCheckObj.type == 'url') {
1262
1485
  const urlToCheck = lpTable.table[i][lpFcnConfigCheckObj.id];
1263
1486
 
1264
- if (this.x.helper.isLikeEmpty(urlToCheck) && lpFcnConfigCheckObj.optional ) {
1265
- continue; // Skip if empty and if is optional.
1487
+ if (this.x.helper.isLikeEmpty(urlToCheck) && lpFcnConfigCheckObj.optional) {
1488
+ continue; // Skip if empty and if is optional.
1266
1489
  }
1267
1490
 
1268
1491
  const checkResult = this.x.helper.validateURL(urlToCheck, true, true);
@@ -1271,67 +1494,88 @@ class SmartControl extends utils.Adapter {
1271
1494
  lpTable.table[i].active = false;
1272
1495
  rowActiveStatus[i] = false;
1273
1496
  }
1274
- issues.push(`[Config Table '${functionConfigObj.tableName}'] - URL '${urlToCheck}' is not a valid URL.`);
1497
+ issues.push(
1498
+ `[Config Table '${functionConfigObj.tableName}'] - URL '${urlToCheck}' is not a valid URL.`,
1499
+ );
1275
1500
  errors++;
1276
1501
  continue;
1277
1502
  } else {
1278
1503
  lpTable.table[i][lpFcnConfigCheckObj.id] = checkResult;
1279
- }
1280
-
1281
- // +++++++ VALIDATION TYPE: targetURL Name +++++++
1282
- } else if (lpFcnConfigCheckObj.type == 'targetURLname') {
1504
+ }
1283
1505
 
1284
- const finalStateId = this.namespace + '.targetURLs.' + lpConfigString.trim();
1506
+ // +++++++ VALIDATION TYPE: targetURL Name +++++++
1507
+ } else if (lpFcnConfigCheckObj.type == 'targetURLname') {
1508
+ const finalStateId = `${this.namespace}.targetURLs.${lpConfigString.trim()}`;
1285
1509
 
1286
- if (! this.x.helper.isStateIdValid(finalStateId)) {
1287
- issues.push(`[Config Table ${functionConfigObj.tableName}] Field ${lpFcnConfigCheckObj.id}, content '${lpConfigString}' contains invalid characters.'.`);
1288
- if (lpFcnConfigCheckObj.deactivateIfError) lpTable.table[i].active = false;
1289
- errors++;
1510
+ if (!this.x.helper.isStateIdValid(finalStateId)) {
1511
+ issues.push(
1512
+ `[Config Table ${functionConfigObj.tableName}] Field ${lpFcnConfigCheckObj.id}, content '${lpConfigString}' contains invalid characters.'.`,
1513
+ );
1514
+ if (lpFcnConfigCheckObj.deactivateIfError) {
1515
+ lpTable.table[i].active = false;
1516
+ }
1517
+ errors++;
1290
1518
  continue;
1291
1519
  }
1292
1520
 
1293
1521
  // Set to tableTargetURLs object row, key "stateId"
1294
1522
  lpTable.table[i]['stateId'] = finalStateId;
1295
1523
 
1296
-
1297
- // +++++++ VALIDATION TYPE: a number +++++++
1524
+ // +++++++ VALIDATION TYPE: a number +++++++
1298
1525
  } else if (lpFcnConfigCheckObj.type == 'number') {
1299
-
1300
1526
  const lpNumberToCheck = lpTable.table[i][lpFcnConfigCheckObj.id];
1301
1527
 
1302
- if (this.x.helper.isLikeEmpty(lpNumberToCheck) && lpFcnConfigCheckObj.optional ) {
1303
- // Skip if empty and if is optional.
1528
+ if (this.x.helper.isLikeEmpty(lpNumberToCheck) && lpFcnConfigCheckObj.optional) {
1529
+ // Skip if empty and if is optional.
1304
1530
  continue;
1305
1531
  }
1306
1532
 
1307
- if(! this.x.helper.isNumber(lpNumberToCheck) ) {
1308
- issues.push(`[Config Table ${functionConfigObj.tableName}] Field ${lpFcnConfigCheckObj.id} is expecting a number, but you set '${lpConfigString}'.`);
1309
- if (lpFcnConfigCheckObj.deactivateIfError) lpTable.table[i].active = false;
1310
- errors++;
1533
+ if (!this.x.helper.isNumber(lpNumberToCheck)) {
1534
+ issues.push(
1535
+ `[Config Table ${functionConfigObj.tableName}] Field ${lpFcnConfigCheckObj.id} is expecting a number, but you set '${lpConfigString}'.`,
1536
+ );
1537
+ if (lpFcnConfigCheckObj.deactivateIfError) {
1538
+ lpTable.table[i].active = false;
1539
+ }
1540
+ errors++;
1311
1541
  continue;
1312
- // check for lower limit, if 'numberLowerLimit' set in functionConfigObj object
1313
- } else if (! this.x.helper.isLikeEmpty(lpFcnConfigCheckObj.numberLowerLimit)) {
1314
- if(parseInt(lpNumberToCheck) < lpFcnConfigCheckObj.numberLowerLimit) {
1315
- issues.push('[Config Table \'' + functionConfigObj.tableName + '\'] Number in field "' + lpFcnConfigCheckObj.id + '" is smaller than ' + lpFcnConfigCheckObj.numberLowerLimit + ', which does not make sense.');
1542
+ // check for lower limit, if 'numberLowerLimit' set in functionConfigObj object
1543
+ } else if (!this.x.helper.isLikeEmpty(lpFcnConfigCheckObj.numberLowerLimit)) {
1544
+ if (parseInt(lpNumberToCheck) < lpFcnConfigCheckObj.numberLowerLimit) {
1545
+ issues.push(
1546
+ `[Config Table '${functionConfigObj.tableName}'] Number in field "${
1547
+ lpFcnConfigCheckObj.id
1548
+ }" is smaller than ${
1549
+ lpFcnConfigCheckObj.numberLowerLimit
1550
+ }, which does not make sense.`,
1551
+ );
1316
1552
  if (lpFcnConfigCheckObj.deactivateIfError) {
1317
1553
  lpTable.table[i].active = false;
1318
1554
  }
1319
- errors++;
1555
+ errors++;
1320
1556
  continue;
1321
1557
  }
1322
- // check for upper limit, if 'numberUpperLimit' set in functionConfigObj object
1323
- } else if (! this.x.helper.isLikeEmpty(lpFcnConfigCheckObj.numberUpperLimit)) {
1324
- if(parseInt(lpNumberToCheck) < lpFcnConfigCheckObj.numberUpperLimit) {
1325
- issues.push('[Config Table \'' + functionConfigObj.tableName + '\'] Number in field "' + lpFcnConfigCheckObj.id + '" is greater than ' + lpFcnConfigCheckObj.numberUpperLimit + ', which does not make sense.');
1326
- if (lpFcnConfigCheckObj.deactivateIfError) lpTable.table[i].active = false;
1558
+ // check for upper limit, if 'numberUpperLimit' set in functionConfigObj object
1559
+ } else if (!this.x.helper.isLikeEmpty(lpFcnConfigCheckObj.numberUpperLimit)) {
1560
+ if (parseInt(lpNumberToCheck) < lpFcnConfigCheckObj.numberUpperLimit) {
1561
+ issues.push(
1562
+ `[Config Table '${functionConfigObj.tableName}'] Number in field "${
1563
+ lpFcnConfigCheckObj.id
1564
+ }" is greater than ${
1565
+ lpFcnConfigCheckObj.numberUpperLimit
1566
+ }, which does not make sense.`,
1567
+ );
1568
+ if (lpFcnConfigCheckObj.deactivateIfError) {
1569
+ lpTable.table[i].active = false;
1570
+ }
1327
1571
  errors++;
1328
1572
  continue;
1329
1573
  }
1330
1574
  }
1331
- // +++++++ VALIDATION TYPE: name (which can also be a drop down with multiple values) +++++++
1575
+ // +++++++ VALIDATION TYPE: name (which can also be a drop down with multiple values) +++++++
1332
1576
  } else if (lpFcnConfigCheckObj.type == 'name') {
1333
1577
  let lpToCheck = lpTable.table[i][lpFcnConfigCheckObj.id];
1334
-
1578
+
1335
1579
  // Trim
1336
1580
  if (Array.isArray(lpToCheck)) {
1337
1581
  for (let i = 0; i < lpToCheck.length; i++) {
@@ -1350,270 +1594,329 @@ class SmartControl extends utils.Adapter {
1350
1594
  checkForbiddenArray.push(lpToCheck); // we have a string
1351
1595
  }
1352
1596
  for (let i = 0; i < checkForbiddenArray.length; i++) {
1353
- const forbidden = this.x.helper.forbiddenCharsInStr(checkForbiddenArray[i], this.x.constants.forbiddenStatePaths);
1597
+ const forbidden = this.x.helper.forbiddenCharsInStr(
1598
+ checkForbiddenArray[i],
1599
+ this.x.constants.forbiddenStatePaths,
1600
+ );
1354
1601
  if (forbidden) {
1355
1602
  // We have forbidden state paths
1356
- this.x.helper.logExtendedInfo(`[Config Table '${functionConfigObj.tableName}'] Field value '${checkForbiddenArray[i]}' contains forbidden character(s) '${forbidden}', so we remove from string.`);
1603
+ this.x.helper.logExtendedInfo(
1604
+ `[Config Table '${functionConfigObj.tableName}'] Field value '${checkForbiddenArray[i]}' contains forbidden character(s) '${forbidden}', so we remove from string.`,
1605
+ );
1357
1606
  if (Array.isArray(lpToCheck)) {
1358
- lpToCheck[i] = lpToCheck[i].replace(this.x.constants.forbiddenStatePaths, '');
1607
+ lpToCheck[i] = lpToCheck[i].replace(
1608
+ this.x.constants.forbiddenStatePaths,
1609
+ '',
1610
+ );
1359
1611
  } else {
1360
1612
  lpToCheck = lpToCheck.replace(this.x.constants.forbiddenStatePaths, '');
1361
1613
  }
1362
- }
1614
+ }
1363
1615
  }
1364
1616
  }
1365
1617
 
1366
- if (this.x.helper.isLikeEmpty(lpToCheck) && !lpFcnConfigCheckObj.optional) {
1367
- issues.push('[Config Table \'' + functionConfigObj.tableName + '\'] Field "' + lpFcnConfigCheckObj.id + '" is empty or contains forbidden chars.');
1368
- if (lpFcnConfigCheckObj.deactivateIfError) lpTable.table[i].active = false;
1369
- errors++;
1618
+ if (this.x.helper.isLikeEmpty(lpToCheck) && !lpFcnConfigCheckObj.optional) {
1619
+ issues.push(
1620
+ `[Config Table '${functionConfigObj.tableName}'] Field "${
1621
+ lpFcnConfigCheckObj.id
1622
+ }" is empty or contains forbidden chars.`,
1623
+ );
1624
+ if (lpFcnConfigCheckObj.deactivateIfError) {
1625
+ lpTable.table[i].active = false;
1626
+ }
1627
+ errors++;
1370
1628
  continue;
1371
1629
  }
1372
-
1630
+
1373
1631
  // We altered lpToCheck, so set to adapter config.
1374
1632
  lpTable.table[i][lpFcnConfigCheckObj.id] = lpToCheck;
1375
1633
 
1376
-
1377
- // +++++++ VALIDATION TYPE: time and timeCron +++++++
1378
- // -- We test for both "time" and "timeCron".
1634
+ // +++++++ VALIDATION TYPE: time and timeCron +++++++
1635
+ // -- We test for both "time" and "timeCron".
1379
1636
  } else if (lpFcnConfigCheckObj.type.substring(0, 4) == 'time') {
1380
- const lpToCheck = lpTable.table[i][lpFcnConfigCheckObj.id];
1637
+ // Textfeld, aber .trim() crasht wenn der Wert kein String ist
1638
+ const rawTime = lpTable.table[i][lpFcnConfigCheckObj.id];
1639
+ const lpToCheck = rawTime == null ? '' : String(rawTime);
1381
1640
  let isValidTime = false;
1382
- if (this.x.helper.getTimeInfoFromAstroString(lpToCheck, false) ) {
1641
+ if (this.x.helper.getTimeInfoFromAstroString(lpToCheck, false)) {
1383
1642
  isValidTime = true;
1384
- } else if (lpFcnConfigCheckObj.type == 'timeCron' && this.x.helper.isCronScheduleValid(lpToCheck.trim())) {
1643
+ } else if (
1644
+ lpFcnConfigCheckObj.type == 'timeCron' &&
1645
+ this.x.helper.isCronScheduleValid(lpToCheck)
1646
+ ) {
1385
1647
  isValidTime = true;
1386
1648
  }
1387
1649
  if (!isValidTime) {
1388
- issues.push(`[Config Table '${functionConfigObj.tableName}'] No valid time in field '${lpFcnConfigCheckObj.id}': '${lpConfigString}'`);
1389
- if (lpFcnConfigCheckObj.deactivateIfError) lpTable.table[i].active = false;
1390
- errors++;
1650
+ issues.push(
1651
+ `[Config Table '${functionConfigObj.tableName}'] No valid time in field '${lpFcnConfigCheckObj.id}': '${lpConfigString}'`,
1652
+ );
1653
+ if (lpFcnConfigCheckObj.deactivateIfError) {
1654
+ lpTable.table[i].active = false;
1655
+ }
1656
+ errors++;
1391
1657
  continue;
1392
1658
  }
1393
1659
 
1394
-
1395
- // +++++++ VALIDATION TYPE: overwrite +++++++
1396
- // -- for tableZones -> targetsOverwrite
1660
+ // +++++++ VALIDATION TYPE: overwrite +++++++
1661
+ // -- for tableZones -> targetsOverwrite
1397
1662
  } else if (lpFcnConfigCheckObj.type == 'overwrite') {
1398
-
1399
1663
  // Like: "targetsOverwrite": { "Bath.Light": "true", "Hallway Light": "50"}
1400
- const targetsOverwriteObject = configObject[functionConfigObj.tableId][i][lpFcnConfigCheckObj.id];
1401
- if (this.x.helper.isLikeEmpty(targetsOverwriteObject)) continue; // nothing at this point
1664
+ const targetsOverwriteObject =
1665
+ configObject[functionConfigObj.tableId][i][lpFcnConfigCheckObj.id];
1666
+ if (this.x.helper.isLikeEmpty(targetsOverwriteObject)) {
1667
+ continue;
1668
+ } // nothing at this point
1402
1669
 
1403
1670
  // loop thru the object to get the key name ("property")
1404
1671
  for (const lpProperty in targetsOverwriteObject) {
1405
1672
  const name = lpProperty; // like 'Bath.Light'
1406
1673
  const lpOverwriteVal = targetsOverwriteObject[lpProperty]; // the new state value
1407
- const lpOverwriteObject = this.x.helper.convertStrToJson(lpOverwriteVal, ['val', 'delay']);
1408
-
1674
+ const lpOverwriteObject = this.x.helper.convertStrToJson(lpOverwriteVal, [
1675
+ 'val',
1676
+ 'delay',
1677
+ ]);
1678
+
1409
1679
  // final object
1410
1680
  const finalObj = {};
1411
1681
 
1412
1682
  // Prep state value
1413
- const lpStateVal = (lpOverwriteObject.val) ? lpOverwriteObject.val : null;
1683
+ const lpStateVal = lpOverwriteObject.val ? lpOverwriteObject.val : null;
1414
1684
  if (lpStateVal !== null) {
1415
1685
  const lpConfigTableName = functionConfigObj.tableName;
1416
- const lpStatePath = this.getOptionTableValue('tableTargetDevices', 'name', name, 'onState');
1686
+ const lpStatePath = this.getOptionTableValue(
1687
+ 'tableTargetDevices',
1688
+ 'name',
1689
+ name,
1690
+ 'onState',
1691
+ );
1417
1692
  if (!lpStatePath) {
1418
- continue; // This is actually handled already by verifying table Target Devices, so no error here.
1693
+ continue; // This is actually handled already by verifying table Target Devices, so no error here.
1419
1694
  // throw(`Unexpected Error - Unable to retrieve state path by name '${name}' from tableTargetDevices.`);
1420
- }
1695
+ }
1421
1696
  // Verify
1422
- const stateValueValidationResult = await this._asyncVerifyConfig_verifyStateValue(lpStatePath, lpStateVal, true, lpConfigTableName);
1697
+ const stateValueValidationResult =
1698
+ await this._asyncVerifyConfig_verifyStateValue(
1699
+ lpStatePath,
1700
+ lpStateVal,
1701
+ true,
1702
+ lpConfigTableName,
1703
+ );
1423
1704
  if (stateValueValidationResult.validationFailed) {
1424
- if (lpFcnConfigCheckObj.deactivateIfError) lpTable.table[i].active = false;
1705
+ if (lpFcnConfigCheckObj.deactivateIfError) {
1706
+ lpTable.table[i].active = false;
1707
+ }
1425
1708
  issues.push(stateValueValidationResult.issue);
1426
- errors++;
1709
+ errors++;
1427
1710
  continue;
1428
1711
  } else {
1429
1712
  finalObj.val = stateValueValidationResult.newStateVal;
1430
-
1431
1713
  }
1432
1714
  }
1433
1715
 
1434
1716
  // Prepare delay
1435
- const lpDelay = (lpOverwriteObject.delay) ? lpOverwriteObject.delay : null;
1436
- if (this.x.helper.isNumber(lpDelay) && parseInt(lpDelay) >= 0) { // need also 0 so that user can de-activate
1717
+ const lpDelay = lpOverwriteObject.delay ? lpOverwriteObject.delay : null;
1718
+ if (this.x.helper.isNumber(lpDelay) && parseInt(lpDelay) >= 0) {
1719
+ // need also 0 so that user can de-activate
1437
1720
  finalObj.delay = parseInt(lpDelay);
1438
1721
  }
1439
1722
 
1440
1723
  // Finalize
1441
- if(this.x.helper.isLikeEmpty(finalObj)) {
1442
- this.log.warn(`Verifying Targets Overwrite - failed for '${name}' - no keys found.`);
1724
+ if (this.x.helper.isLikeEmpty(finalObj)) {
1725
+ this.log.warn(
1726
+ `Verifying Targets Overwrite - failed for '${name}' - no keys found.`,
1727
+ );
1443
1728
  errors++;
1444
1729
  continue;
1445
1730
  } else {
1446
- configObject[functionConfigObj.tableId][i][lpFcnConfigCheckObj.id][name] = finalObj;
1731
+ configObject[functionConfigObj.tableId][i][lpFcnConfigCheckObj.id][name] =
1732
+ finalObj;
1447
1733
  }
1448
-
1449
1734
  }
1450
1735
  }
1451
1736
  }
1452
- if(functionConfigObj.isTriggerTable) validTriggerCounter++;
1453
- if(functionConfigObj.isTargetTable) validTargetDevicesCounter++;
1454
-
1737
+ if (functionConfigObj.isTriggerTable) {
1738
+ validTriggerCounter++;
1739
+ }
1740
+ if (functionConfigObj.isTargetTable) {
1741
+ validTargetDevicesCounter++;
1742
+ }
1455
1743
  }
1456
1744
  let activeRowCounter = 0;
1457
1745
  for (const lpRow of lpTable.table) {
1458
- if (lpRow.active) activeRowCounter++;
1746
+ if (lpRow.active) {
1747
+ activeRowCounter++;
1748
+ }
1459
1749
  }
1460
1750
 
1461
- if (activeRowCounter == 0 && functionConfigObj.tableMustHaveActiveRows && !functionConfigObj.isTriggerTable) {
1462
- issues.push(`[Config Table '${functionConfigObj.tableName}'] No active rows defined (certain rows may have been deactivated due to errors, see previous logs for details).`);
1751
+ if (
1752
+ activeRowCounter == 0 &&
1753
+ functionConfigObj.tableMustHaveActiveRows &&
1754
+ !functionConfigObj.isTriggerTable
1755
+ ) {
1756
+ issues.push(
1757
+ `[Config Table '${functionConfigObj.tableName}'] No active rows defined (certain rows may have been deactivated due to errors, see previous logs for details).`,
1758
+ );
1463
1759
  errors++;
1464
- }
1760
+ }
1465
1761
 
1466
1762
  // We altered table variable, so set into config object
1467
1763
  if (!(functionConfigObj.tableId == 'tableZoneExecution')) {
1468
1764
  configObject[functionConfigObj.tableId] = lpTable.table;
1469
1765
  } else {
1470
- // @ts-ignore - Type 'undefined' cannot be used as an index type
1766
+ // @ts-expect-error - Type 'undefined' cannot be used as an index type
1471
1767
  configObject.tableZones[lpTable.zoneTableRowNo].executionJson = JSON.stringify(lpTable.table);
1472
1768
  }
1473
-
1474
1769
  }
1475
-
1476
1770
  }
1477
1771
  if (validTriggerCounter == 0) {
1478
- issues.push(`Tab [3. TRIGGERS] You need to define at least 1 trigger: you either have no triggers defined, or your triggers(s) did not pass the input validation.`);
1479
- errors++;
1772
+ issues.push(
1773
+ `Tab [3. TRIGGERS] You need to define at least 1 trigger: you either have no triggers defined, or your triggers(s) did not pass the input validation.`,
1774
+ );
1775
+ errors++;
1480
1776
  }
1481
1777
  if (validTargetDevicesCounter == 0) {
1482
- issues.push(`Tab '1. TARGET DEVICES': You need to define at least 1 target: you either have no targets defined, or your target(s) did not pass the input validation.`);
1483
- errors++;
1778
+ issues.push(
1779
+ `Tab '1. TARGET DEVICES': You need to define at least 1 target: you either have no targets defined, or your target(s) did not pass the input validation.`,
1780
+ );
1781
+ errors++;
1484
1782
  }
1485
1783
 
1486
-
1487
-
1488
1784
  // SECOND: Certain table values must be unique.
1489
1785
  // TODO: Add to constants.js
1490
1786
  const uniqueCheckObjects = [
1491
1787
  // name: for logging only, column: the table to check, rows: the adapter config table rows
1492
- // @ts-ignore -> https://github.com/microsoft/TypeScript/issues/36769
1493
- { name:'Trigger Tables: Names', column:'name', rows:configObject.tableTriggerMotion.concat(configObject.tableTriggerDevices, configObject.tableTriggerTimes) },
1494
- { name:'Target device table: Names', column:'name', rows:configObject.tableTargetDevices },
1495
- { name:'Zones table: Names', column:'name', rows:configObject.tableZones },
1496
- { name:'Conditions table: Names', column:'name', rows:configObject.tableConditions },
1788
+ // @ts-expect-error -> https://github.com/microsoft/TypeScript/issues/36769
1789
+ {
1790
+ name: 'Trigger Tables: Names',
1791
+ column: 'name',
1792
+ rows: configObject.tableTriggerMotion.concat(
1793
+ configObject.tableTriggerDevices,
1794
+ configObject.tableTriggerTimes,
1795
+ ),
1796
+ },
1797
+ { name: 'Target device table: Names', column: 'name', rows: configObject.tableTargetDevices },
1798
+ { name: 'Zones table: Names', column: 'name', rows: configObject.tableZones },
1799
+ { name: 'Conditions table: Names', column: 'name', rows: configObject.tableConditions },
1497
1800
  // { name:'Trigger Tables Motion/Other: State Paths', column:'stateId', rows:configObject.tableTriggerMotion.concat(configObject.tableTriggerDevices) },
1498
1801
  ];
1499
1802
  for (const lpCheckObj of uniqueCheckObjects) {
1500
1803
  if (!this.x.helper.isLikeEmpty(lpCheckObj.rows)) {
1501
1804
  const allValues = [];
1502
1805
  for (const lpRow of lpCheckObj.rows) {
1503
- if(lpRow.active) {
1806
+ if (lpRow.active) {
1504
1807
  allValues.push(lpRow[lpCheckObj.column]);
1505
1808
  }
1506
1809
  }
1507
- if ( !this.x.helper.isArrayUnique(allValues) ) {
1508
- issues.push(`${lpCheckObj.name} must be unique. You cannot use same string more than once here.`);
1810
+ if (!this.x.helper.isArrayUnique(allValues)) {
1811
+ issues.push(
1812
+ `${lpCheckObj.name} must be unique. You cannot use same string more than once here.`,
1813
+ );
1509
1814
  errors++;
1510
1815
  }
1511
1816
  }
1512
1817
  }
1513
1818
 
1514
-
1515
1819
  // FINALIZE
1516
1820
  if (errors == 0) {
1517
- return {passed:true, obj:configObject, issues:[]};
1518
- } else {
1519
- return {passed:false, obj:configObject, issues:this.x.helper.uniqueArray(issues)};
1821
+ return { passed: true, obj: configObject, issues: [] };
1520
1822
  }
1521
-
1823
+ return { passed: false, obj: configObject, issues: this.x.helper.uniqueArray(issues) };
1522
1824
  } catch (error) {
1523
1825
  this.x.helper.dumpError('[asyncVerifyConfig()]', error);
1524
- return {passed:false, obj:configObject, issues:[`Error in [asyncVerifyConfig()]: ${error}`]};
1826
+ return { passed: false, obj: configObject, issues: [`Error in [asyncVerifyConfig()]: ${error}`] };
1525
1827
  }
1526
1828
  }
1527
1829
 
1528
-
1529
1830
  /**
1530
1831
  * Verifies a state value
1531
- *
1832
+ *
1532
1833
  * @param {string} statePath
1533
1834
  * @param {*} stateVal
1534
- * @param {boolean} isOptional
1835
+ * @param {boolean} isOptional
1535
1836
  * @param {string} configTableName -- name of config table, for log only
1536
- * @return {Promise<object>} {validationFailed:false, newStateVal:'xyz', issue:''}
1837
+ * @returns {Promise<object>} {validationFailed:false, newStateVal:'xyz', issue:''}
1537
1838
  */
1538
1839
  async _asyncVerifyConfig_verifyStateValue(statePath, stateVal, isOptional, configTableName) {
1539
-
1540
1840
  try {
1841
+ // Boolean already from a previous save – not a string
1842
+ if (typeof stateVal !== 'boolean') {
1843
+ if (stateVal == null) {
1844
+ stateVal = '';
1845
+ } else {
1846
+ // Remove any brackets at beginning and end
1847
+ stateVal = stateVal.toString().replace(/^(\[|"|'|`|´)([\s\S]*)(]|"|'|`|´)$/, '$2');
1848
+ stateVal = stateVal.trim();
1849
+ }
1850
+ }
1541
1851
 
1542
- // Remove any brackets at beginning and end
1543
- stateVal = stateVal.toString().replace(/^(\[|"|'|`|´)([\s\S]*)(]|"|'|`|´)$/, '$2');
1544
-
1545
- // Trim again
1546
- stateVal = stateVal.trim();
1547
-
1548
- if ( this.x.helper.isLikeEmpty(statePath.trim()) || (this.x.helper.isLikeEmpty(stateVal) && isOptional) ) {
1549
- // Skip if empty and if is optional.
1550
- // We also check if the state path is empty.
1551
- return {validationFailed:false, newStateVal:''};
1852
+ if (this.x.helper.isLikeEmpty(statePath.trim()) || (this.x.helper.isLikeEmpty(stateVal) && isOptional)) {
1853
+ // Skip if empty and if is optional.
1854
+ // We also check if the state path is empty.
1855
+ return { validationFailed: false, newStateVal: '' };
1552
1856
  }
1553
1857
 
1554
1858
  const lpStateObject = await this.getForeignObjectAsync(statePath);
1555
-
1859
+
1556
1860
  if (!lpStateObject) {
1557
1861
  // State does not exist
1558
- return {validationFailed:true, issue:`[Config Table '${configTableName}'] State '${statePath}' does not exist.`};
1559
- } else {
1560
- // State exists
1561
- // Verify State Type (like boolean, switch, number)
1562
- const stateType = lpStateObject.common.type;
1563
-
1564
- if (stateType == 'boolean' || stateType == 'switch') {
1565
- if (stateVal != 'true' && stateVal != 'false') {
1566
- return {validationFailed:true, issue:`[Config Table '${configTableName}'] State '${statePath}' is expecting boolean (true/false), but you set '${stateVal}'.`};
1567
- } else {
1568
- if (stateVal == 'true') stateVal = true;
1569
- if (stateVal == 'false') stateVal = false;
1570
- return {validationFailed:false, newStateVal:stateVal};
1571
- }
1572
- } else if (stateType == 'number') {
1573
- // We allow comparators '<', '>=' etc.
1574
- const isComparator = (/^(>=|<=|>|<|!=|<>)\s?(\d{1,})$/.test(stateVal.trim()));
1575
- if (isComparator) {
1576
- return {validationFailed:false, newStateVal:stateVal};
1577
- } else if (this.x.helper.isNumber(stateVal)) {
1578
- return {validationFailed:false, newStateVal:parseFloat(stateVal)};
1579
- } else {
1580
- return {validationFailed:true, issue:`[Config Table ${configTableName}] State ${statePath} is expecting a number, but you set '${stateVal}'.`};
1581
- }
1582
- } else if (this.x.helper.isLikeEmpty(stateVal)) {
1583
- // Let's convert an "like empty" value to an empty string, just to make sure....
1584
- return {validationFailed:false, newStateVal:''};
1585
- } else {
1586
- // Nothing to do at this point; return
1587
- return {validationFailed:false, newStateVal:stateVal};
1862
+ return {
1863
+ validationFailed: true,
1864
+ issue: `[Config Table '${configTableName}'] State '${statePath}' does not exist.`,
1865
+ };
1866
+ }
1867
+ // State exists
1868
+ // Verify State Type (like boolean, switch, number)
1869
+ const stateType = lpStateObject.common.type;
1870
+
1871
+ if (stateType == 'boolean' || stateType == 'switch') {
1872
+ const parsed = this.x.helper.parseBooleanStateVal(stateVal);
1873
+ if (parsed.ok) {
1874
+ return { validationFailed: false, newStateVal: parsed.value };
1588
1875
  }
1589
- }
1876
+ return {
1877
+ validationFailed: true,
1878
+ issue: `[Config Table '${configTableName}'] State '${statePath}' is boolean. Enter true or false in the value column (comparison value); you set '${stateVal}'.`,
1879
+ };
1880
+ } else if (stateType == 'number') {
1881
+ // We allow comparators '<', '>=' etc. including negatives and decimals (#164)
1882
+ if (this.x.helper.parseNumComparator(stateVal).isComparator) {
1883
+ return { validationFailed: false, newStateVal: stateVal };
1884
+ } else if (this.x.helper.isNumber(stateVal)) {
1885
+ return { validationFailed: false, newStateVal: parseFloat(stateVal) };
1886
+ }
1887
+ return {
1888
+ validationFailed: true,
1889
+ issue: `[Config Table ${configTableName}] State ${statePath} is expecting a number, but you set '${stateVal}'.`,
1890
+ };
1891
+ } else if (this.x.helper.isLikeEmpty(stateVal)) {
1892
+ // Let's convert an "like empty" value to an empty string, just to make sure....
1893
+ return { validationFailed: false, newStateVal: '' };
1894
+ }
1895
+ // Nothing to do at this point; return
1896
+ return { validationFailed: false, newStateVal: stateVal };
1590
1897
  } catch (error) {
1591
- return {validationFailed:true, issue:this.x.helper.dumpError('[verifyStateValue()]', error, true)};
1898
+ return { validationFailed: true, issue: this.x.helper.dumpError('[verifyStateValue()]', error, true) };
1592
1899
  }
1593
-
1594
1900
  }
1595
1901
 
1596
-
1597
-
1598
1902
  /**
1599
1903
  * Retrieves a value of an admin option table
1600
- *
1904
+ *
1601
1905
  * Call example: const res = this.getOptionTableValue('tableTargetDevices', 'name', 'Bathroom Light', 'offState');
1602
- *
1906
+ *
1603
1907
  * @param {string} tableId The id of the table, like 'tableTargetDevices'
1604
1908
  * @param {string} identifierId The column id of the identifier, like 'name'
1605
1909
  * @param {string} identifierName Like 'Bathroom Light'
1606
1910
  * @param {string} resultId The column id of the value we need, like 'offState'
1607
- * @return {*} The value, or undefined if nothing found.
1911
+ * @returns {*} The value, or undefined if nothing found.
1608
1912
  */
1609
1913
  getOptionTableValue(tableId, identifierId, identifierName, resultId) {
1610
1914
  for (const tableRow of this.config[tableId]) {
1611
1915
  if (tableRow.active) {
1612
1916
  if (tableRow[identifierId] == identifierName) {
1613
1917
  return tableRow[resultId];
1614
- } else {
1615
- continue; // no hit
1616
1918
  }
1919
+ continue; // no hit
1617
1920
  } else {
1618
1921
  continue;
1619
1922
  }
@@ -1625,15 +1928,14 @@ class SmartControl extends utils.Adapter {
1625
1928
  * For tableTargetEnums
1626
1929
  * 1. Sets result in adapter config: 'adapter.config._tableTargetDevicesEnums'
1627
1930
  * 2. Update tableZones, field 'targets', e.g. 'Enum.Beleuchtung' --> 'Enum.Beleuchtung_enum-1', 'Enum.Beleuchtung_enum-2', etc.
1628
- * @return {Promise<boolean>} - true if successful, false if not
1931
+ *
1932
+ * @returns {Promise<boolean>} - true if successful, false if not
1629
1933
  */
1630
1934
  async _asyncConvertEnumTargetsToTargetDevices() {
1631
-
1632
1935
  try {
1633
-
1634
1936
  const targetDevicesResult = []; // Table row objects to be added to this.config.tableTargetDevices
1635
- const zoneTargetsResult = {}; // Object with 'old' names as keys, and new names as values, e.g.: {'Windows': ['Windows_enum-1', 'Windows_enum-2'], 'Lights' : ['Lights_enum-1', 'Lights_enum-2', 'Lights_enum-3']}
1636
-
1937
+ const zoneTargetsResult = {}; // Object with 'old' names as keys, and new names as values, e.g.: {'Windows': ['Windows_enum-1', 'Windows_enum-2'], 'Lights' : ['Lights_enum-1', 'Lights_enum-2', 'Lights_enum-3']}
1938
+
1637
1939
  /**
1638
1940
  * Get room and function enumerations (for tableTargetEnums)
1639
1941
  */
@@ -1658,22 +1960,25 @@ class SmartControl extends utils.Adapter {
1658
1960
  }
1659
1961
  enumRoomNamesAndIds = this.x.helper.enumsGetNamesAndIds(enumRooms, true); // Option allLanguages=true
1660
1962
  enumFuncNamesAndIds = this.x.helper.enumsGetNamesAndIds(enumFuncs, true); // Option allLanguages=true
1661
-
1662
- if(this.x.helper.isLikeEmpty(this.config.tableTargetEnums)) {
1963
+
1964
+ if (this.x.helper.isLikeEmpty(this.config.tableTargetEnums)) {
1663
1965
  return true; // Table tableTargetEnums is empty, which is not an error
1664
1966
  }
1665
1967
  for (const lpEnumRow of this.config.tableTargetEnums) {
1666
-
1667
- if (!lpEnumRow.active) continue;
1968
+ if (!lpEnumRow.active) {
1969
+ continue;
1970
+ }
1668
1971
 
1669
1972
  const lpRowName = lpEnumRow.name;
1670
1973
  const lpEnumFuncName = lpEnumRow.enumId;
1671
1974
  const lpEnumRooms = lpEnumRow.enumRooms;
1672
1975
 
1673
- if (this.x.helper.isLikeEmpty(lpEnumFuncName) || !lpEnumFuncName) continue;
1976
+ if (this.x.helper.isLikeEmpty(lpEnumFuncName) || !lpEnumFuncName) {
1977
+ continue;
1978
+ }
1674
1979
 
1675
1980
  let finalStates = [];
1676
-
1981
+
1677
1982
  /**
1678
1983
  * Get states
1679
1984
  */
@@ -1684,9 +1989,8 @@ class SmartControl extends utils.Adapter {
1684
1989
  errorCounter++;
1685
1990
  continue;
1686
1991
  }
1687
-
1688
- for (const lpStatePath of targetStates) {
1689
1992
 
1993
+ for (const lpStatePath of targetStates) {
1690
1994
  // Check if room is matching
1691
1995
  if (enumRooms && enumRoomNamesAndIds && !this.x.helper.isLikeEmpty(lpEnumRooms)) {
1692
1996
  for (const lpEnumRoomName of lpEnumRooms) {
@@ -1702,15 +2006,15 @@ class SmartControl extends utils.Adapter {
1702
2006
  // No room defined, so we add all
1703
2007
  finalStates = targetStates;
1704
2008
  }
1705
-
1706
2009
  }
1707
2010
  if (this.x.helper.isLikeEmpty(finalStates)) {
1708
- this.log.warn(`Targets - Enum '${lpRowName}', function '${lpEnumFuncName}', rooms '${lpEnumRooms.toString()}': no states found.`);
2011
+ this.log.warn(
2012
+ `Targets - Enum '${lpRowName}', function '${lpEnumFuncName}', rooms '${lpEnumRooms.toString()}': no states found.`,
2013
+ );
1709
2014
  errorCounter++;
1710
2015
  continue;
1711
2016
  }
1712
2017
 
1713
-
1714
2018
  /** Build table row for tableTargetDevices and object entry for tableZone -> Target Device names */
1715
2019
  let counter = 0;
1716
2020
  for (const statePath of finalStates) {
@@ -1719,7 +2023,7 @@ class SmartControl extends utils.Adapter {
1719
2023
  const rowObj = {};
1720
2024
  rowObj.active = true; // we checked this before
1721
2025
  rowObj.isEnum = true; // additionally added
1722
- rowObj.name = lpRowName + '_enum-' + counter;
2026
+ rowObj.name = `${lpRowName}_enum-${counter}`;
1723
2027
  rowObj.onState = statePath;
1724
2028
  rowObj.onValue = lpEnumRow.onValue;
1725
2029
  rowObj.offValue = lpEnumRow.offValue;
@@ -1736,18 +2040,14 @@ class SmartControl extends utils.Adapter {
1736
2040
  // We already have an entry, so we add to array
1737
2041
  zoneTargetsResult[lpRowName].push(rowObj.name);
1738
2042
  }
1739
-
1740
-
1741
- }
1742
-
2043
+ }
1743
2044
  }
1744
2045
 
1745
- // @ts-ignore - Property '_tableTargetDevicesEnums' does not exist on type 'AdapterConfig'
1746
- if (errorCounter == 0 && (this.x.helper.isLikeEmpty(targetDevicesResult))) {
2046
+ // @ts-expect-error - Property '_tableTargetDevicesEnums' does not exist on type 'AdapterConfig'
2047
+ if (errorCounter == 0 && this.x.helper.isLikeEmpty(targetDevicesResult)) {
1747
2048
  // No issue here, we just have an empty table
1748
2049
  return true;
1749
- } else if (errorCounter == 0 && (!this.x.helper.isLikeEmpty(targetDevicesResult))) {
1750
-
2050
+ } else if (errorCounter == 0 && !this.x.helper.isLikeEmpty(targetDevicesResult)) {
1751
2051
  /**
1752
2052
  * Successfully completed
1753
2053
  */
@@ -1759,27 +2059,27 @@ class SmartControl extends utils.Adapter {
1759
2059
  let zoneRowIdx = -1;
1760
2060
  for (const lpZoneRow of this.config.tableZones) {
1761
2061
  zoneRowIdx++;
1762
- if (!lpZoneRow.active) continue;
2062
+ if (!lpZoneRow.active) {
2063
+ continue;
2064
+ }
1763
2065
  for (const lpKey in zoneTargetsResult) {
1764
2066
  const index = lpZoneRow.targets.indexOf(lpKey);
1765
2067
  if (index !== -1) {
1766
2068
  lpZoneRow.targets.splice(index, 1); // remove array element
1767
- this.config.tableZones[zoneRowIdx].targets = lpZoneRow.targets.concat(zoneTargetsResult[lpKey]);
2069
+ this.config.tableZones[zoneRowIdx].targets = lpZoneRow.targets.concat(
2070
+ zoneTargetsResult[lpKey],
2071
+ );
1768
2072
  }
1769
2073
  }
1770
2074
  }
1771
2075
  return true;
1772
-
1773
- } else {
1774
- // warn msg should already been logged
1775
- return false;
1776
2076
  }
1777
-
2077
+ // warn msg should already been logged
2078
+ return false;
1778
2079
  } catch (error) {
1779
2080
  this.x.helper.dumpError('[_asyncConvertEnumTargetsToTargetDevices]', error);
1780
2081
  return false;
1781
- }
1782
-
2082
+ }
1783
2083
  }
1784
2084
 
1785
2085
  /**
@@ -1787,18 +2087,17 @@ class SmartControl extends utils.Adapter {
1787
2087
  * Set to tableTargetDevices
1788
2088
  */
1789
2089
  _setTargetsURLsToTargetDevicesTable() {
1790
-
1791
2090
  try {
1792
-
1793
2091
  const targetDevicesResult = []; // Table row objects to be added to this.config.tableTargetDevices
1794
2092
 
1795
- if(this.x.helper.isLikeEmpty(this.config.tableTargetURLs)) {
2093
+ if (this.x.helper.isLikeEmpty(this.config.tableTargetURLs)) {
1796
2094
  return; // Table is empty
1797
2095
  }
1798
2096
 
1799
2097
  for (const lpURLRow of this.config.tableTargetURLs) {
1800
-
1801
- if (!lpURLRow.active) continue;
2098
+ if (!lpURLRow.active) {
2099
+ continue;
2100
+ }
1802
2101
 
1803
2102
  /** Build table row for tableTargetDevices */
1804
2103
  const rowObj = {};
@@ -1807,16 +2106,16 @@ class SmartControl extends utils.Adapter {
1807
2106
  rowObj.noTargetOnCheck = true;
1808
2107
  rowObj.noTargetOffCheck = true;
1809
2108
  rowObj.isTargetURL = true; // special property to identify tableTargetURLs items
1810
- rowObj.onState = lpURLRow.stateId + '.call_on';
2109
+ rowObj.onState = `${lpURLRow.stateId}.call_on`;
1811
2110
  rowObj.onValue = true;
1812
2111
 
1813
2112
  if (lpURLRow.urlOff && !this.x.helper.isLikeEmpty(lpURLRow.urlOff)) {
1814
2113
  // URL for switching off is available
1815
- rowObj.offState = lpURLRow.stateId + '.call_off';
2114
+ rowObj.offState = `${lpURLRow.stateId}.call_off`;
1816
2115
  rowObj.offValue = true;
1817
2116
  } else {
1818
2117
  // No URL for switching off"
1819
- rowObj.offState = lpURLRow.stateId + '.call_on'; // let's add this, but could be anything
2118
+ rowObj.offState = `${lpURLRow.stateId}.call_on`; // let's add this, but could be anything
1820
2119
  rowObj.offValue = false; // NOTE: false will not trigger anything per _asyncOnStateChange() since it will only recognize "true"
1821
2120
  }
1822
2121
 
@@ -1826,34 +2125,33 @@ class SmartControl extends utils.Adapter {
1826
2125
  if (this.x.helper.isLikeEmpty(targetDevicesResult)) {
1827
2126
  return;
1828
2127
  }
1829
-
2128
+
1830
2129
  // Add to target devices
1831
- // @ts-ignore No overload matches this call -> https://github.com/microsoft/TypeScript/issues/36769
2130
+ // @ts-expect-error No overload matches this call -> https://github.com/microsoft/TypeScript/issues/36769
1832
2131
  this.config.tableTargetDevices = this.config.tableTargetDevices.concat(targetDevicesResult);
1833
2132
  return true;
1834
-
1835
2133
  } catch (error) {
1836
2134
  this.x.helper.dumpError('[_asyncConvertEnumTargetsToTargetDevices]', error);
1837
2135
  return false;
1838
- }
1839
-
2136
+ }
1840
2137
  }
1841
2138
 
1842
2139
  /**
1843
2140
  * Called once a trigger was activated (i.e. a motion or other trigger state changed)
1844
2141
  * For the given state, we retrieve all triggers and do some verifications.
2142
+ *
1845
2143
  * @param {string} statePath State Path of the trigger
1846
2144
  * @param {ioBroker.State|null|undefined} stateObject State object
1847
2145
  * @fires trigger.asyncSetTargetDevices() Called if all verifications were successful.
1848
2146
  */
1849
- async asyncDoOnTriggerActivated (statePath, stateObject) {
1850
-
2147
+ async asyncDoOnTriggerActivated(statePath, stateObject) {
1851
2148
  try {
1852
-
1853
- if (!stateObject || !statePath || stateObject.val == null) return;
2149
+ if (!stateObject || !statePath || stateObject.val == null) {
2150
+ return;
2151
+ }
1854
2152
 
1855
2153
  // Get all trigger names which contain the statePath (per asyncVerifyConfig(), names are unique)
1856
- // @ts-ignore No overload matches this call -> https://github.com/microsoft/TypeScript/issues/36769
2154
+ // @ts-expect-error No overload matches this call -> https://github.com/microsoft/TypeScript/issues/36769
1857
2155
  const allTriggerRows = this.config.tableTriggerMotion.concat(this.config.tableTriggerDevices);
1858
2156
  const triggerNames = [];
1859
2157
  for (const lpTriggerRow of allTriggerRows) {
@@ -1862,16 +2160,17 @@ class SmartControl extends utils.Adapter {
1862
2160
  }
1863
2161
  }
1864
2162
  if (triggerNames.length == 0) {
1865
- throw(`No trigger found for '${statePath}'`);
2163
+ throw `No trigger found for '${statePath}'`;
1866
2164
  }
1867
2165
 
1868
2166
  // Loop through all trigger names
1869
2167
  // We may have 2 trigger class instances for "motion linked devices"
1870
2168
  for (const lpTriggerName of triggerNames) {
1871
-
1872
2169
  const triggers = [];
1873
2170
  if (!this.x.triggers[lpTriggerName]) {
1874
- this.log.debug(`Trigger '${lpTriggerName}': not not found for ${statePath}. This is likely caused by user (invalid configuration).`);
2171
+ this.log.debug(
2172
+ `Trigger '${lpTriggerName}': not not found for ${statePath}. This is likely caused by user (invalid configuration).`,
2173
+ );
1875
2174
  continue;
1876
2175
  }
1877
2176
  this.x.triggers[lpTriggerName].mimicMotion = false;
@@ -1889,36 +2188,41 @@ class SmartControl extends utils.Adapter {
1889
2188
  }
1890
2189
  }
1891
2190
  }
1892
- }
2191
+ }
1893
2192
 
1894
2193
  // Finally, go through both triggers
1895
2194
  for (const trigger of triggers) {
1896
-
1897
2195
  /**
1898
2196
  * If motion sensor changed to false (no motion).
1899
2197
  * In this case, we will not switch any target devices, but set a timer to turn targets off.
1900
2198
  */
1901
- if (!trigger.mimicMotion && trigger.triggerIsMotion && stateObject.val===false && !this.x.helper.isLikeEmpty(trigger.motionDuration) && (parseInt(trigger.motionDuration) > 0)) {
1902
-
2199
+ if (
2200
+ !trigger.mimicMotion &&
2201
+ trigger.triggerIsMotion &&
2202
+ stateObject.val === false &&
2203
+ !this.x.helper.isLikeEmpty(trigger.motionDuration) &&
2204
+ parseInt(trigger.motionDuration) > 0
2205
+ ) {
1903
2206
  // We start timer to switch devices off
1904
2207
  if (!trigger.zoneNames || !trigger.zoneTargetNames) {
1905
- this.x.helper.logExtendedInfo(`Motion sensor ${lpTriggerName} changed to false, but no zone name or zone target names found which were switched on before.`);
2208
+ this.x.helper.logExtendedInfo(
2209
+ `Motion sensor ${lpTriggerName} changed to false, but no zone name or zone target names found which were switched on before.`,
2210
+ );
1906
2211
  } else {
1907
2212
  for (const lpZoneName of trigger.zoneNames) {
1908
2213
  trigger.asyncSetZoneTimer_motion(lpZoneName);
1909
2214
  }
1910
2215
  }
1911
2216
  continue; // Motion sensor to false - so we can go out here.
1912
-
1913
2217
  }
1914
2218
 
1915
2219
  /**
1916
2220
  * Motion sensor changed to true. We also handle motion linked trigger here
1917
2221
  * Clear motion timer
1918
2222
  */
1919
- if (trigger.mimicMotion || (trigger.triggerIsMotion && stateObject.val===true)) {
1920
- clearTimeout(trigger.motionTimer);
1921
- trigger.motionTimer = null;
2223
+ if (trigger.mimicMotion || (trigger.triggerIsMotion && stateObject.val === true)) {
2224
+ // Zonen-Timer löschen, nicht nur den eigenen Melder: sonst läuft der Timer des anderen BWM weiter (#147)
2225
+ this._clearMotionOffTimersForTrigger(trigger.triggerName);
1922
2226
  }
1923
2227
 
1924
2228
  /**
@@ -1926,68 +2230,82 @@ class SmartControl extends utils.Adapter {
1926
2230
  */
1927
2231
  // Check for >=, <=, >, <, !=/<> and number, so like '>= 3', '<7'
1928
2232
  let comparatorSuccess = false;
1929
- if (trigger.triggerTableId == 'tableTriggerDevices' && (typeof trigger.triggerStateVal == 'string') ) {
2233
+ if (trigger.triggerTableId == 'tableTriggerDevices' && typeof trigger.triggerStateVal == 'string') {
1930
2234
  const res = this.x.helper.isNumComparatorMatching(stateObject.val, trigger.triggerStateVal);
1931
2235
  if (res.isComparator && res.result) {
1932
2236
  comparatorSuccess = true;
1933
2237
  } else if (res.isComparator && !res.result) {
1934
- this.log.debug(`Trigger '${lpTriggerName}' activated, but not meeting 'comparator' condition (trigger state val: '${trigger.triggerStateVal}'), therefore, we disregard the activation.`);
2238
+ this.log.debug(
2239
+ `Trigger '${lpTriggerName}' activated, but not meeting 'comparator' condition (trigger state val: '${trigger.triggerStateVal}'), therefore, we disregard the activation.`,
2240
+ );
1935
2241
  continue; // We go out since we have a comparator, but not matching
1936
2242
  }
1937
-
1938
2243
  }
1939
2244
  // Compare state value with config
1940
- if (!comparatorSuccess && trigger.triggerStateVal != undefined && trigger.triggerStateVal != stateObject.val ) {
1941
- this.log.debug(`Trigger '${lpTriggerName}' activated, but not meeting conditions (triggerStateVal '${trigger.triggerStateVal}' != stateObject.val '${stateObject.val}' ), therefore, we disregard the activation.`);
2245
+ if (
2246
+ !comparatorSuccess &&
2247
+ trigger.triggerStateVal != undefined &&
2248
+ trigger.triggerStateVal != stateObject.val
2249
+ ) {
2250
+ this.log.debug(
2251
+ `Trigger '${lpTriggerName}' activated, but not meeting conditions (triggerStateVal '${trigger.triggerStateVal}' != stateObject.val '${stateObject.val}' ), therefore, we disregard the activation.`,
2252
+ );
1942
2253
  continue; // Go out since no match
1943
2254
  }
1944
-
2255
+
1945
2256
  /**
1946
2257
  * Do not switch more often than x seconds
1947
2258
  */
1948
2259
  let threshold = parseInt(this.config.limitTriggerInterval); // in seconds
1949
- if(!threshold || !this.x.helper.isNumber(threshold) || threshold < 1) threshold = 1;
2260
+ if (!threshold || !this.x.helper.isNumber(threshold) || threshold < 1) {
2261
+ threshold = 1;
2262
+ }
1950
2263
  const formerTs = this.x.onStateChangeTriggers[trigger.triggerName];
1951
2264
  const currTs = Date.now();
1952
2265
  this.x.onStateChangeTriggers[trigger.triggerName] = currTs;
1953
- if (formerTs && ( (formerTs + (threshold*1000)) > currTs)) {
1954
- if (trigger.triggerIsMotion && stateObject.val===true && this.getOptionTableValue('tableTriggerMotion', 'name', trigger.triggerName, 'ignoreMotionOn')) {
2266
+ if (formerTs && formerTs + threshold * 1000 > currTs) {
2267
+ if (
2268
+ trigger.triggerIsMotion &&
2269
+ stateObject.val === true &&
2270
+ this.getOptionTableValue(
2271
+ 'tableTriggerMotion',
2272
+ 'name',
2273
+ trigger.triggerName,
2274
+ 'ignoreMotionOn',
2275
+ )
2276
+ ) {
1955
2277
  // Do switch anyway, because of motionLinkedTrigger may have triggered right before.
1956
2278
  // Scenario: Wall switch switched on, and motion is detected like 0.3s after. E.g. Xiaomi Aquara detect motion just every 2min.
1957
2279
  } else {
1958
2280
  // do not switch
1959
- this.x.helper.logExtendedInfo(`Trigger '${trigger.triggerName}' was already activated ${Math.round(((currTs-formerTs) / 1000) * 100) / 100} seconds ago and is ignored. Must be at least ${threshold} seconds.`);
2281
+ this.x.helper.logExtendedInfo(
2282
+ `Trigger '${trigger.triggerName}' was already activated ${Math.round(((currTs - formerTs) / 1000) * 100) / 100} seconds ago and is ignored. Must be at least ${threshold} seconds.`,
2283
+ );
1960
2284
  continue;
1961
2285
  }
1962
2286
  }
1963
-
2287
+
1964
2288
  /**
1965
2289
  * All conditions passed -> set all target devices
1966
2290
  */
1967
2291
  trigger.asyncSetTargetDevices();
1968
-
1969
-
1970
2292
  }
1971
-
1972
2293
  }
1973
-
1974
2294
  } catch (error) {
1975
2295
  this.x.helper.dumpError('[asyncDoOnTriggerActivated]', error);
1976
2296
  return false;
1977
2297
  }
1978
-
1979
2298
  }
1980
-
1981
2299
  }
1982
2300
 
1983
- // @ts-ignore parent is a valid property on module
2301
+ // @ts-expect-error parent is a valid property on module
1984
2302
  if (module.parent) {
1985
2303
  // Export the constructor in compact mode
1986
2304
  /**
1987
- * @param {Partial<utils.AdapterOptions>} [options={}]
2305
+ * @param {Partial<utils.AdapterOptions>} [options]
1988
2306
  */
1989
- module.exports = (options) => new SmartControl(options);
2307
+ module.exports = options => new SmartControl(options);
1990
2308
  } else {
1991
2309
  // otherwise start the instance directly
1992
2310
  new SmartControl();
1993
- }
2311
+ }