iobroker.smartcontrol 1.3.2 → 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.
Files changed (42) hide show
  1. package/LICENSE +2 -0
  2. package/README.md +57 -297
  3. package/admin/css/LICENSE-github-markdown-css.txt +24 -0
  4. package/admin/css/github-markdown-dark.min.css +8 -0
  5. package/admin/css/github-markdown.min.css +8 -0
  6. package/admin/doc-md/table-trigger-motion_de.md +1 -1
  7. package/admin/doc-md/table-trigger-motion_en.md +1 -1
  8. package/admin/doc-md/table-trigger-times_de.md +1 -1
  9. package/admin/doc-md/table-trigger-times_en.md +1 -1
  10. package/admin/i18n/de/translations.json +109 -0
  11. package/admin/i18n/en/translations.json +109 -0
  12. package/admin/i18n/es/translations.json +109 -0
  13. package/admin/i18n/fr/translations.json +109 -0
  14. package/admin/i18n/it/translations.json +109 -0
  15. package/admin/i18n/nl/translations.json +109 -0
  16. package/admin/i18n/pl/translations.json +109 -0
  17. package/admin/i18n/pt/translations.json +109 -0
  18. package/admin/i18n/ru/translations.json +109 -0
  19. package/admin/i18n/zh-cn/translations.json +109 -0
  20. package/admin/index_m.js +207 -3
  21. package/admin/style.css +76 -8
  22. package/admin/tsconfig.json +45 -0
  23. package/io-package.json +44 -31
  24. package/lib/boolean-value.js +30 -0
  25. package/lib/constants.js +299 -65
  26. package/lib/cron-schedule.js +59 -0
  27. package/lib/helper.js +380 -373
  28. package/lib/midnight-reschedule.js +31 -0
  29. package/lib/motion-zone-timer.js +55 -0
  30. package/lib/num-comparator.js +70 -0
  31. package/lib/tools.js +12 -6
  32. package/lib/trigger-class.js +527 -282
  33. package/main.js +954 -626
  34. package/package.json +48 -32
  35. package/.github/ISSUE_TEMPLATE/BugReport.md +0 -36
  36. package/.github/ISSUE_TEMPLATE/Enhancement.md +0 -19
  37. package/.github/auto-merge.yml +0 -17
  38. package/.github/dependabot.yml +0 -12
  39. package/.github/workflows/dependabot-auto-merge.yml +0 -23
  40. package/.github/workflows/test-and-release.yml +0 -99
  41. package/.releaseconfig.json +0 -3
  42. package/main.test.js +0 -30
package/lib/helper.js CHANGED
@@ -1,47 +1,51 @@
1
- /* eslint-disable no-irregular-whitespace */
2
1
  'use strict';
3
2
 
4
3
  /**
5
- * @desc Generic Helper Functions
4
+ * @param adapter
5
+ * @description Generic Helper Functions
6
6
  * @author Mic-M <https://github.com/Mic-M/ioBroker.smartcontrol>
7
7
  * @license MIT
8
8
  */
9
9
  module.exports = function (adapter) {
10
-
11
10
  return {
12
-
13
-
14
11
  /**
15
12
  * Create States, either under adapter instance or anywhere.
16
13
  * TODO: Better error handling (callback: function (err, _obj) ) for set(Foreign)ObjectNotExistsAsync and set(Foreign)StateAsync
17
- *
18
- * @param {object|array} statesToCreate Object like {statePath:'0_userdata.0.motionHallway', commonObject:{name:'Motion', type:'boolean', read:true, write:true, role:'state', def:false }
14
+ *
15
+ * @param {object | Array} statesToCreate Object like {statePath:'0_userdata.0.motionHallway', commonObject:{name:'Motion', type:'boolean', read:true, write:true, role:'state', def:false }
19
16
  * You can pass multiple objects via array of these objects.
20
- * @param {boolean} [isForeign=false] False: creates states under adapter instance, if true: creates states anywhere.
17
+ * @param {boolean} [isForeign] False: creates states under adapter instance, if true: creates states anywhere.
21
18
  * WARN: use the "true" flag carefully!
22
- * @return {Promise<boolean>} false if errors caught, otherwise true.
19
+ * @returns {Promise<boolean>} false if errors caught, otherwise true.
23
20
  */
24
- async asyncCreateStates(statesToCreate, isForeign=false) {
25
-
21
+ async asyncCreateStates(statesToCreate, isForeign = false) {
26
22
  try {
27
-
28
23
  // Convert to array if it is an object, since we allow both
29
- if(!Array.isArray(statesToCreate)) statesToCreate = [statesToCreate];
24
+ if (!Array.isArray(statesToCreate)) {
25
+ statesToCreate = [statesToCreate];
26
+ }
30
27
 
31
28
  for (const lpStateToCreate of statesToCreate) {
32
-
33
29
  // Check parameters
34
30
  if (!lpStateToCreate.statePath || !lpStateToCreate.commonObject) {
35
31
  adapter.log.error(`asyncCreateForeignStates(): invalid parameter provided to function`);
36
32
  return false;
37
33
  }
38
34
 
39
- // Create new state.
35
+ // Create new state.
40
36
  // While set(Foreign)ObjectNotExistsAsync takes care if state does not exist, we still check as we also set values afterwards.
41
- if (isForeign && ! await this.asyncObjectExists(lpStateToCreate.statePath, true)) {
42
- await adapter.setForeignObjectNotExistsAsync(lpStateToCreate.statePath, {type:'state', common:lpStateToCreate.commonObject, native: {}});
43
- } else if(!isForeign && ! await this.asyncObjectExists(lpStateToCreate.statePath, false)) {
44
- await adapter.setObjectNotExistsAsync(lpStateToCreate.statePath, {type:'state', common:lpStateToCreate.commonObject, native: {}});
37
+ if (isForeign && !(await this.asyncObjectExists(lpStateToCreate.statePath, true))) {
38
+ await adapter.setForeignObjectNotExistsAsync(lpStateToCreate.statePath, {
39
+ type: 'state',
40
+ common: lpStateToCreate.commonObject,
41
+ native: {},
42
+ });
43
+ } else if (!isForeign && !(await this.asyncObjectExists(lpStateToCreate.statePath, false))) {
44
+ await adapter.setObjectNotExistsAsync(lpStateToCreate.statePath, {
45
+ type: 'state',
46
+ common: lpStateToCreate.commonObject,
47
+ native: {},
48
+ });
45
49
  } else {
46
50
  // State already exists.
47
51
  continue;
@@ -54,39 +58,45 @@ module.exports = function (adapter) {
54
58
  if (def !== undefined) {
55
59
  initialDefault = def;
56
60
  } else {
57
- if(type === 'number') initialDefault = 0;
58
- if(type === 'boolean') initialDefault = false;
59
- if(type === 'string') initialDefault = '';
60
- if(type === 'array') initialDefault = [];
61
- if(type === 'object') initialDefault = {};
62
- }
61
+ if (type === 'number') {
62
+ initialDefault = 0;
63
+ }
64
+ if (type === 'boolean') {
65
+ initialDefault = false;
66
+ }
67
+ if (type === 'string') {
68
+ initialDefault = '';
69
+ }
70
+ if (type === 'array') {
71
+ initialDefault = [];
72
+ }
73
+ if (type === 'object') {
74
+ initialDefault = {};
75
+ }
76
+ }
63
77
  if (isForeign) {
64
78
  await adapter.setForeignStateAsync(lpStateToCreate.statePath, initialDefault, false);
65
79
  } else {
66
80
  await adapter.setStateAsync(lpStateToCreate.statePath, initialDefault, false);
67
- }
81
+ }
68
82
  adapter.log.debug(`State '${lpStateToCreate.statePath}' created.`);
69
-
70
83
  }
71
84
 
72
85
  return true;
73
-
74
-
75
86
  } catch (error) {
76
87
  this.dumpError('[asyncCreateForeignStates()]', error);
77
88
  return false;
78
89
  }
79
-
80
90
  },
81
91
 
82
- /**
92
+ /**
83
93
  * Check if an ioBroker object exists.
94
+ *
84
95
  * @param {string} str State path
85
- * @param {boolean} [isForeign=false] true if a foreign state, false if a state of this adapter
86
- * @return {Promise<boolean>}
96
+ * @param {boolean} [isForeign] true if a foreign state, false if a state of this adapter
97
+ * @returns {Promise<boolean>}
87
98
  */
88
- async asyncObjectExists (str, isForeign=false) {
89
-
99
+ async asyncObjectExists(str, isForeign = false) {
90
100
  try {
91
101
  let ret;
92
102
  if (isForeign) {
@@ -94,65 +104,61 @@ module.exports = function (adapter) {
94
104
  } else {
95
105
  ret = await adapter.getObjectAsync(str);
96
106
  }
97
-
107
+
98
108
  if (ret == undefined) {
99
109
  return false;
100
- } else {
101
- return true;
102
110
  }
111
+ return true;
103
112
  } catch (error) {
104
113
  this.dumpError('[asyncObjectExists()]', error);
105
114
  return false;
106
115
  }
107
-
108
116
  },
109
117
 
110
118
  /**
111
119
  * Get foreign state value
112
- *
120
+ *
113
121
  * @param {string} statePath - Full path to state, like 0_userdata.0.other.isSummer
114
- * @return {Promise<*>} - State value, or null if error
122
+ * @returns {Promise<*>} - State value, or null if error
115
123
  */
116
124
  async asyncGetForeignStateValue(statePath) {
117
125
  try {
118
126
  const stateObject = await this.asyncGetForeignState(statePath);
119
- if (stateObject == null) return null; // error thrown already in asyncGetForeignState()
120
- return stateObject.val;
127
+ if (stateObject == null) {
128
+ return null;
129
+ } // error thrown already in asyncGetForeignState()
130
+ return stateObject.val;
121
131
  } catch (error) {
122
132
  this.dumpError(`[asyncGetForeignStateValue]`, error);
123
133
  return null;
124
134
  }
125
-
126
- },
135
+ },
127
136
 
128
137
  /**
129
138
  * Get foreign state
130
- *
139
+ *
131
140
  * @param {string} statePath - Full path to state, like 0_userdata.0.other.isSummer
132
- * @return {Promise<object>} - State object: {val: false, ack: true, ts: 1591117034451, …}, or null if error
141
+ * @returns {Promise<object>} - State object: {val: false, ack: true, ts: 1591117034451, …}, or null if error
133
142
  */
134
143
  async asyncGetForeignState(statePath) {
135
-
136
144
  try {
137
145
  // Check state existence
138
146
  const stateObject = await adapter.getForeignObjectAsync(statePath);
139
147
 
140
148
  if (!stateObject) {
141
- throw(`State '${statePath}' does not exist.`);
149
+ throw `State '${statePath}' does not exist.`;
142
150
  } else {
143
151
  // Get state value, so like: {val: false, ack: true, ts: 1591117034451, …}
144
152
  const stateValueObject = await adapter.getForeignStateAsync(statePath);
145
- if (! this.isLikeEmpty(stateValueObject)) {
153
+ if (!this.isLikeEmpty(stateValueObject)) {
146
154
  return stateValueObject;
147
- } else {
148
- throw(`Unable to retrieve info from state '${statePath}'.`);
149
155
  }
156
+ throw `Unable to retrieve info from state '${statePath}'.`;
150
157
  }
151
158
  } catch (error) {
152
159
  this.dumpError(`[asyncGetForeignState]`, error);
153
160
  return null;
154
161
  }
155
-
156
162
  },
157
163
 
158
164
  /**
@@ -160,30 +166,28 @@ module.exports = function (adapter) {
160
166
  * This function is needed since toISOString() uses UTC +0 (Zulu) as time zone.
161
167
  * https://stackoverflow.com/questions/10830357/
162
168
  * Mic-M, 04/Apr/2020
169
+ *
163
170
  * @param {object} date Date object
164
- * @return {string} string like "2015-01-26T06:40:36.181", without trailing Z (which would represent Zulu time zone)
171
+ * @returns {string} string like "2015-01-26T06:40:36.181", without trailing Z (which would represent Zulu time zone)
165
172
  */
166
173
  dateToLocalIsoString(date) {
167
174
  const timezoneOffset = date.getTimezoneOffset() * 60000; //offset in milliseconds
168
- return (new Date(date.getTime() - timezoneOffset)).toISOString().slice(0, -1);
175
+ return new Date(date.getTime() - timezoneOffset).toISOString().slice(0, -1);
169
176
  },
170
177
 
171
-
172
-
173
-
174
178
  /**
175
179
  * For given object of enum objects, get the names and associated ids.
176
180
  * enumObj.common.name can be either string like 'Living room' or {en:'Living room', de:'Wohnzimmer', ...}
181
+ *
177
182
  * @param {object} enumObj - object of multiple enum objects, so return of getEnumAsync('rooms').result or getEnumAsync('functions').result
178
- * @param {boolean} [allLanguages=false] if true, it will return all languages (in case user changes ioBroker language after saving options), if false, just the current language
179
- * @return {object|null} resulting object like {'Bathroom': 'enum.rooms.bathroom', 'Bedroom': 'enum.rooms.bedroom'}, or null if nothing found
183
+ * @param {boolean} [allLanguages] if true, it will return all languages (in case user changes ioBroker language after saving options), if false, just the current language
184
+ * @returns {object|null} resulting object like {'Bathroom': 'enum.rooms.bathroom', 'Bedroom': 'enum.rooms.bedroom'}, or null if nothing found
180
185
  */
181
- enumsGetNamesAndIds(enumObj, allLanguages=false) {
182
-
186
+ enumsGetNamesAndIds(enumObj, allLanguages = false) {
183
187
  try {
184
-
185
188
  const result = {};
186
- for (const id in enumObj) { // id = like 'enum.rooms.bathroom'
189
+ for (const id in enumObj) {
190
+ // id = like 'enum.rooms.bathroom'
187
191
  const nameObj = enumObj[id].common.name; // either string like 'Living room' or {en:'Living room', de:'Wohnzimmer', ...}
188
192
  if (typeof nameObj === 'string') {
189
193
  result[nameObj] = id;
@@ -195,23 +199,21 @@ module.exports = function (adapter) {
195
199
  } else {
196
200
  result[nameObj[adapter.x.systemConfig.language]] = id;
197
201
  }
198
-
199
202
  } else {
200
- adapter.log.warn(`Getting enum room name for '${id}': type for name must be string or object, but is '${typeof nameObj}'.`);
203
+ adapter.log.warn(
204
+ `Getting enum room name for '${id}': type for name must be string or object, but is '${typeof nameObj}'.`,
205
+ );
201
206
  }
202
207
  }
203
208
 
204
209
  if (!this.isLikeEmpty(result)) {
205
210
  return result;
206
- } else {
207
- return null;
208
211
  }
209
-
212
+ return null;
210
213
  } catch (error) {
211
214
  this.dumpError('[enumsGetNamesAndIds]', error);
212
215
  return null;
213
216
  }
214
-
215
217
  },
216
218
 
217
219
  /**
@@ -240,33 +242,31 @@ module.exports = function (adapter) {
240
242
  },
241
243
  */
242
244
 
243
-
244
-
245
-
246
245
  /**
247
246
  * Verify acknowledge (ack) once a state was changed.
248
- *
247
+ *
249
248
  * In General: Any state changes of states will be ignored, if acknowledge (ack) = false.
250
249
  * The reason is that adapters confirm states by the acknowledge "ack" flag (setting to true).
251
250
  * Reference: https://forum.iobroker.net/post/448606
252
- *
251
+ *
253
252
  * Exception 1: States under javascript.x/0_userdata.0/alias.x: For states created by users, this behavior can be changed in the adapter options.
254
253
  * Exception 2: States under smartcontrol.x.: ack:false only.
255
- * Exception 3: States which are not under a "real" adapter namespace, so like "Messwerte.0". Reason: Several users have created
254
+ * Exception 3: States which are not under a "real" adapter namespace, so like "Messwerte.0". Reason: Several users have created
256
255
  * own states in the object main tree, like "Messwerte.0". https://forum.iobroker.net/post/461189
257
- *
256
+ *
258
257
  * @param {string} statePath - State Path
259
258
  * @param {ioBroker.State|null|undefined} stateObject - State object
260
- * @return {Promise<object>} {passing: false; msg:'some message'}
259
+ * @returns {Promise<object>} {passing: false; msg:'some message'}
261
260
  * if state change shall be ignored due to the ack (or error occurred), otherwise true.
262
- *
263
261
  */
264
262
  async isAckPassing(statePath, stateObject) {
265
-
266
263
  try {
267
-
268
- if (!stateObject || !statePath)
269
- return {passing:false, msg:`Unexpected error: isAckPassing() was no valid statePath or stateObject provided.`};
264
+ if (!stateObject || !statePath) {
265
+ return {
266
+ passing: false,
267
+ msg: `Unexpected error: isAckPassing() was no valid statePath or stateObject provided.`,
268
+ };
269
+ }
270
270
 
271
271
  const namespace = `${statePath.split('.')[0]}.${statePath.split('.')[1]}`; // like sonos.1
272
272
 
@@ -275,107 +275,116 @@ module.exports = function (adapter) {
275
275
  // if (statePath.startsWith(`${adapter.namespace}.`)) {
276
276
  if (statePath.match(/^smartcontrol.\d+./)) {
277
277
  if (stateObject.ack == false) {
278
- return {passing:true, msg:`Adapter Instance State (${adapter.namespace}) requires ack:false`};
279
- } else {
280
- return {passing:false, msg:`Adapter Instance State (${adapter.namespace}) requires ack:false`};
278
+ return {
279
+ passing: true,
280
+ msg: `Adapter Instance State (${adapter.namespace}) requires ack:false`,
281
+ };
281
282
  }
283
+ return { passing: false, msg: `Adapter Instance State (${adapter.namespace}) requires ack:false` };
282
284
  }
283
285
 
284
286
  // Handle User States
285
287
  let isUserState = false;
286
- if (statePath.startsWith('javascript.') || statePath.startsWith('0_userdata.0') || statePath.startsWith('alias.')) isUserState = true;
288
+ if (
289
+ statePath.startsWith('javascript.') ||
290
+ statePath.startsWith('0_userdata.0') ||
291
+ statePath.startsWith('alias.')
292
+ ) {
293
+ isUserState = true;
294
+ }
287
295
 
288
296
  if (!isUserState) {
289
297
  // Check if state is under a "real" adapter namespace.
290
298
  const isRealAdapter = await adapter.getForeignObjectAsync(`system.adapter.${namespace}`);
291
- if (!isRealAdapter) isUserState = true;
299
+ if (!isRealAdapter) {
300
+ isUserState = true;
301
+ }
292
302
  }
293
303
 
294
304
  if (isUserState) {
295
-
296
305
  if (!adapter.config.triggerStatesAck || adapter.config.triggerStatesAck == 'false') {
297
306
  if (stateObject.ack == false) {
298
- return {passing:true, msg:`User State (${statePath}) requires ack:false per adapter configuration`};
299
- } else {
300
- return {passing:false, msg:`User State (${statePath}) requires ack:false per adapter configuration`};
307
+ return {
308
+ passing: true,
309
+ msg: `User State (${statePath}) requires ack:false per adapter configuration`,
310
+ };
301
311
  }
302
-
312
+ return {
313
+ passing: false,
314
+ msg: `User State (${statePath}) requires ack:false per adapter configuration`,
315
+ };
303
316
  } else if (adapter.config.triggerStatesAck == 'true') {
304
317
  if (stateObject.ack == true) {
305
- return {passing:true, msg:`User State (${statePath}) requires ack:true per adapter configuration`};
306
- } else {
307
- return {passing:false, msg:`User State (${statePath}) requires ack:true per adapter configuration`};
318
+ return {
319
+ passing: true,
320
+ msg: `User State (${statePath}) requires ack:true per adapter configuration`,
321
+ };
308
322
  }
309
- } else {
310
- // any (ack: true or false)
311
- return {passing:true, msg:`User State (${statePath}) can be ack:true or ack:false per adapter configuration`};
312
- }
313
-
314
- } else {
315
- // For any other "real" adapter state changes, we require ack = true
316
- if (stateObject.ack == true) {
317
- return {passing:true, msg:`"Real" adapter state (${statePath}) requires ack:true`};
318
- } else {
319
- return {passing:false, msg:`"Real" adapter state (${statePath}) requires ack:true`};
323
+ return {
324
+ passing: false,
325
+ msg: `User State (${statePath}) requires ack:true per adapter configuration`,
326
+ };
320
327
  }
328
+ // any (ack: true or false)
329
+ return {
330
+ passing: true,
331
+ msg: `User State (${statePath}) can be ack:true or ack:false per adapter configuration`,
332
+ };
321
333
  }
322
-
334
+ // For any other "real" adapter state changes, we require ack = true
335
+ if (stateObject.ack == true) {
336
+ return { passing: true, msg: `"Real" adapter state (${statePath}) requires ack:true` };
337
+ }
338
+ return { passing: false, msg: `"Real" adapter state (${statePath}) requires ack:true` };
323
339
  } catch (error) {
324
340
  this.dumpError('[isAckPassing()]', error);
325
- return {passing:false, msg:`Unexpected error occurred in isAckPassing()`};
341
+ return { passing: false, msg: `Unexpected error occurred in isAckPassing()` };
326
342
  }
327
-
328
343
  },
329
344
 
330
-
331
345
  /**
332
346
  * Checks if a cron string like xxx is valid or not.
333
- * Source: "Test if schedule is valid" - https://github.com/node-schedule/node-schedule/issues/296#issuecomment-269971152
334
- * Read: https://stackoverflow.com/questions/35817080/node-requiring-module-inside-function
335
- *
347
+ *
336
348
  * @param {string} str String to check, so like '0 22 * * 1-5'
337
- * @return {boolean} true if we have a valid cron string, false if not.
349
+ * @returns {boolean} true if we have a valid cron string, false if not.
338
350
  */
339
351
  isCronScheduleValid(str) {
340
-
341
- // node-schedule uses cron-parser, so we can simply require it here without adding to package.json
342
- const cronParser = require('cron-parser');
343
- try {
344
- cronParser.parseExpression(str);
345
- } catch (error) {
346
- // handle the parse error
347
- return false;
348
- }
349
- // success
350
- return true;
351
-
352
+ // Ausgelagert: gleiche Prüfung beim Speichern und beim Planen der Timer.
353
+ return require('./cron-schedule').isCronScheduleValid(str);
352
354
  },
353
355
 
354
356
  /**
355
357
  * Get the timestamp of an astro name.
356
- *
358
+ *
357
359
  * @param {string} astroName Name of sunlight time, like "sunrise", "nauticalDusk", etc.
358
- * @param {number} [offsetMinutes=0] Offset in minutes
359
- * @return {number} Timestamp of the astro name
360
+ * @param {number} [offsetMinutes] Offset in minutes
361
+ * @returns {number} Timestamp of the astro name
360
362
  */
361
- getAstroNameTs(astroName, offsetMinutes=0) {
362
-
363
+ getAstroNameTs(astroName, offsetMinutes = 0) {
363
364
  try {
364
- let ts = adapter.x.mSuncalc.getTimes(new Date(), adapter.x.systemConfig.latitude, adapter.x.systemConfig.longitude)[astroName];
365
+ let ts = adapter.x.mSuncalc.getTimes(
366
+ new Date(),
367
+ adapter.x.systemConfig.latitude,
368
+ adapter.x.systemConfig.longitude,
369
+ )[astroName];
365
370
  if (!ts || ts.getTime().toString() === 'NaN') {
366
371
  // Fix night / nightEnd per adapter options.
367
- // In northern areas is no night/nightEnd provided in the Summer.
372
+ // In northern areas is no night/nightEnd provided in the Summer.
368
373
  // So we use 0:00 for night and 2:00 for night end as fallback.
369
- if (adapter.config.fixNightNightEnd && ['night', 'nightEnd'].includes(astroName) ) {
370
- const currDate = new Date();
371
- const midnightTs = currDate.setHours(24,0,0,0); // is the future midnight of today, not the one that was at 0:00 today
374
+ if (adapter.config.fixNightNightEnd && ['night', 'nightEnd'].includes(astroName)) {
375
+ const currDate = new Date();
376
+ const midnightTs = currDate.setHours(24, 0, 0, 0); // is the future midnight of today, not the one that was at 0:00 today
372
377
  switch (astroName) {
373
378
  case 'night':
374
- adapter.log.debug(`[getAstroNameTs] No time found for [${astroName}], so we set 00:00 as fallback per adapter config.`);
379
+ adapter.log.debug(
380
+ `[getAstroNameTs] No time found for [${astroName}], so we set 00:00 as fallback per adapter config.`,
381
+ );
375
382
  return midnightTs; // midnight - 00:00
376
- case 'nightEnd':
377
- adapter.log.debug(`[getAstroNameTs] No time found for [${astroName}], so we set 02:00 as fallback per adapter config.`);
378
- return midnightTs + (1000*3600*2); // 02:00
383
+ case 'nightEnd':
384
+ adapter.log.debug(
385
+ `[getAstroNameTs] No time found for [${astroName}], so we set 02:00 as fallback per adapter config.`,
386
+ );
387
+ return midnightTs + 1000 * 3600 * 2; // 02:00
379
388
  }
380
389
  } else {
381
390
  adapter.log.warn(`[getAstroNameTs] No time found for [${astroName}].`);
@@ -384,31 +393,28 @@ module.exports = function (adapter) {
384
393
  }
385
394
 
386
395
  ts = this.roundTimeStampToNearestMinute(ts);
387
- ts = ts + (offsetMinutes * 60 * 1000);
396
+ ts = ts + offsetMinutes * 60 * 1000;
388
397
  return ts;
389
398
  } catch (error) {
390
399
  this.dumpError('[getAstroNameTs()]', error);
391
400
  return 0;
392
401
  }
393
-
394
402
  },
395
403
 
396
-
397
404
  /**
398
405
  * Get the time stamp of a time string, like '23:30', 'goldenHourEnd', or 'goldenHourEnd+30'
399
406
  * Supports times like 'h:ss'/'hh:ss', and also astro names.
400
407
  * Astro names can also have an additional offset in minutes, so like "sunriseEnd-40" or "sunriseEnd+120".
401
- *
408
+ *
402
409
  * @param {string} input the input string
403
- * @param {boolean} [getFullResult=false] if false: returns true if a valid time provided, and false if not.
410
+ * @param {boolean} [getFullResult] if false: returns true if a valid time provided, and false if not.
404
411
  * if true: Empty object if nothing found, or object with details.
405
- * @return {boolean|object} Return value
412
+ * @returns {boolean|object} Return value
406
413
  */
407
- getTimeInfoFromAstroString(input, getFullResult=false) {
408
-
414
+ getTimeInfoFromAstroString(input, getFullResult = false) {
409
415
  const currentDateTime = new Date(); // Date object of current date/time
410
416
 
411
- input = input.replace(/\s/g,''); // remove all white spaces
417
+ input = input.replace(/\s/g, ''); // remove all white spaces
412
418
 
413
419
  const returnObject = {
414
420
  full: input,
@@ -421,20 +427,23 @@ module.exports = function (adapter) {
421
427
  };
422
428
 
423
429
  const matchTime = input.match(/^(\d{1,2})(:)(\d{2})$/);
424
- const matchAstroName = input.match(/^(sunriseEnd|sunrise|goldenHourEnd|solarNoon|goldenHour|sunsetStart|sunset|dusk|nauticalDusk|nightEnd|nadir|night|nauticalDawn|dawn)$/g);
425
- const matchAstroWithOffset = input.match(/^(sunriseEnd|sunrise|goldenHourEnd|solarNoon|goldenHour|sunsetStart|sunset|dusk|nauticalDusk|nightEnd|nadir|night|nauticalDawn|dawn)(-|\+)(\d{1,3})$/);
430
+ const matchAstroName = input.match(
431
+ /^(sunriseEnd|sunrise|goldenHourEnd|solarNoon|goldenHour|sunsetStart|sunset|dusk|nauticalDusk|nightEnd|nadir|night|nauticalDawn|dawn)$/g,
432
+ );
433
+ const matchAstroWithOffset = input.match(
434
+ /^(sunriseEnd|sunrise|goldenHourEnd|solarNoon|goldenHour|sunsetStart|sunset|dusk|nauticalDusk|nightEnd|nadir|night|nauticalDawn|dawn)(-|\+)(\d{1,3})$/,
435
+ );
426
436
 
427
437
  if (matchTime != null) {
428
438
  // No Astro.
429
439
  // Time like "19:35" found. Convert to timestamp by using current date
430
-
440
+
431
441
  const hour = parseInt(matchTime[1]);
432
442
  const min = parseInt(matchTime[3]);
433
443
 
434
- if ( (input != '24:00') && (hour < 0 || hour > 23 || min < 0 || min > 60 ) ) {
444
+ if (input != '24:00' && (hour < 0 || hour > 23 || min < 0 || min > 60)) {
435
445
  returnObject.full = '';
436
446
  } else {
437
-
438
447
  returnObject.timestamp = new Date(
439
448
  currentDateTime.getFullYear(),
440
449
  currentDateTime.getMonth(),
@@ -442,7 +451,6 @@ module.exports = function (adapter) {
442
451
  hour, // hours
443
452
  min, // minutes
444
453
  ).getTime();
445
-
446
454
  }
447
455
  } else {
448
456
  if (matchAstroName != null) {
@@ -456,10 +464,13 @@ module.exports = function (adapter) {
456
464
  returnObject.astroHasOffset = true;
457
465
  returnObject.astroName = matchAstroWithOffset[1];
458
466
  returnObject.astroOffsetMinutes = parseInt(matchAstroWithOffset[3]);
459
- if(matchAstroWithOffset[2] == '-') {
460
- returnObject.astroOffsetMinutes = returnObject.astroOffsetMinutes * (-1);
467
+ if (matchAstroWithOffset[2] == '-') {
468
+ returnObject.astroOffsetMinutes = returnObject.astroOffsetMinutes * -1;
461
469
  }
462
- returnObject.timestamp = this.getAstroNameTs(returnObject.astroName, returnObject.astroOffsetMinutes);
470
+ returnObject.timestamp = this.getAstroNameTs(
471
+ returnObject.astroName,
472
+ returnObject.astroOffsetMinutes,
473
+ );
463
474
  } else {
464
475
  // Nothing found
465
476
  returnObject.full = '';
@@ -471,110 +482,106 @@ module.exports = function (adapter) {
471
482
 
472
483
  // handle '24:00'. We add a full day.
473
484
  if (input == '24:00') {
474
- returnObject.timestamp = returnObject.timestamp + +1000*60*60*24;
485
+ returnObject.timestamp = returnObject.timestamp + +1000 * 60 * 60 * 24;
475
486
  returnObject.hoursMins = '24:00';
476
487
  }
477
488
 
478
-
479
489
  if (!getFullResult) {
480
490
  if (!returnObject.full) {
481
491
  return false;
482
- } else {
483
- return true;
484
492
  }
485
- } else {
486
- return returnObject;
493
+ return true;
487
494
  }
488
-
495
+ return returnObject;
489
496
  },
490
497
 
491
498
  /**
492
499
  * Converts a given timestamp into European time. E.g. '9:03pm and 45 seconds' -> '21:03:45'
500
+ *
493
501
  * @param {object} ts Timestamp
494
- * @param {boolean} [noSeconds=false] if true, seconds will not be added. Result is '21:04' (rounded)
495
- * @return {string} Date in European date/time as String
502
+ * @param {boolean} [noSeconds] if true, seconds will not be added. Result is '21:04' (rounded)
503
+ * @returns {string} Date in European date/time as String
496
504
  */
497
- timestampToTimeString(ts, noSeconds=false) {
498
-
499
- if(noSeconds) ts = this.roundTimeStampToNearestMinute(ts);
500
- const inputDate = new Date(ts);
501
-
505
+ timestampToTimeString(ts, noSeconds = false) {
502
506
  if (noSeconds) {
503
- return this.zeroPad(inputDate.getHours(), 2) + ':' + this.zeroPad(inputDate.getMinutes(), 2);
504
- } else {
505
- return this.zeroPad(inputDate.getHours(), 2) + ':' + this.zeroPad(inputDate.getMinutes(), 2) + ':' + this.zeroPad(inputDate.getSeconds(), 2);
507
+ ts = this.roundTimeStampToNearestMinute(ts);
506
508
  }
509
+ const inputDate = new Date(ts);
507
510
 
511
+ if (noSeconds) {
512
+ return `${this.zeroPad(inputDate.getHours(), 2)}:${this.zeroPad(inputDate.getMinutes(), 2)}`;
513
+ }
514
+ return `${this.zeroPad(inputDate.getHours(), 2)}:${this.zeroPad(inputDate.getMinutes(), 2)}:${this.zeroPad(
515
+ inputDate.getSeconds(),
516
+ 2,
517
+ )}`;
508
518
  },
509
519
 
510
-
511
520
  /**
512
521
  * Checks if time of '08:30' is between '23:00' and '09:00'.
513
522
  * Source/inspired by: https://stackoverflow.com/a/24577309
514
- *
523
+ *
515
524
  * @param {string} start - start string, like: '23:00', '07:30', 9:15'
516
525
  * @param {string} end - end string, like: '08:15', '17:23'
517
526
  * @param {string} check - to check, like: '17:25', '9:30'
518
- * @return {boolean} true if in between, false if not
519
- *
527
+ * @returns {boolean} true if in between, false if not
520
528
  */
521
- isTimeBetween (start, end, check) {
522
-
523
-
524
- const timeIsBetween = function(start, end, check) {
525
- return (start.hour <= end.hour) ? check.isGreaterThan(start) && !check.isGreaterThan(end)
526
- : (check.isGreaterThan(start) && check.isGreaterThan(end)) || (!check.isGreaterThan(start) && !check.isGreaterThan(end));
529
+ isTimeBetween(start, end, check) {
530
+ const timeIsBetween = function (start, end, check) {
531
+ return start.hour <= end.hour
532
+ ? check.isGreaterThan(start) && !check.isGreaterThan(end)
533
+ : (check.isGreaterThan(start) && check.isGreaterThan(end)) ||
534
+ (!check.isGreaterThan(start) && !check.isGreaterThan(end));
527
535
  };
528
-
529
- function getTimeObj (timeString) {
536
+
537
+ function getTimeObj(timeString) {
530
538
  const t = timeString.split(':');
531
539
  const returnObject = {};
532
540
  returnObject.hour = parseInt(t[0]);
533
541
  returnObject.minutes = parseInt(t[1]);
534
- returnObject.isGreaterThan = function(other) {
535
- return (returnObject.hour > other.hour) || (returnObject.hour === other.hour) && (returnObject.minutes > other.minutes);
542
+ returnObject.isGreaterThan = function (other) {
543
+ return (
544
+ returnObject.hour > other.hour ||
545
+ (returnObject.hour === other.hour && returnObject.minutes > other.minutes)
546
+ );
536
547
  };
537
548
  return returnObject;
538
549
  }
539
-
550
+
540
551
  return timeIsBetween(getTimeObj(start), getTimeObj(end), getTimeObj(check));
541
-
542
552
  },
543
553
 
544
-
545
554
  /**
546
555
  * Gets the time left of 'const xxx = setTimeout()', where xxx is the timer id.
547
- *
556
+ *
548
557
  * @author Mic-M <https://github.com/Mic-M/>
549
558
  * @version 0.1 (30 June 2020)
550
- *
551
559
  * @param {object} timerId - The timer object 'xxx' when executing a 'const xxx = setTimeout()'
552
- * @return {number} The time remaining of the setTimeout() in milliseconds. Returns -1, if not or no longer running, never run, or object not even set.
560
+ * @returns {number} The time remaining of the setTimeout() in milliseconds. Returns -1, if not or no longer running, never run, or object not even set.
553
561
  * To convert ms to seconds, simply use: (timeLeft / 1000).toFixed(0) - where timeLeft is the return value of the function.
554
- *
555
562
  */
556
563
  getTimeoutTimeLeft(timerId) {
557
-
558
564
  try {
559
-
560
565
  // Return -1 if timer object is undefined/null or if timer is not running
561
- if (!timerId || timerId._destroyed) return -1;
566
+ if (!timerId || timerId._destroyed) {
567
+ return -1;
568
+ }
562
569
 
563
- const dummyTimer = setTimeout(() => {}, 0); // We need a dummy timer to get the current number of ms when the node.js session was started
564
- const currMsAfterNodeJsStart = dummyTimer['_idleStart']; // _idleStart is the number of milliseconds since the node.js session was started.
565
- clearTimeout(dummyTimer); // clear dummy timer, just in case.
570
+ const dummyTimer = setTimeout(() => {}, 0); // We need a dummy timer to get the current number of ms when the node.js session was started
571
+ const currMsAfterNodeJsStart = dummyTimer['_idleStart']; // _idleStart is the number of milliseconds since the node.js session was started.
572
+ clearTimeout(dummyTimer); // clear dummy timer, just in case.
566
573
 
567
- const elapsed = currMsAfterNodeJsStart - timerId._idleStart; // for how many milliseconds is timer already running?
568
- let remaining = timerId._idleTimeout - elapsed; // remaining time in ms
569
- if (remaining < 0 ) remaining = -1; // Just in case, should be already caught by timerObject._destroyed
574
+ const elapsed = currMsAfterNodeJsStart - timerId._idleStart; // for how many milliseconds is timer already running?
575
+ let remaining = timerId._idleTimeout - elapsed; // remaining time in ms
576
+ if (remaining < 0) {
577
+ remaining = -1;
578
+ } // Just in case, should be already caught by timerObject._destroyed
570
579
 
571
580
  return remaining;
572
-
573
581
  } catch (error) {
574
582
  this.dumpError('[getTimeoutTimeLeft()]', error);
575
583
  return -1;
576
- }
577
-
584
+ }
578
585
  },
579
586
 
580
587
  /**
@@ -584,30 +591,36 @@ module.exports = function (adapter) {
584
591
  * @param {string} start Start time, like '18:30', or 'sunrise, or 'sunset+30'
585
592
  * @param {string} end End time
586
593
  * @param {string} ofWhat Typically zone name. For logging purposes only.
587
- * @return {boolean} true if within times, and false if not.
594
+ * @returns {boolean} true if within times, and false if not.
588
595
  */
589
596
  scheduleIsTimeStampWithinPeriod(tsGiven, start, end, ofWhat) {
590
-
591
597
  try {
592
-
593
598
  // First: convert potential Astro start time to "normal", so like 'sunset-30' to '18:30'
594
599
  const givenFinal = this.timestampToTimeString(tsGiven, true);
595
600
  const startFinal = this.getTimeInfoFromAstroString(start, true).hoursMins;
596
- const endFinal = this.getTimeInfoFromAstroString(end, true).hoursMins;
601
+ const endFinal = this.getTimeInfoFromAstroString(end, true).hoursMins;
597
602
 
598
- if (!givenFinal) throw(`givenFinal is undefined. start: '${start}', end: '${end}', ofWhat: '${ofWhat}'`);
599
- if (!startFinal) throw(`startFinal is undefined. start: '${start}', end: '${end}', ofWhat: '${ofWhat}'`);
600
- if (!endFinal) throw(`endFinal is undefined. start: '${start}', end: '${end}', ofWhat: '${ofWhat}'`);
603
+ if (!givenFinal) {
604
+ throw `givenFinal is undefined. start: '${start}', end: '${end}', ofWhat: '${ofWhat}'`;
605
+ }
606
+ if (!startFinal) {
607
+ throw `startFinal is undefined. start: '${start}', end: '${end}', ofWhat: '${ofWhat}'`;
608
+ }
609
+ if (!endFinal) {
610
+ throw `endFinal is undefined. start: '${start}', end: '${end}', ofWhat: '${ofWhat}'`;
611
+ }
601
612
 
602
613
  // Next, check if given time is in between
603
614
  if (this.isTimeBetween(startFinal, endFinal, givenFinal)) {
604
- adapter.log.debug(`'${ofWhat}' - Current time '${givenFinal}' *is* within schedule times (start: '${startFinal}', end: '${endFinal}).`);
605
- return true;
606
- } else {
607
- adapter.log.debug(`'${ofWhat}' - Current time '${givenFinal}' is *not* within schedule times (start: '${startFinal}', end: '${endFinal}).`);
608
- return false;
615
+ adapter.log.debug(
616
+ `'${ofWhat}' - Current time '${givenFinal}' *is* within schedule times (start: '${startFinal}', end: '${endFinal}).`,
617
+ );
618
+ return true;
609
619
  }
610
-
620
+ adapter.log.debug(
621
+ `'${ofWhat}' - Current time '${givenFinal}' is *not* within schedule times (start: '${startFinal}', end: '${endFinal}).`,
622
+ );
623
+ return false;
611
624
  } catch (error) {
612
625
  this.dumpError('[scheduleIsTimeStampWithinPeriod]', error);
613
626
  return false;
@@ -616,24 +629,28 @@ module.exports = function (adapter) {
616
629
 
617
630
  /**
618
631
  * Check if current day is within the mon-sun options as set in Execution table.
619
- *
632
+ *
620
633
  * @param {object} row The "Execution" table row which was triggered.
621
634
  * @param {number} ts The timestamp to check.
622
635
  * @param {string} ofWhat Typically zone name. For logging purposes only.
623
- * @return {boolean} True if matching, false if not.
636
+ * @returns {boolean} True if matching, false if not.
624
637
  */
625
638
  scheduleIsWeekdayMatching(row, ts, ofWhat) {
626
639
  const days = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
627
640
  const lpWeekdayGiven = getWeekDayString(ts);
628
641
  for (const lpDay of days) {
629
642
  if (lpWeekdayGiven == null) {
630
- adapter.log.error(`[scheduleIsWeekdayMatching()] Unable to calculate day of week for given timestamp '${ts}'`);
643
+ adapter.log.error(
644
+ `[scheduleIsWeekdayMatching()] Unable to calculate day of week for given timestamp '${ts}'`,
645
+ );
631
646
  return false;
632
- } else if ( (row[lpDay] == true) && (lpDay == lpWeekdayGiven) ) {
633
- adapter.log.debug(`${ofWhat} - Current weekday '${lpWeekdayGiven}' *is* matching Execution table row.`);
647
+ } else if (row[lpDay] == true && lpDay == lpWeekdayGiven) {
648
+ adapter.log.debug(
649
+ `${ofWhat} - Current weekday '${lpWeekdayGiven}' *is* matching Execution table row.`,
650
+ );
634
651
  return true;
635
652
  }
636
- }
653
+ }
637
654
  // There was no hit, so we return false.
638
655
  adapter.log.debug(`${ofWhat} - Current weekday '${lpWeekdayGiven}' is *not* matching Execution table row.`);
639
656
  return false;
@@ -641,74 +658,84 @@ module.exports = function (adapter) {
641
658
  /**
642
659
  * get the week day of a string.
643
660
  * Source: https://stackoverflow.com/a/17964373
661
+ *
644
662
  * @param {*} date object or time stamp or string that is recognized by the Date.parse() method
645
- * @return {string|null} day of week as string, or null if not found.
663
+ * @returns {string|null} day of week as string, or null if not found.
646
664
  */
647
665
  function getWeekDayString(date) {
648
- const dayOfWeek = new Date(date).getDay();
666
+ const dayOfWeek = new Date(date).getDay();
649
667
  return isNaN(dayOfWeek) ? null : ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'][dayOfWeek];
650
668
  }
651
-
652
669
  },
653
670
 
654
671
  /**
655
672
  * JSON Log to smartcontrol.x.info.log.<id>.json
673
+ *
656
674
  * @param {string} id - e.g. 'zoneActivations' or 'switchedTargetDevices'
657
675
  * @param {object} jsonObj - object to add, e.g. {zone:'xyz', targetDevice:'xyz'}
658
- * @return {boolean} - false if errors caught, otherwise true.
676
+ * @returns {boolean} - false if errors caught, otherwise true.
659
677
  */
660
678
  async setJsonLog(id, jsonObj) {
661
-
662
679
  try {
663
-
664
680
  let maxJsonLength = 0;
665
- if (adapter.x.helper.isNumber(adapter.config.jsonMaxEntries)) {
681
+ if (adapter.x.helper.isNumber(adapter.config.jsonMaxEntries)) {
666
682
  maxJsonLength = parseInt(adapter.config.jsonMaxEntries);
667
683
  }
668
- if (maxJsonLength <= 0) return true;
669
-
670
- if(!this.isLikeEmpty(adapter.x.jsonLogs[id])) {
684
+ if (maxJsonLength <= 0) {
685
+ return true;
686
+ }
687
+
688
+ if (!this.isLikeEmpty(adapter.x.jsonLogs[id])) {
671
689
  adapter.x.jsonLogs[id] = adapter.x.jsonLogs[id].slice(0, maxJsonLength - 1); // just keep first x entries
672
- adapter.x.jsonLogs[id].unshift(jsonObj); // Add new entry as first element of array
690
+ adapter.x.jsonLogs[id].unshift(jsonObj); // Add new entry as first element of array
673
691
  } else {
674
692
  adapter.x.jsonLogs[id] = [jsonObj]; // add as array
675
693
  }
676
694
  adapter.setState(`info.log.${id}.json`, { val: JSON.stringify(adapter.x.jsonLogs[id]), ack: true });
677
695
  return true;
678
-
679
696
  } catch (error) {
680
697
  this.dumpError('[setJsonLog]', error);
681
698
  return false;
682
699
  }
683
-
684
700
  },
685
701
 
686
-
687
702
  /**
688
- * Checks if an ioBroker state id (path) string is valid.
703
+ * Checks if an ioBroker state id (path) string is valid.
689
704
  * NOTE: This does not verify if the state is existing. It does just some basic checks if the path looks good-
690
- *
705
+ *
691
706
  * @param {string} str String to validate
692
- * @return {boolean} true/false of validation result
707
+ * @returns {boolean} true/false of validation result
693
708
  */
694
709
  isStateIdValid(str) {
695
-
696
- if (!str || typeof str !== 'string') return false; // String?
697
- if(str.length < 5) return false; // If string length < 5 chars (minimum state length is 5, assuming this is a valid state: 'x.0.a'
698
- if (adapter.x.constants.forbiddenStatePaths.test(str)) return false; // If forbidden chars
699
- if (!/\.\d+\./.test(str)) return false; // If no instance number with a leading and trailing dot "."
700
- if (str.startsWith(' ') || str.endsWith(' ')) return false; // If spaces at beginning or end
701
- if (str.startsWith('.') || str.endsWith('.')) return false; // If dots at beginning or end
710
+ if (!str || typeof str !== 'string') {
711
+ return false;
712
+ } // String?
713
+ if (str.length < 5) {
714
+ return false;
715
+ } // If string length < 5 chars (minimum state length is 5, assuming this is a valid state: 'x.0.a'
716
+ if (adapter.x.constants.forbiddenStatePaths.test(str)) {
717
+ return false;
718
+ } // If forbidden chars
719
+ if (!/\.\d+\./.test(str)) {
720
+ return false;
721
+ } // If no instance number with a leading and trailing dot "."
722
+ if (str.startsWith(' ') || str.endsWith(' ')) {
723
+ return false;
724
+ } // If spaces at beginning or end
725
+ if (str.startsWith('.') || str.endsWith('.')) {
726
+ return false;
727
+ } // If dots at beginning or end
702
728
  return true; // All passed
703
729
  },
704
730
 
705
731
  /**
706
732
  * Logs information to ioBroker log.
707
733
  * If "extendedInfoLog" in adapter settings is disabled, log level is debug.
734
+ *
708
735
  * @param {string} msg The log message
709
736
  */
710
737
  logExtendedInfo(msg) {
711
- if(adapter.config.extendedInfoLog) {
738
+ if (adapter.config.extendedInfoLog) {
712
739
  adapter.log.info(msg);
713
740
  } else {
714
741
  adapter.log.debug(msg);
@@ -719,11 +746,11 @@ module.exports = function (adapter) {
719
746
  * Error Message to Log. Handles error object being provided.
720
747
  *
721
748
  * @param {string} msg - (intro) message of the error
722
- * @param {*} [error=undefined] - Optional: Error object or string
723
- * @param {boolean} [returnMsg=false] - Optional: If true, it will not log an error, but return the msg as string
724
- * @return {void|string}
749
+ * @param {*} [error] - Optional: Error object or string
750
+ * @param {boolean} [returnMsg] - Optional: If true, it will not log an error, but return the msg as string
751
+ * @returns {void|string}
725
752
  */
726
- dumpError(msg, error=undefined, returnMsg=false) {
753
+ dumpError(msg, error = undefined, returnMsg = false) {
727
754
  let finalMsg = 'undefined';
728
755
  if (!error) {
729
756
  finalMsg = msg;
@@ -740,15 +767,12 @@ module.exports = function (adapter) {
740
767
  finalMsg = `${msg} – ${error}`;
741
768
  } else {
742
769
  finalMsg = `[dumpError()] : wrong error argument: ${JSON.stringify(error)}`;
743
-
744
770
  }
745
771
  }
746
772
  if (returnMsg) {
747
773
  return finalMsg;
748
- } else {
749
- adapter.log.error(finalMsg);
750
774
  }
751
-
775
+ adapter.log.error(finalMsg);
752
776
  },
753
777
 
754
778
  /**
@@ -756,87 +780,81 @@ module.exports = function (adapter) {
756
780
  * Array, object, or string containing just white spaces or >'< or >"< or >[< or >]< is considered empty
757
781
  * 18-Jun-2020: added check for { and } to also catch empty objects.
758
782
  * 08-Sep-2019: added check for [ and ] to also catch arrays with empty strings.
783
+ *
759
784
  * @param {any} inputVar Input Array or String, Number, etc.
760
- * @return {boolean} True if it is undefined/null/empty, false if it contains value(s)
785
+ * @returns {boolean} True if it is undefined/null/empty, false if it contains value(s)
761
786
  */
762
787
  isLikeEmpty(inputVar) {
763
788
  if (typeof inputVar !== 'undefined' && inputVar !== null) {
764
789
  let strTemp = JSON.stringify(inputVar);
765
790
  strTemp = strTemp.replace(/\s+/g, ''); // remove all white spaces
766
- strTemp = strTemp.replace(/"+/g, ''); // remove all >"<
767
- strTemp = strTemp.replace(/'+/g, ''); // remove all >'<
768
- strTemp = strTemp.replace(/\[+/g, ''); // remove all >[<
769
- strTemp = strTemp.replace(/\]+/g, ''); // remove all >]<
770
- strTemp = strTemp.replace(/\{+/g, ''); // remove all >{<
771
- strTemp = strTemp.replace(/\}+/g, ''); // remove all >}<
791
+ strTemp = strTemp.replace(/"+/g, ''); // remove all >"<
792
+ strTemp = strTemp.replace(/'+/g, ''); // remove all >'<
793
+ strTemp = strTemp.replace(/\[+/g, ''); // remove all >[<
794
+ strTemp = strTemp.replace(/\]+/g, ''); // remove all >]<
795
+ strTemp = strTemp.replace(/\{+/g, ''); // remove all >{<
796
+ strTemp = strTemp.replace(/\}+/g, ''); // remove all >}<
772
797
  if (strTemp !== '') {
773
798
  return false;
774
- } else {
775
- return true;
776
799
  }
777
- } else {
778
800
  return true;
779
801
  }
802
+ return true;
780
803
  },
781
804
 
782
805
  /**
783
806
  * Checks whether variable is number
784
807
  * true: 5, '123'
785
808
  * false: '123abc', 'q345', null, undefined, false, ' '
809
+ *
786
810
  * @source https://stackoverflow.com/questions/1303646/check-whether-variable-is-number-or-string-in-javascript
787
811
  * @param {any} n Input variable to check
788
- * @return {boolean} true if number, false if not.
812
+ * @returns {boolean} true if number, false if not.
789
813
  */
790
814
  isNumber(n) {
791
815
  return /^-?[\d.]+(?:e-?\d+)?$/.test(n);
792
816
  },
793
817
 
818
+ /**
819
+ * true/false aus dem Vergleichswert in der Config (#170).
820
+ *
821
+ * @param {any} val
822
+ * @returns {{ok: boolean, value?: boolean}}
823
+ */
824
+ parseBooleanStateVal(val) {
825
+ return require('./boolean-value').parseBooleanStateVal(val);
826
+ },
827
+
828
+ /**
829
+ * Parse a comparator string like '< -200' or '>26,5'.
830
+ *
831
+ * @param {string} compStr
832
+ * @returns {{isComparator: boolean, operand?: string, compNum?: number}}
833
+ */
834
+ parseNumComparator(compStr) {
835
+ return require('./num-comparator').parseNumComparator(compStr);
836
+ },
794
837
 
795
838
  /**
796
- * Check a given number against a comparator string, like '>30', '<= 25', etc.
839
+ * Check a given number against a comparator string, like '>30', '<= 25', '< -200'.
840
+ *
797
841
  * @param {any} numToCheck - number to check against comparator
798
842
  * @param {string} compStr - comparator, like '>30', '<= 25'
799
- * @return {object} - Object like {isComparator:true, result:true} - isComparator: if compStr was recognized as comparator, result: true if matching, false if not
843
+ * @returns {object} - Object like {isComparator:true, result:true}
800
844
  */
801
845
  isNumComparatorMatching(numToCheck, compStr) {
802
- // Check for >=, <=, >, <, != leading a number, so like '>= 3', '<7'
803
- if (typeof compStr == 'string' && (typeof numToCheck == 'string' || typeof numToCheck == 'number')) {
804
- const matchComparator =compStr.match(/^(>=|<=|>|<|!=|<>)\s?(\d{1,})$/);
805
- if (matchComparator != null) {
806
- // String like ">= 30" found.
807
- const operand = matchComparator[1];
808
- const compNum = parseFloat(matchComparator[2]);
809
- if (operand == '>=' && Number(numToCheck) >= compNum) {
810
- return {isComparator:true, result:true};
811
- } else if (operand == '<=' && Number(numToCheck) <= compNum) {
812
- return {isComparator:true, result:true};
813
- } else if (operand == '>' && Number(numToCheck) > compNum) {
814
- return {isComparator:true, result:true};
815
- } else if (operand == '<' && Number(numToCheck) < compNum) {
816
- return {isComparator:true, result:true};
817
- } else if ((operand == '!=' || operand == '<>' ) && Number(numToCheck) != compNum) {
818
- return {isComparator:true, result:true};
819
- } else {
820
- return {isComparator:true, result:false};
821
- }
822
- } else {
823
- return {isComparator:false, result:false};
824
- }
825
-
826
- } else {
827
- return {isComparator:false, result:false};
828
- }
846
+ return require('./num-comparator').isNumComparatorMatching(numToCheck, compStr);
829
847
  },
830
848
 
831
-
832
849
  /**
833
850
  * Remove certain (forbidden) chars from a string
851
+ *
834
852
  * @param {string} str - The input string
835
853
  * @param {RegExp} regex - Regex of chars to be removed, like /[\][*,;'"`<>\\?]/g
836
- * @param {boolean} [cleanSpaces=false] - Optional: trim and remove replace multiple spaces with single space
837
- * @return {array} Array with two elements: [0]: the resulting string, [1]: message if str was altered or empty string if no changes applied
854
+ * @param {boolean} [cleanSpaces] - Optional: trim and remove replace multiple spaces with single space
855
+ * @returns {Array} Array with two elements: [0]: the resulting string, [1]: message if str was altered or empty string if no changes applied
838
856
  */
839
- strCharsRemove(str, regex, cleanSpaces=false) {
857
+ strCharsRemove(str, regex, cleanSpaces = false) {
840
858
  let correctedMsg = '';
841
859
  let result = str;
842
860
  if (result.match(regex)) {
@@ -858,46 +876,44 @@ module.exports = function (adapter) {
858
876
  return [result, correctedMsg];
859
877
  },
860
878
 
861
-
862
-
863
879
  /**
864
880
  * Remove Duplicates from Array
881
+ *
865
882
  * @source https://stackoverflow.com/questions/23237704/nodejs-how-to-remove-duplicates-from-array
866
- * @param {array} inputArray Array to process
867
- * @return {array} Array without duplicates.
883
+ * @param {Array} inputArray Array to process
884
+ * @returns {Array} Array without duplicates.
868
885
  */
869
886
  uniqueArray(inputArray) {
870
- return inputArray.filter(function(elem, pos) {
887
+ return inputArray.filter(function (elem, pos) {
871
888
  return inputArray.indexOf(elem) == pos;
872
889
  });
873
890
  },
874
891
 
875
-
876
892
  /**
877
893
  * Check if an array contains duplicate values
878
894
  * https://stackoverflow.com/a/34192063
879
895
  *
880
896
  * @param {*} myArray - The given array
881
- * @return {boolean} - true if it is unique, false otherwise.
897
+ * @returns {boolean} - true if it is unique, false otherwise.
882
898
  */
883
899
  isArrayUnique(myArray) {
884
900
  return myArray.length === new Set(myArray).size;
885
901
  },
886
902
 
887
903
  /**
888
- * Removing Array element(s) by input value.
889
- * @param {array} arr the input array
904
+ * Removing Array element(s) by input value.
905
+ *
906
+ * @param {Array} arr the input array
890
907
  * @param {string} valRemove the value to be removed
891
- * @param {boolean} [exact=true] OPTIONAL: default is true. if true, it must fully match. if false, it matches also if valRemove is part of element string
892
- * @return {array} the array without the element(s)
908
+ * @param {boolean} [exact] OPTIONAL: default is true. if true, it must fully match. if false, it matches also if valRemove is part of element string
909
+ * @returns {Array} the array without the element(s)
893
910
  */
894
- arrayRemoveElementByValue(arr, valRemove, exact=true) {
895
-
911
+ arrayRemoveElementByValue(arr, valRemove, exact = true) {
896
912
  const arrGiven = [...arr]; // copy array
897
913
 
898
- for ( let i = 0; i < arrGiven.length; i++){
914
+ for (let i = 0; i < arrGiven.length; i++) {
899
915
  if (exact) {
900
- if ( arrGiven[i] === valRemove) {
916
+ if (arrGiven[i] === valRemove) {
901
917
  arrGiven.splice(i, 1);
902
918
  i--;
903
919
  }
@@ -914,32 +930,31 @@ module.exports = function (adapter) {
914
930
  /**
915
931
  * Remove duplicates from an array of objects by key
916
932
  * https://stackoverflow.com/a/58437069
917
- *
918
- * @param {array} givenArray
933
+ *
934
+ * @param {Array} givenArray
919
935
  * @param {string} key key which value must be unique.
920
- * @param {boolean} [all=false] if true: unique by all properties of the object, if false: unique by just the key value
936
+ * @param {boolean} [all] if true: unique by all properties of the object, if false: unique by just the key value
921
937
  */
922
- uniqueArrayObjectByKey(givenArray, key, all=false) {
923
-
938
+ uniqueArrayObjectByKey(givenArray, key, all = false) {
924
939
  if (all) {
925
- return givenArray.filter((v,i,a)=>a.findIndex(t=>(JSON.stringify(t) === JSON.stringify(v)))===i);
926
- } else {
927
- return givenArray.filter((v,i,a)=>a.findIndex(t=>(t[key] === v[key]))===i);
940
+ return givenArray.filter((v, i, a) => a.findIndex(t => JSON.stringify(t) === JSON.stringify(v)) === i);
928
941
  }
929
-
942
+ return givenArray.filter((v, i, a) => a.findIndex(t => t[key] === v[key]) === i);
930
943
  },
931
944
 
932
945
  /**
933
946
  * Converts string like 'val:'abc', delay:500' to a JSON object
934
947
  * If keys 'val' or 'delay' are not existing, return {val: query}
948
+ *
935
949
  * @param {string} query
936
- * @param {array} keys - array of strings like ['val', 'delay']
937
- * @param {boolean} [flat=false]
938
- * @return {object|null} JSON object, or null if query is empty or errors
950
+ * @param {Array} keys - array of strings like ['val', 'delay']
951
+ * @param {boolean} [flat]
952
+ * @returns {object|null} JSON object, or null if query is empty or errors
939
953
  */
940
- convertStrToJson(query, keys, flat=false) {
941
-
942
- if (this.isLikeEmpty(query)) return null;
954
+ convertStrToJson(query, keys, flat = false) {
955
+ if (this.isLikeEmpty(query)) {
956
+ return null;
957
+ }
943
958
 
944
959
  let keyFound = false;
945
960
  for (const lpKey of keys) {
@@ -950,8 +965,7 @@ module.exports = function (adapter) {
950
965
  }
951
966
  }
952
967
 
953
- if ( keyFound ) {
954
-
968
+ if (keyFound) {
955
969
  const arrayOfKeyValues = query.split(',');
956
970
  const modifiedArray = [];
957
971
  for (const lpEntryStr of arrayOfKeyValues) {
@@ -964,35 +978,30 @@ module.exports = function (adapter) {
964
978
 
965
979
  if (flat) {
966
980
  return modifiedArray.toString();
967
- } else {
968
- try {
969
- return JSON.parse('{' + modifiedArray.toString() + '}');
970
- } catch (error) {
971
- adapter.log.error('[convertStrToJson())]: Could not convert given query to JSON object');
972
- return null;
973
- }
981
+ }
982
+ try {
983
+ return JSON.parse(`{${modifiedArray.toString()}}`);
984
+ } catch {
985
+ adapter.log.error('[convertStrToJson())]: Could not convert given query to JSON object');
986
+ return null;
974
987
  }
975
988
  } else {
976
989
  const newVal = this.strCharsRemove(query, /['"`]/g, true)[0];
977
990
  if (flat) {
978
991
  return newVal;
979
- } else {
980
- return {val: newVal};
981
992
  }
993
+ return { val: newVal };
982
994
  }
983
-
984
995
  },
985
996
 
986
-
987
997
  /**
988
998
  * Rounds the given timestamp to the nearest minute
989
999
  * Inspired by https://github.com/date-fns/date-fns/blob/master/src/roundToNearestMinutes/index.js
990
1000
  *
991
1001
  * @param {number} ts a timestamp
992
- * @return {number} the resulting timestamp
1002
+ * @returns {number} the resulting timestamp
993
1003
  */
994
1004
  roundTimeStampToNearestMinute(ts) {
995
-
996
1005
  const date = new Date(ts);
997
1006
  const minutes = date.getMinutes() + date.getSeconds() / 60;
998
1007
  const roundedMinutes = Math.floor(minutes);
@@ -1003,68 +1012,66 @@ module.exports = function (adapter) {
1003
1012
  date.getMonth(),
1004
1013
  date.getDate(),
1005
1014
  date.getHours(),
1006
- roundedMinutes + addedMinutes
1015
+ roundedMinutes + addedMinutes,
1007
1016
  ).getTime();
1008
-
1009
1017
  },
1010
1018
 
1011
1019
  /**
1012
1020
  * Validate URL
1021
+ *
1013
1022
  * @param {string} url - given URL as string
1014
- * @param {boolean} [clean=false] - removes white spaces if true
1015
- * @param {boolean} [returnUrl=false] - if false: returns boolean, if true: url if successful, null if not
1016
- * @return {boolean|string|null}
1023
+ * @param {boolean} [clean] - removes white spaces if true
1024
+ * @param {boolean} [returnUrl] - if false: returns boolean, if true: url if successful, null if not
1025
+ * @returns {boolean|string|null}
1017
1026
  */
1018
- validateURL(url, clean=false, returnUrl=false) {
1019
- if(clean) url = url.replace(/\s/g,''); // remove all white spaces
1027
+ validateURL(url, clean = false, returnUrl = false) {
1028
+ if (clean) {
1029
+ url = url.replace(/\s/g, '');
1030
+ } // remove all white spaces
1031
+ // eslint-disable-next-line no-useless-escape -- same regex as before (string, no logic change)
1020
1032
  const urlRegexStr = `^(https?)://([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+.?([a-zA-Z]))(:[0-9]+)*(/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$`;
1021
1033
  const regex = new RegExp(urlRegexStr);
1022
1034
  const isUrlValid = url.length < 2083 && regex.test(url);
1023
1035
  if (returnUrl) {
1024
1036
  if (isUrlValid) {
1025
1037
  return url;
1026
- } else {
1027
- return null;
1028
1038
  }
1029
- } else {
1030
- return isUrlValid;
1039
+ return null;
1031
1040
  }
1041
+ return isUrlValid;
1032
1042
  },
1033
1043
 
1034
1044
  /**
1035
1045
  * Pad a number with leading zeros, like 7 => '007' if 3 places.
1046
+ *
1036
1047
  * @param {string|number} num Input number
1037
1048
  * @param {number} digits Number of digits
1038
- * @return {string} The result
1049
+ * @returns {string} The result
1039
1050
  */
1040
1051
  zeroPad(num, digits) {
1041
1052
  const zero = digits - num.toString().length + 1;
1042
- return Array(+(zero > 0 && zero)).join('0') + num;
1053
+ return Array(+(zero > 0 && zero)).join('0') + num;
1043
1054
  },
1044
1055
 
1045
1056
  /**
1046
1057
  * Check string against a forbidden chars regex
1047
1058
  * Mic-M
1048
- *
1059
+ *
1049
1060
  * @param {string} str - the input string
1050
1061
  * @param {RegExp} regex - the regular expression, like: /[\][*,;'"`<>\\?]/g
1051
- * @return {boolean|string} - returns false if nothing found, or all forbidden chars found space separated as string, like '[ ] , ? *'
1062
+ * @returns {boolean|string} - returns false if nothing found, or all forbidden chars found space separated as string, like '[ ] , ? *'
1052
1063
  */
1053
1064
  forbiddenCharsInStr(str, regex) {
1054
-
1055
1065
  let result = str.match(regex);
1056
1066
  if (result) {
1057
1067
  result = this.uniqueArray(result);
1058
1068
  let returnStr = '';
1059
1069
  for (const lpCharForbidden of result) {
1060
- returnStr = returnStr + ' ' + lpCharForbidden;
1070
+ returnStr = `${returnStr} ${lpCharForbidden}`;
1061
1071
  }
1062
- return (returnStr.trim());
1063
- } else {
1064
- return false;
1072
+ return returnStr.trim();
1065
1073
  }
1066
-
1074
+ return false;
1067
1075
  },
1068
-
1069
1076
  };
1070
- };
1077
+ };