iobroker.smartcontrol 1.2.1 → 1.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/ISSUE_TEMPLATE/BugReport.md +36 -36
- package/.github/ISSUE_TEMPLATE/Enhancement.md +19 -19
- package/.github/auto-merge.yml +17 -17
- package/.github/workflows/dependabot-auto-merge.yml +22 -22
- package/.github/workflows/npmpublish.yml +30 -30
- package/.github/workflows/test-and-release.yml +92 -129
- package/.releaseconfig.json +3 -0
- package/LICENSE +21 -21
- package/README.md +374 -406
- package/admin/doc-md/readme.txt +6 -6
- package/admin/doc-md/start_de.md +124 -124
- package/admin/doc-md/start_en.md +126 -126
- package/admin/doc-md/table-conditions_de.md +10 -10
- package/admin/doc-md/table-conditions_en.md +10 -10
- package/admin/doc-md/table-execution_de.md +12 -12
- package/admin/doc-md/table-execution_en.md +12 -12
- package/admin/doc-md/table-target-devices_de.md +18 -18
- package/admin/doc-md/table-target-devices_en.md +21 -21
- package/admin/doc-md/table-target-enums_de.md +13 -13
- package/admin/doc-md/table-target-enums_en.md +15 -15
- package/admin/doc-md/table-target-url_de.md +29 -29
- package/admin/doc-md/table-target-url_en.md +27 -27
- package/admin/doc-md/table-trigger-devices_de.md +12 -12
- package/admin/doc-md/table-trigger-devices_en.md +10 -10
- package/admin/doc-md/table-trigger-motion_de.md +23 -23
- package/admin/doc-md/table-trigger-motion_en.md +24 -24
- package/admin/doc-md/table-trigger-times_de.md +13 -13
- package/admin/doc-md/table-trigger-times_en.md +11 -11
- package/admin/doc-md/table-zones_de.md +14 -14
- package/admin/doc-md/table-zones_en.md +13 -13
- package/admin/doc-md/table-zones_select-targets_de.md +18 -18
- package/admin/doc-md/table-zones_select-targets_en.md +18 -18
- package/admin/index_m.js +1 -1
- package/admin/zero-md/webcomponents-loader.min.js +8 -8
- package/admin/zero-md/zero-md.min.js.js +8 -8
- package/io-package.json +461 -448
- package/lib/adapter-config.d.ts +15 -15
- package/lib/constants.js +128 -128
- package/lib/helper.js +1069 -1069
- package/lib/tools.js +93 -93
- package/lib/trigger-class.js +964 -964
- package/main.js +1 -1
- package/main.test.js +30 -30
- package/package.json +73 -70
package/lib/helper.js
CHANGED
|
@@ -1,1070 +1,1070 @@
|
|
|
1
|
-
/* eslint-disable no-irregular-whitespace */
|
|
2
|
-
'use strict';
|
|
3
|
-
|
|
4
|
-
/**
|
|
5
|
-
* @desc Generic Helper Functions
|
|
6
|
-
* @author Mic-M <https://github.com/Mic-M/ioBroker.smartcontrol>
|
|
7
|
-
* @license MIT
|
|
8
|
-
*/
|
|
9
|
-
module.exports = function (adapter) {
|
|
10
|
-
|
|
11
|
-
return {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
* Create States, either under adapter instance or anywhere.
|
|
16
|
-
* 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 }
|
|
19
|
-
* 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.
|
|
21
|
-
* WARN: use the "true" flag carefully!
|
|
22
|
-
* @return {Promise<boolean>} false if errors caught, otherwise true.
|
|
23
|
-
*/
|
|
24
|
-
async asyncCreateStates(statesToCreate, isForeign=false) {
|
|
25
|
-
|
|
26
|
-
try {
|
|
27
|
-
|
|
28
|
-
// Convert to array if it is an object, since we allow both
|
|
29
|
-
if(!Array.isArray(statesToCreate)) statesToCreate = [statesToCreate];
|
|
30
|
-
|
|
31
|
-
for (const lpStateToCreate of statesToCreate) {
|
|
32
|
-
|
|
33
|
-
// Check parameters
|
|
34
|
-
if (!lpStateToCreate.statePath || !lpStateToCreate.commonObject) {
|
|
35
|
-
adapter.log.error(`asyncCreateForeignStates(): invalid parameter provided to function`);
|
|
36
|
-
return false;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
// Create new state.
|
|
40
|
-
// 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: {}});
|
|
45
|
-
} else {
|
|
46
|
-
// State already exists.
|
|
47
|
-
continue;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
// Set default value
|
|
51
|
-
const def = lpStateToCreate.commonObject.def;
|
|
52
|
-
const type = lpStateToCreate.commonObject.type;
|
|
53
|
-
let initialDefault;
|
|
54
|
-
if (def !== undefined) {
|
|
55
|
-
initialDefault = def;
|
|
56
|
-
} 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
|
-
}
|
|
63
|
-
if (isForeign) {
|
|
64
|
-
await adapter.setForeignStateAsync(lpStateToCreate.statePath, initialDefault, false);
|
|
65
|
-
} else {
|
|
66
|
-
await adapter.setStateAsync(lpStateToCreate.statePath, initialDefault, false);
|
|
67
|
-
}
|
|
68
|
-
adapter.log.debug(`State '${lpStateToCreate.statePath}' created.`);
|
|
69
|
-
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
return true;
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
} catch (error) {
|
|
76
|
-
this.dumpError('[asyncCreateForeignStates()]', error);
|
|
77
|
-
return false;
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
},
|
|
81
|
-
|
|
82
|
-
/**
|
|
83
|
-
* Check if an ioBroker object exists.
|
|
84
|
-
* @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>}
|
|
87
|
-
*/
|
|
88
|
-
async asyncObjectExists (str, isForeign=false) {
|
|
89
|
-
|
|
90
|
-
try {
|
|
91
|
-
let ret;
|
|
92
|
-
if (isForeign) {
|
|
93
|
-
ret = await adapter.getForeignObjectAsync(str);
|
|
94
|
-
} else {
|
|
95
|
-
ret = await adapter.getObjectAsync(str);
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
if (ret == undefined) {
|
|
99
|
-
return false;
|
|
100
|
-
} else {
|
|
101
|
-
return true;
|
|
102
|
-
}
|
|
103
|
-
} catch (error) {
|
|
104
|
-
this.dumpError('[asyncObjectExists()]', error);
|
|
105
|
-
return false;
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
},
|
|
109
|
-
|
|
110
|
-
/**
|
|
111
|
-
* Get foreign state value
|
|
112
|
-
*
|
|
113
|
-
* @param {string} statePath - Full path to state, like 0_userdata.0.other.isSummer
|
|
114
|
-
* @return {Promise<*>} - State value, or null if error
|
|
115
|
-
*/
|
|
116
|
-
async asyncGetForeignStateValue(statePath) {
|
|
117
|
-
try {
|
|
118
|
-
const stateObject = await this.asyncGetForeignState(statePath);
|
|
119
|
-
if (stateObject == null) return null; // error thrown already in asyncGetForeignState()
|
|
120
|
-
return stateObject.val;
|
|
121
|
-
} catch (error) {
|
|
122
|
-
this.dumpError(`[asyncGetForeignStateValue]`, error);
|
|
123
|
-
return null;
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
},
|
|
127
|
-
|
|
128
|
-
/**
|
|
129
|
-
* Get foreign state
|
|
130
|
-
*
|
|
131
|
-
* @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
|
|
133
|
-
*/
|
|
134
|
-
async asyncGetForeignState(statePath) {
|
|
135
|
-
|
|
136
|
-
try {
|
|
137
|
-
// Check state existence
|
|
138
|
-
const stateObject = await adapter.getForeignObjectAsync(statePath);
|
|
139
|
-
|
|
140
|
-
if (!stateObject) {
|
|
141
|
-
throw(`State '${statePath}' does not exist.`);
|
|
142
|
-
} else {
|
|
143
|
-
// Get state value, so like: {val: false, ack: true, ts: 1591117034451, …}
|
|
144
|
-
const stateValueObject = await adapter.getForeignStateAsync(statePath);
|
|
145
|
-
if (! this.isLikeEmpty(stateValueObject)) {
|
|
146
|
-
return stateValueObject;
|
|
147
|
-
} else {
|
|
148
|
-
throw(`Unable to retrieve info from state '${statePath}'.`);
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
} catch (error) {
|
|
152
|
-
this.dumpError(`[asyncGetForeignState]`, error);
|
|
153
|
-
return null;
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
},
|
|
157
|
-
|
|
158
|
-
/**
|
|
159
|
-
* Convert date/time to a local ISO string
|
|
160
|
-
* This function is needed since toISOString() uses UTC +0 (Zulu) as time zone.
|
|
161
|
-
* https://stackoverflow.com/questions/10830357/
|
|
162
|
-
* Mic-M, 04/Apr/2020
|
|
163
|
-
* @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)
|
|
165
|
-
*/
|
|
166
|
-
dateToLocalIsoString(date) {
|
|
167
|
-
const timezoneOffset = date.getTimezoneOffset() * 60000; //offset in milliseconds
|
|
168
|
-
return (new Date(date.getTime() - timezoneOffset)).toISOString().slice(0, -1);
|
|
169
|
-
},
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
/**
|
|
175
|
-
* For given object of enum objects, get the names and associated ids.
|
|
176
|
-
* enumObj.common.name can be either string like 'Living room' or {en:'Living room', de:'Wohnzimmer', ...}
|
|
177
|
-
* @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
|
|
180
|
-
*/
|
|
181
|
-
enumsGetNamesAndIds(enumObj, allLanguages=false) {
|
|
182
|
-
|
|
183
|
-
try {
|
|
184
|
-
|
|
185
|
-
const result = {};
|
|
186
|
-
for (const id in enumObj) { // id = like 'enum.rooms.bathroom'
|
|
187
|
-
const nameObj = enumObj[id].common.name; // either string like 'Living room' or {en:'Living room', de:'Wohnzimmer', ...}
|
|
188
|
-
if (typeof nameObj === 'string') {
|
|
189
|
-
result[nameObj] = id;
|
|
190
|
-
} else if (typeof nameObj === 'object') {
|
|
191
|
-
if (allLanguages) {
|
|
192
|
-
for (const lpLang in nameObj) {
|
|
193
|
-
result[nameObj[lpLang]] = id;
|
|
194
|
-
}
|
|
195
|
-
} else {
|
|
196
|
-
result[nameObj[adapter.x.systemConfig.language]] = id;
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
} else {
|
|
200
|
-
adapter.log.warn(`Getting enum room name for '${id}': type for name must be string or object, but is '${typeof nameObj}'.`);
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
if (!this.isLikeEmpty(result)) {
|
|
205
|
-
return result;
|
|
206
|
-
} else {
|
|
207
|
-
return null;
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
} catch (error) {
|
|
211
|
-
this.dumpError('[enumsGetNamesAndIds]', error);
|
|
212
|
-
return null;
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
},
|
|
216
|
-
|
|
217
|
-
/**
|
|
218
|
-
* Restart the adapter instance.
|
|
219
|
-
* Source: https://github.com/foxriver76/ioBroker.xbox/blob/275e03635d657e7b18762166b4feca96fc4b1b1c/main.js#L630
|
|
220
|
-
*/
|
|
221
|
-
/*
|
|
222
|
-
async asyncRestartAdapter() {
|
|
223
|
-
|
|
224
|
-
try {
|
|
225
|
-
|
|
226
|
-
const resultObject = await adapter.getForeignObjectAsync('system.adapter.' + adapter.namespace);
|
|
227
|
-
if (resultObject) {
|
|
228
|
-
await adapter.setForeignObjectAsync('system.adapter.' + adapter.namespace, resultObject);
|
|
229
|
-
return;
|
|
230
|
-
} else {
|
|
231
|
-
adapter.log.error(`[asyncRestartAdapter()]: getForeignObjectAsync() No object provided from function.`);
|
|
232
|
-
return;
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
} catch (error) {
|
|
236
|
-
adapter.log.error(`[asyncRestartAdapter()]: ${error}`);
|
|
237
|
-
return;
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
},
|
|
241
|
-
*/
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
/**
|
|
247
|
-
* Verify acknowledge (ack) once a state was changed.
|
|
248
|
-
*
|
|
249
|
-
* In General: Any state changes of states will be ignored, if acknowledge (ack) = false.
|
|
250
|
-
* The reason is that adapters confirm states by the acknowledge "ack" flag (setting to true).
|
|
251
|
-
* Reference: https://forum.iobroker.net/post/448606
|
|
252
|
-
*
|
|
253
|
-
* 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
|
-
* 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
|
|
256
|
-
* own states in the object main tree, like "Messwerte.0". https://forum.iobroker.net/post/461189
|
|
257
|
-
*
|
|
258
|
-
* @param {string} statePath - State Path
|
|
259
|
-
* @param {ioBroker.State|null|undefined} stateObject - State object
|
|
260
|
-
* @return {Promise<object>} {passing: false; msg:'some message'}
|
|
261
|
-
* if state change shall be ignored due to the ack (or error occurred), otherwise true.
|
|
262
|
-
*
|
|
263
|
-
*/
|
|
264
|
-
async isAckPassing(statePath, stateObject) {
|
|
265
|
-
|
|
266
|
-
try {
|
|
267
|
-
|
|
268
|
-
if (!stateObject || !statePath)
|
|
269
|
-
return {passing:false, msg:`Unexpected error: isAckPassing() was no valid statePath or stateObject provided.`};
|
|
270
|
-
|
|
271
|
-
const namespace = `${statePath.split('.')[0]}.${statePath.split('.')[1]}`; // like sonos.1
|
|
272
|
-
|
|
273
|
-
// For any states under this adapter instance (so )smartcontrol.x), we require ack = false;
|
|
274
|
-
// 22-Jul-2020: we allow different adapter instances as well.
|
|
275
|
-
// if (statePath.startsWith(`${adapter.namespace}.`)) {
|
|
276
|
-
if (statePath.match(/^smartcontrol.\d+./)) {
|
|
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`};
|
|
281
|
-
}
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
// Handle User States
|
|
285
|
-
let isUserState = false;
|
|
286
|
-
if (statePath.startsWith('javascript.') || statePath.startsWith('0_userdata.0') || statePath.startsWith('alias.')) isUserState = true;
|
|
287
|
-
|
|
288
|
-
if (!isUserState) {
|
|
289
|
-
// Check if state is under a "real" adapter namespace.
|
|
290
|
-
const isRealAdapter = await adapter.getForeignObjectAsync(`system.adapter.${namespace}`);
|
|
291
|
-
if (!isRealAdapter) isUserState = true;
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
if (isUserState) {
|
|
295
|
-
|
|
296
|
-
if (!adapter.config.triggerStatesAck || adapter.config.triggerStatesAck == 'false') {
|
|
297
|
-
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`};
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
} else if (adapter.config.triggerStatesAck == 'true') {
|
|
304
|
-
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`};
|
|
308
|
-
}
|
|
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`};
|
|
320
|
-
}
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
} catch (error) {
|
|
324
|
-
this.dumpError('[isAckPassing()]', error);
|
|
325
|
-
return {passing:false, msg:`Unexpected error occurred in isAckPassing()`};
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
},
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
/**
|
|
332
|
-
* 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
|
-
*
|
|
336
|
-
* @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.
|
|
338
|
-
*/
|
|
339
|
-
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
|
-
},
|
|
353
|
-
|
|
354
|
-
/**
|
|
355
|
-
* Get the timestamp of an astro name.
|
|
356
|
-
*
|
|
357
|
-
* @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
|
-
*/
|
|
361
|
-
getAstroNameTs(astroName, offsetMinutes=0) {
|
|
362
|
-
|
|
363
|
-
try {
|
|
364
|
-
let ts = adapter.x.mSuncalc.getTimes(new Date(), adapter.x.systemConfig.latitude, adapter.x.systemConfig.longitude)[astroName];
|
|
365
|
-
if (!ts || ts.getTime().toString() === 'NaN') {
|
|
366
|
-
// Fix night / nightEnd per adapter options.
|
|
367
|
-
// In northern areas is no night/nightEnd provided in the Summer.
|
|
368
|
-
// 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
|
|
372
|
-
switch (astroName) {
|
|
373
|
-
case 'night':
|
|
374
|
-
adapter.log.debug(`[getAstroNameTs] No time found for [${astroName}], so we set 00:00 as fallback per adapter config.`);
|
|
375
|
-
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
|
|
379
|
-
}
|
|
380
|
-
} else {
|
|
381
|
-
adapter.log.warn(`[getAstroNameTs] No time found for [${astroName}].`);
|
|
382
|
-
return 0;
|
|
383
|
-
}
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
ts = this.roundTimeStampToNearestMinute(ts);
|
|
387
|
-
ts = ts + (offsetMinutes * 60 * 1000);
|
|
388
|
-
return ts;
|
|
389
|
-
} catch (error) {
|
|
390
|
-
this.dumpError('[getAstroNameTs()]', error);
|
|
391
|
-
return 0;
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
},
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
/**
|
|
398
|
-
* Get the time stamp of a time string, like '23:30', 'goldenHourEnd', or 'goldenHourEnd+30'
|
|
399
|
-
* Supports times like 'h:ss'/'hh:ss', and also astro names.
|
|
400
|
-
* Astro names can also have an additional offset in minutes, so like "sunriseEnd-40" or "sunriseEnd+120".
|
|
401
|
-
*
|
|
402
|
-
* @param {string} input the input string
|
|
403
|
-
* @param {boolean} [getFullResult=false] if false: returns true if a valid time provided, and false if not.
|
|
404
|
-
* if true: Empty object if nothing found, or object with details.
|
|
405
|
-
* @return {boolean|object} Return value
|
|
406
|
-
*/
|
|
407
|
-
getTimeInfoFromAstroString(input, getFullResult=false) {
|
|
408
|
-
|
|
409
|
-
const currentDateTime = new Date(); // Date object of current date/time
|
|
410
|
-
|
|
411
|
-
input = input.replace(/\s/g,''); // remove all white spaces
|
|
412
|
-
|
|
413
|
-
const returnObject = {
|
|
414
|
-
full: input,
|
|
415
|
-
timestamp: 0,
|
|
416
|
-
hoursMins: '', // like '19:35'
|
|
417
|
-
isAstro: false,
|
|
418
|
-
astroName: '',
|
|
419
|
-
astroHasOffset: false,
|
|
420
|
-
astroOffsetMinutes: 0,
|
|
421
|
-
};
|
|
422
|
-
|
|
423
|
-
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})$/);
|
|
426
|
-
|
|
427
|
-
if (matchTime != null) {
|
|
428
|
-
// No Astro.
|
|
429
|
-
// Time like "19:35" found. Convert to timestamp by using current date
|
|
430
|
-
|
|
431
|
-
const hour = parseInt(matchTime[1]);
|
|
432
|
-
const min = parseInt(matchTime[3]);
|
|
433
|
-
|
|
434
|
-
if ( (input != '24:00') && (hour < 0 || hour > 23 || min < 0 || min > 60 ) ) {
|
|
435
|
-
returnObject.full = '';
|
|
436
|
-
} else {
|
|
437
|
-
|
|
438
|
-
returnObject.timestamp = new Date(
|
|
439
|
-
currentDateTime.getFullYear(),
|
|
440
|
-
currentDateTime.getMonth(),
|
|
441
|
-
currentDateTime.getDate(),
|
|
442
|
-
hour, // hours
|
|
443
|
-
min, // minutes
|
|
444
|
-
).getTime();
|
|
445
|
-
|
|
446
|
-
}
|
|
447
|
-
} else {
|
|
448
|
-
if (matchAstroName != null) {
|
|
449
|
-
// Astro found, with no offset
|
|
450
|
-
returnObject.astroName = input;
|
|
451
|
-
returnObject.isAstro = true;
|
|
452
|
-
returnObject.timestamp = this.getAstroNameTs(input);
|
|
453
|
-
} else if (matchAstroWithOffset != null) {
|
|
454
|
-
// Astro found, with offset
|
|
455
|
-
returnObject.isAstro = true;
|
|
456
|
-
returnObject.astroHasOffset = true;
|
|
457
|
-
returnObject.astroName = matchAstroWithOffset[1];
|
|
458
|
-
returnObject.astroOffsetMinutes = parseInt(matchAstroWithOffset[3]);
|
|
459
|
-
if(matchAstroWithOffset[2] == '-') {
|
|
460
|
-
returnObject.astroOffsetMinutes = returnObject.astroOffsetMinutes * (-1);
|
|
461
|
-
}
|
|
462
|
-
returnObject.timestamp = this.getAstroNameTs(returnObject.astroName, returnObject.astroOffsetMinutes);
|
|
463
|
-
} else {
|
|
464
|
-
// Nothing found
|
|
465
|
-
returnObject.full = '';
|
|
466
|
-
}
|
|
467
|
-
}
|
|
468
|
-
|
|
469
|
-
// Add hourMins string
|
|
470
|
-
returnObject.hoursMins = this.timestampToTimeString(returnObject.timestamp, true);
|
|
471
|
-
|
|
472
|
-
// handle '24:00'. We add a full day.
|
|
473
|
-
if (input == '24:00') {
|
|
474
|
-
returnObject.timestamp = returnObject.timestamp + +1000*60*60*24;
|
|
475
|
-
returnObject.hoursMins = '24:00';
|
|
476
|
-
}
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
if (!getFullResult) {
|
|
480
|
-
if (!returnObject.full) {
|
|
481
|
-
return false;
|
|
482
|
-
} else {
|
|
483
|
-
return true;
|
|
484
|
-
}
|
|
485
|
-
} else {
|
|
486
|
-
return returnObject;
|
|
487
|
-
}
|
|
488
|
-
|
|
489
|
-
},
|
|
490
|
-
|
|
491
|
-
/**
|
|
492
|
-
* Converts a given timestamp into European time. E.g. '9:03pm and 45 seconds' -> '21:03:45'
|
|
493
|
-
* @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
|
|
496
|
-
*/
|
|
497
|
-
timestampToTimeString(ts, noSeconds=false) {
|
|
498
|
-
|
|
499
|
-
if(noSeconds) ts = this.roundTimeStampToNearestMinute(ts);
|
|
500
|
-
const inputDate = new Date(ts);
|
|
501
|
-
|
|
502
|
-
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);
|
|
506
|
-
}
|
|
507
|
-
|
|
508
|
-
},
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
/**
|
|
512
|
-
* Checks if time of '08:30' is between '23:00' and '09:00'.
|
|
513
|
-
* Source/inspired by: https://stackoverflow.com/a/24577309
|
|
514
|
-
*
|
|
515
|
-
* @param {string} start - start string, like: '23:00', '07:30', 9:15'
|
|
516
|
-
* @param {string} end - end string, like: '08:15', '17:23'
|
|
517
|
-
* @param {string} check - to check, like: '17:25', '9:30'
|
|
518
|
-
* @return {boolean} true if in between, false if not
|
|
519
|
-
*
|
|
520
|
-
*/
|
|
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));
|
|
527
|
-
};
|
|
528
|
-
|
|
529
|
-
function getTimeObj (timeString) {
|
|
530
|
-
const t = timeString.split(':');
|
|
531
|
-
const returnObject = {};
|
|
532
|
-
returnObject.hour = parseInt(t[0]);
|
|
533
|
-
returnObject.minutes = parseInt(t[1]);
|
|
534
|
-
returnObject.isGreaterThan = function(other) {
|
|
535
|
-
return (returnObject.hour > other.hour) || (returnObject.hour === other.hour) && (returnObject.minutes > other.minutes);
|
|
536
|
-
};
|
|
537
|
-
return returnObject;
|
|
538
|
-
}
|
|
539
|
-
|
|
540
|
-
return timeIsBetween(getTimeObj(start), getTimeObj(end), getTimeObj(check));
|
|
541
|
-
|
|
542
|
-
},
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
/**
|
|
546
|
-
* Gets the time left of 'const xxx = setTimeout()', where xxx is the timer id.
|
|
547
|
-
*
|
|
548
|
-
* @author Mic-M <https://github.com/Mic-M/>
|
|
549
|
-
* @version 0.1 (30 June 2020)
|
|
550
|
-
*
|
|
551
|
-
* @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.
|
|
553
|
-
* To convert ms to seconds, simply use: (timeLeft / 1000).toFixed(0) - where timeLeft is the return value of the function.
|
|
554
|
-
*
|
|
555
|
-
*/
|
|
556
|
-
getTimeoutTimeLeft(timerId) {
|
|
557
|
-
|
|
558
|
-
try {
|
|
559
|
-
|
|
560
|
-
// Return -1 if timer object is undefined/null or if timer is not running
|
|
561
|
-
if (!timerId || timerId._destroyed) return -1;
|
|
562
|
-
|
|
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.
|
|
566
|
-
|
|
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
|
|
570
|
-
|
|
571
|
-
return remaining;
|
|
572
|
-
|
|
573
|
-
} catch (error) {
|
|
574
|
-
this.dumpError('[getTimeoutTimeLeft()]', error);
|
|
575
|
-
return -1;
|
|
576
|
-
}
|
|
577
|
-
|
|
578
|
-
},
|
|
579
|
-
|
|
580
|
-
/**
|
|
581
|
-
* Check if a timestamp is within two times.
|
|
582
|
-
*
|
|
583
|
-
* @param {number} tsGiven Timestamp to be checked if between start and end time
|
|
584
|
-
* @param {string} start Start time, like '18:30', or 'sunrise, or 'sunset+30'
|
|
585
|
-
* @param {string} end End time
|
|
586
|
-
* @param {string} ofWhat Typically zone name. For logging purposes only.
|
|
587
|
-
* @return {boolean} true if within times, and false if not.
|
|
588
|
-
*/
|
|
589
|
-
scheduleIsTimeStampWithinPeriod(tsGiven, start, end, ofWhat) {
|
|
590
|
-
|
|
591
|
-
try {
|
|
592
|
-
|
|
593
|
-
// First: convert potential Astro start time to "normal", so like 'sunset-30' to '18:30'
|
|
594
|
-
const givenFinal = this.timestampToTimeString(tsGiven, true);
|
|
595
|
-
const startFinal = this.getTimeInfoFromAstroString(start, true).hoursMins;
|
|
596
|
-
const endFinal = this.getTimeInfoFromAstroString(end, true).hoursMins;
|
|
597
|
-
|
|
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}'`);
|
|
601
|
-
|
|
602
|
-
// Next, check if given time is in between
|
|
603
|
-
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;
|
|
609
|
-
}
|
|
610
|
-
|
|
611
|
-
} catch (error) {
|
|
612
|
-
this.dumpError('[scheduleIsTimeStampWithinPeriod]', error);
|
|
613
|
-
return false;
|
|
614
|
-
}
|
|
615
|
-
},
|
|
616
|
-
|
|
617
|
-
/**
|
|
618
|
-
* Check if current day is within the mon-sun options as set in Execution table.
|
|
619
|
-
*
|
|
620
|
-
* @param {object} row The "Execution" table row which was triggered.
|
|
621
|
-
* @param {number} ts The timestamp to check.
|
|
622
|
-
* @param {string} ofWhat Typically zone name. For logging purposes only.
|
|
623
|
-
* @return {boolean} True if matching, false if not.
|
|
624
|
-
*/
|
|
625
|
-
scheduleIsWeekdayMatching(row, ts, ofWhat) {
|
|
626
|
-
const days = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
|
|
627
|
-
const lpWeekdayGiven = getWeekDayString(ts);
|
|
628
|
-
for (const lpDay of days) {
|
|
629
|
-
if (lpWeekdayGiven == null) {
|
|
630
|
-
adapter.log.error(`[scheduleIsWeekdayMatching()] Unable to calculate day of week for given timestamp '${ts}'`);
|
|
631
|
-
return false;
|
|
632
|
-
} else if ( (row[lpDay] == true) && (lpDay == lpWeekdayGiven) ) {
|
|
633
|
-
adapter.log.debug(`${ofWhat} - Current weekday '${lpWeekdayGiven}' *is* matching Execution table row.`);
|
|
634
|
-
return true;
|
|
635
|
-
}
|
|
636
|
-
}
|
|
637
|
-
// There was no hit, so we return false.
|
|
638
|
-
adapter.log.debug(`${ofWhat} - Current weekday '${lpWeekdayGiven}' is *not* matching Execution table row.`);
|
|
639
|
-
return false;
|
|
640
|
-
|
|
641
|
-
/**
|
|
642
|
-
* get the week day of a string.
|
|
643
|
-
* Source: https://stackoverflow.com/a/17964373
|
|
644
|
-
* @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.
|
|
646
|
-
*/
|
|
647
|
-
function getWeekDayString(date) {
|
|
648
|
-
const dayOfWeek = new Date(date).getDay();
|
|
649
|
-
return isNaN(dayOfWeek) ? null : ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'][dayOfWeek];
|
|
650
|
-
}
|
|
651
|
-
|
|
652
|
-
},
|
|
653
|
-
|
|
654
|
-
/**
|
|
655
|
-
* JSON Log to smartcontrol.x.info.log.<id>.json
|
|
656
|
-
* @param {string} id - e.g. 'zoneActivations' or 'switchedTargetDevices'
|
|
657
|
-
* @param {object} jsonObj - object to add, e.g. {zone:'xyz', targetDevice:'xyz'}
|
|
658
|
-
* @return {boolean} - false if errors caught, otherwise true.
|
|
659
|
-
*/
|
|
660
|
-
async setJsonLog(id, jsonObj) {
|
|
661
|
-
|
|
662
|
-
try {
|
|
663
|
-
|
|
664
|
-
let maxJsonLength = 0;
|
|
665
|
-
if (adapter.x.helper.isNumber(adapter.config.jsonMaxEntries)) {
|
|
666
|
-
maxJsonLength = parseInt(adapter.config.jsonMaxEntries);
|
|
667
|
-
}
|
|
668
|
-
if (maxJsonLength <= 0) return true;
|
|
669
|
-
|
|
670
|
-
if(!this.isLikeEmpty(adapter.x.jsonLogs[id])) {
|
|
671
|
-
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
|
|
673
|
-
} else {
|
|
674
|
-
adapter.x.jsonLogs[id] = [jsonObj]; // add as array
|
|
675
|
-
}
|
|
676
|
-
adapter.setState(`info.log.${id}.json`, { val: JSON.stringify(adapter.x.jsonLogs[id]), ack: true });
|
|
677
|
-
return true;
|
|
678
|
-
|
|
679
|
-
} catch (error) {
|
|
680
|
-
this.dumpError('[setJsonLog]', error);
|
|
681
|
-
return false;
|
|
682
|
-
}
|
|
683
|
-
|
|
684
|
-
},
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
/**
|
|
688
|
-
* Checks if an ioBroker state id (path) string is valid.
|
|
689
|
-
* NOTE: This does not verify if the state is existing. It does just some basic checks if the path looks good-
|
|
690
|
-
*
|
|
691
|
-
* @param {string} str String to validate
|
|
692
|
-
* @return {boolean} true/false of validation result
|
|
693
|
-
*/
|
|
694
|
-
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
|
|
702
|
-
return true; // All passed
|
|
703
|
-
},
|
|
704
|
-
|
|
705
|
-
/**
|
|
706
|
-
* Logs information to ioBroker log.
|
|
707
|
-
* If "extendedInfoLog" in adapter settings is disabled, log level is debug.
|
|
708
|
-
* @param {string} msg The log message
|
|
709
|
-
*/
|
|
710
|
-
logExtendedInfo(msg) {
|
|
711
|
-
if(adapter.config.extendedInfoLog) {
|
|
712
|
-
adapter.log.info(msg);
|
|
713
|
-
} else {
|
|
714
|
-
adapter.log.debug(msg);
|
|
715
|
-
}
|
|
716
|
-
},
|
|
717
|
-
|
|
718
|
-
/**
|
|
719
|
-
* Error Message to Log. Handles error object being provided.
|
|
720
|
-
*
|
|
721
|
-
* @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}
|
|
725
|
-
*/
|
|
726
|
-
dumpError(msg, error=undefined, returnMsg=false) {
|
|
727
|
-
let finalMsg = 'undefined';
|
|
728
|
-
if (!error) {
|
|
729
|
-
finalMsg = msg;
|
|
730
|
-
} else {
|
|
731
|
-
if (typeof error === 'object') {
|
|
732
|
-
if (error.stack) {
|
|
733
|
-
finalMsg = `${msg} – ${error.stack}`;
|
|
734
|
-
} else if (error.message) {
|
|
735
|
-
finalMsg = `${msg} – ${error.message}`;
|
|
736
|
-
} else {
|
|
737
|
-
finalMsg = `${msg} – ${JSON.stringify(error)}`;
|
|
738
|
-
}
|
|
739
|
-
} else if (typeof error === 'string') {
|
|
740
|
-
finalMsg = `${msg} – ${error}`;
|
|
741
|
-
} else {
|
|
742
|
-
finalMsg = `[dumpError()] : wrong error argument: ${JSON.stringify(error)}`;
|
|
743
|
-
|
|
744
|
-
}
|
|
745
|
-
}
|
|
746
|
-
if (returnMsg) {
|
|
747
|
-
return finalMsg;
|
|
748
|
-
} else {
|
|
749
|
-
adapter.log.error(finalMsg);
|
|
750
|
-
}
|
|
751
|
-
|
|
752
|
-
},
|
|
753
|
-
|
|
754
|
-
/**
|
|
755
|
-
* Checks if Array or String is not undefined, null or empty.
|
|
756
|
-
* Array, object, or string containing just white spaces or >'< or >"< or >[< or >]< is considered empty
|
|
757
|
-
* 18-Jun-2020: added check for { and } to also catch empty objects.
|
|
758
|
-
* 08-Sep-2019: added check for [ and ] to also catch arrays with empty strings.
|
|
759
|
-
* @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)
|
|
761
|
-
*/
|
|
762
|
-
isLikeEmpty(inputVar) {
|
|
763
|
-
if (typeof inputVar !== 'undefined' && inputVar !== null) {
|
|
764
|
-
let strTemp = JSON.stringify(inputVar);
|
|
765
|
-
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 >}<
|
|
772
|
-
if (strTemp !== '') {
|
|
773
|
-
return false;
|
|
774
|
-
} else {
|
|
775
|
-
return true;
|
|
776
|
-
}
|
|
777
|
-
} else {
|
|
778
|
-
return true;
|
|
779
|
-
}
|
|
780
|
-
},
|
|
781
|
-
|
|
782
|
-
/**
|
|
783
|
-
* Checks whether variable is number
|
|
784
|
-
* true: 5, '123'
|
|
785
|
-
* false: '123abc', 'q345', null, undefined, false, ' '
|
|
786
|
-
* @source https://stackoverflow.com/questions/1303646/check-whether-variable-is-number-or-string-in-javascript
|
|
787
|
-
* @param {any} n Input variable to check
|
|
788
|
-
* @return {boolean} true if number, false if not.
|
|
789
|
-
*/
|
|
790
|
-
isNumber(n) {
|
|
791
|
-
return /^-?[\d.]+(?:e-?\d+)?$/.test(n);
|
|
792
|
-
},
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
/**
|
|
796
|
-
* Check a given number against a comparator string, like '>30', '<= 25', etc.
|
|
797
|
-
* @param {any} numToCheck - number to check against comparator
|
|
798
|
-
* @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
|
|
800
|
-
*/
|
|
801
|
-
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
|
-
}
|
|
829
|
-
},
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
/**
|
|
833
|
-
* Remove certain (forbidden) chars from a string
|
|
834
|
-
* @param {string} str - The input string
|
|
835
|
-
* @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
|
|
838
|
-
*/
|
|
839
|
-
strCharsRemove(str, regex, cleanSpaces=false) {
|
|
840
|
-
let correctedMsg = '';
|
|
841
|
-
let result = str;
|
|
842
|
-
if (result.match(regex)) {
|
|
843
|
-
result = result.replace(regex, '');
|
|
844
|
-
correctedMsg += 'removed certain chars;';
|
|
845
|
-
}
|
|
846
|
-
if (cleanSpaces) {
|
|
847
|
-
// remove multiple spaces
|
|
848
|
-
if (result.match(/ +/g)) {
|
|
849
|
-
result = result.replace(/ +/g, ' '); // remove multiple spaces
|
|
850
|
-
correctedMsg += 'removed multiple spaces;';
|
|
851
|
-
}
|
|
852
|
-
// remove spaces from the start and end
|
|
853
|
-
if (result.startsWith(' ') || result.endsWith(' ')) {
|
|
854
|
-
result = result.trim();
|
|
855
|
-
correctedMsg += 'remove spaces from start and/or end;';
|
|
856
|
-
}
|
|
857
|
-
}
|
|
858
|
-
return [result, correctedMsg];
|
|
859
|
-
},
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
/**
|
|
864
|
-
* Remove Duplicates from Array
|
|
865
|
-
* @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.
|
|
868
|
-
*/
|
|
869
|
-
uniqueArray(inputArray) {
|
|
870
|
-
return inputArray.filter(function(elem, pos) {
|
|
871
|
-
return inputArray.indexOf(elem) == pos;
|
|
872
|
-
});
|
|
873
|
-
},
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
/**
|
|
877
|
-
* Check if an array contains duplicate values
|
|
878
|
-
* https://stackoverflow.com/a/34192063
|
|
879
|
-
*
|
|
880
|
-
* @param {*} myArray - The given array
|
|
881
|
-
* @return {boolean} - true if it is unique, false otherwise.
|
|
882
|
-
*/
|
|
883
|
-
isArrayUnique(myArray) {
|
|
884
|
-
return myArray.length === new Set(myArray).size;
|
|
885
|
-
},
|
|
886
|
-
|
|
887
|
-
/**
|
|
888
|
-
* Removing Array element(s) by input value.
|
|
889
|
-
* @param {array} arr the input array
|
|
890
|
-
* @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)
|
|
893
|
-
*/
|
|
894
|
-
arrayRemoveElementByValue(arr, valRemove, exact=true) {
|
|
895
|
-
|
|
896
|
-
const arrGiven = [...arr]; // copy array
|
|
897
|
-
|
|
898
|
-
for ( let i = 0; i < arrGiven.length; i++){
|
|
899
|
-
if (exact) {
|
|
900
|
-
if ( arrGiven[i] === valRemove) {
|
|
901
|
-
arrGiven.splice(i, 1);
|
|
902
|
-
i--;
|
|
903
|
-
}
|
|
904
|
-
} else {
|
|
905
|
-
if (arrGiven[i].indexOf(valRemove) != -1) {
|
|
906
|
-
arrGiven.splice(i, 1);
|
|
907
|
-
i--;
|
|
908
|
-
}
|
|
909
|
-
}
|
|
910
|
-
}
|
|
911
|
-
return arrGiven;
|
|
912
|
-
},
|
|
913
|
-
|
|
914
|
-
/**
|
|
915
|
-
* Remove duplicates from an array of objects by key
|
|
916
|
-
* https://stackoverflow.com/a/58437069
|
|
917
|
-
*
|
|
918
|
-
* @param {array} givenArray
|
|
919
|
-
* @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
|
|
921
|
-
*/
|
|
922
|
-
uniqueArrayObjectByKey(givenArray, key, all=false) {
|
|
923
|
-
|
|
924
|
-
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);
|
|
928
|
-
}
|
|
929
|
-
|
|
930
|
-
},
|
|
931
|
-
|
|
932
|
-
/**
|
|
933
|
-
* Converts string like 'val:'abc', delay:500' to a JSON object
|
|
934
|
-
* If keys 'val' or 'delay' are not existing, return {val: query}
|
|
935
|
-
* @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
|
|
939
|
-
*/
|
|
940
|
-
convertStrToJson(query, keys, flat=false) {
|
|
941
|
-
|
|
942
|
-
if (this.isLikeEmpty(query)) return null;
|
|
943
|
-
|
|
944
|
-
let keyFound = false;
|
|
945
|
-
for (const lpKey of keys) {
|
|
946
|
-
const regex = new RegExp(`'?"?${lpKey}'?"?:\\s?`, '');
|
|
947
|
-
if (regex.test(query)) {
|
|
948
|
-
keyFound = true;
|
|
949
|
-
break;
|
|
950
|
-
}
|
|
951
|
-
}
|
|
952
|
-
|
|
953
|
-
if ( keyFound ) {
|
|
954
|
-
|
|
955
|
-
const arrayOfKeyValues = query.split(',');
|
|
956
|
-
const modifiedArray = [];
|
|
957
|
-
for (const lpEntryStr of arrayOfKeyValues) {
|
|
958
|
-
const lpEntryArr = lpEntryStr.split(':');
|
|
959
|
-
const key = this.strCharsRemove(lpEntryArr[0], /['"`]/g, true)[0];
|
|
960
|
-
const val = this.strCharsRemove(lpEntryArr[1], /['"`]/g, true)[0];
|
|
961
|
-
const newEntryStr = `"${key}":"${val}"`;
|
|
962
|
-
modifiedArray.push(newEntryStr);
|
|
963
|
-
}
|
|
964
|
-
|
|
965
|
-
if (flat) {
|
|
966
|
-
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
|
-
}
|
|
974
|
-
}
|
|
975
|
-
} else {
|
|
976
|
-
const newVal = this.strCharsRemove(query, /['"`]/g, true)[0];
|
|
977
|
-
if (flat) {
|
|
978
|
-
return newVal;
|
|
979
|
-
} else {
|
|
980
|
-
return {val: newVal};
|
|
981
|
-
}
|
|
982
|
-
}
|
|
983
|
-
|
|
984
|
-
},
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
/**
|
|
988
|
-
* Rounds the given timestamp to the nearest minute
|
|
989
|
-
* Inspired by https://github.com/date-fns/date-fns/blob/master/src/roundToNearestMinutes/index.js
|
|
990
|
-
*
|
|
991
|
-
* @param {number} ts a timestamp
|
|
992
|
-
* @return {number} the resulting timestamp
|
|
993
|
-
*/
|
|
994
|
-
roundTimeStampToNearestMinute(ts) {
|
|
995
|
-
|
|
996
|
-
const date = new Date(ts);
|
|
997
|
-
const minutes = date.getMinutes() + date.getSeconds() / 60;
|
|
998
|
-
const roundedMinutes = Math.floor(minutes);
|
|
999
|
-
const remainderMinutes = minutes % 1;
|
|
1000
|
-
const addedMinutes = Math.round(remainderMinutes);
|
|
1001
|
-
return new Date(
|
|
1002
|
-
date.getFullYear(),
|
|
1003
|
-
date.getMonth(),
|
|
1004
|
-
date.getDate(),
|
|
1005
|
-
date.getHours(),
|
|
1006
|
-
roundedMinutes + addedMinutes
|
|
1007
|
-
).getTime();
|
|
1008
|
-
|
|
1009
|
-
},
|
|
1010
|
-
|
|
1011
|
-
/**
|
|
1012
|
-
* Validate URL
|
|
1013
|
-
* @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}
|
|
1017
|
-
*/
|
|
1018
|
-
validateURL(url, clean=false, returnUrl=false) {
|
|
1019
|
-
if(clean) url = url.replace(/\s/g,''); // remove all white spaces
|
|
1020
|
-
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
|
-
const regex = new RegExp(urlRegexStr);
|
|
1022
|
-
const isUrlValid = url.length < 2083 && regex.test(url);
|
|
1023
|
-
if (returnUrl) {
|
|
1024
|
-
if (isUrlValid) {
|
|
1025
|
-
return url;
|
|
1026
|
-
} else {
|
|
1027
|
-
return null;
|
|
1028
|
-
}
|
|
1029
|
-
} else {
|
|
1030
|
-
return isUrlValid;
|
|
1031
|
-
}
|
|
1032
|
-
},
|
|
1033
|
-
|
|
1034
|
-
/**
|
|
1035
|
-
* Pad a number with leading zeros, like 7 => '007' if 3 places.
|
|
1036
|
-
* @param {string|number} num Input number
|
|
1037
|
-
* @param {number} digits Number of digits
|
|
1038
|
-
* @return {string} The result
|
|
1039
|
-
*/
|
|
1040
|
-
zeroPad(num, digits) {
|
|
1041
|
-
const zero = digits - num.toString().length + 1;
|
|
1042
|
-
return Array(+(zero > 0 && zero)).join('0') + num;
|
|
1043
|
-
},
|
|
1044
|
-
|
|
1045
|
-
/**
|
|
1046
|
-
* Check string against a forbidden chars regex
|
|
1047
|
-
* Mic-M
|
|
1048
|
-
*
|
|
1049
|
-
* @param {string} str - the input string
|
|
1050
|
-
* @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 '[ ] , ? *'
|
|
1052
|
-
*/
|
|
1053
|
-
forbiddenCharsInStr(str, regex) {
|
|
1054
|
-
|
|
1055
|
-
let result = str.match(regex);
|
|
1056
|
-
if (result) {
|
|
1057
|
-
result = this.uniqueArray(result);
|
|
1058
|
-
let returnStr = '';
|
|
1059
|
-
for (const lpCharForbidden of result) {
|
|
1060
|
-
returnStr = returnStr + ' ' + lpCharForbidden;
|
|
1061
|
-
}
|
|
1062
|
-
return (returnStr.trim());
|
|
1063
|
-
} else {
|
|
1064
|
-
return false;
|
|
1065
|
-
}
|
|
1066
|
-
|
|
1067
|
-
},
|
|
1068
|
-
|
|
1069
|
-
};
|
|
1
|
+
/* eslint-disable no-irregular-whitespace */
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @desc Generic Helper Functions
|
|
6
|
+
* @author Mic-M <https://github.com/Mic-M/ioBroker.smartcontrol>
|
|
7
|
+
* @license MIT
|
|
8
|
+
*/
|
|
9
|
+
module.exports = function (adapter) {
|
|
10
|
+
|
|
11
|
+
return {
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Create States, either under adapter instance or anywhere.
|
|
16
|
+
* 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 }
|
|
19
|
+
* 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.
|
|
21
|
+
* WARN: use the "true" flag carefully!
|
|
22
|
+
* @return {Promise<boolean>} false if errors caught, otherwise true.
|
|
23
|
+
*/
|
|
24
|
+
async asyncCreateStates(statesToCreate, isForeign=false) {
|
|
25
|
+
|
|
26
|
+
try {
|
|
27
|
+
|
|
28
|
+
// Convert to array if it is an object, since we allow both
|
|
29
|
+
if(!Array.isArray(statesToCreate)) statesToCreate = [statesToCreate];
|
|
30
|
+
|
|
31
|
+
for (const lpStateToCreate of statesToCreate) {
|
|
32
|
+
|
|
33
|
+
// Check parameters
|
|
34
|
+
if (!lpStateToCreate.statePath || !lpStateToCreate.commonObject) {
|
|
35
|
+
adapter.log.error(`asyncCreateForeignStates(): invalid parameter provided to function`);
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Create new state.
|
|
40
|
+
// 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: {}});
|
|
45
|
+
} else {
|
|
46
|
+
// State already exists.
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Set default value
|
|
51
|
+
const def = lpStateToCreate.commonObject.def;
|
|
52
|
+
const type = lpStateToCreate.commonObject.type;
|
|
53
|
+
let initialDefault;
|
|
54
|
+
if (def !== undefined) {
|
|
55
|
+
initialDefault = def;
|
|
56
|
+
} 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
|
+
}
|
|
63
|
+
if (isForeign) {
|
|
64
|
+
await adapter.setForeignStateAsync(lpStateToCreate.statePath, initialDefault, false);
|
|
65
|
+
} else {
|
|
66
|
+
await adapter.setStateAsync(lpStateToCreate.statePath, initialDefault, false);
|
|
67
|
+
}
|
|
68
|
+
adapter.log.debug(`State '${lpStateToCreate.statePath}' created.`);
|
|
69
|
+
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
return true;
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
} catch (error) {
|
|
76
|
+
this.dumpError('[asyncCreateForeignStates()]', error);
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
},
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Check if an ioBroker object exists.
|
|
84
|
+
* @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>}
|
|
87
|
+
*/
|
|
88
|
+
async asyncObjectExists (str, isForeign=false) {
|
|
89
|
+
|
|
90
|
+
try {
|
|
91
|
+
let ret;
|
|
92
|
+
if (isForeign) {
|
|
93
|
+
ret = await adapter.getForeignObjectAsync(str);
|
|
94
|
+
} else {
|
|
95
|
+
ret = await adapter.getObjectAsync(str);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
if (ret == undefined) {
|
|
99
|
+
return false;
|
|
100
|
+
} else {
|
|
101
|
+
return true;
|
|
102
|
+
}
|
|
103
|
+
} catch (error) {
|
|
104
|
+
this.dumpError('[asyncObjectExists()]', error);
|
|
105
|
+
return false;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
},
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Get foreign state value
|
|
112
|
+
*
|
|
113
|
+
* @param {string} statePath - Full path to state, like 0_userdata.0.other.isSummer
|
|
114
|
+
* @return {Promise<*>} - State value, or null if error
|
|
115
|
+
*/
|
|
116
|
+
async asyncGetForeignStateValue(statePath) {
|
|
117
|
+
try {
|
|
118
|
+
const stateObject = await this.asyncGetForeignState(statePath);
|
|
119
|
+
if (stateObject == null) return null; // error thrown already in asyncGetForeignState()
|
|
120
|
+
return stateObject.val;
|
|
121
|
+
} catch (error) {
|
|
122
|
+
this.dumpError(`[asyncGetForeignStateValue]`, error);
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
},
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Get foreign state
|
|
130
|
+
*
|
|
131
|
+
* @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
|
|
133
|
+
*/
|
|
134
|
+
async asyncGetForeignState(statePath) {
|
|
135
|
+
|
|
136
|
+
try {
|
|
137
|
+
// Check state existence
|
|
138
|
+
const stateObject = await adapter.getForeignObjectAsync(statePath);
|
|
139
|
+
|
|
140
|
+
if (!stateObject) {
|
|
141
|
+
throw(`State '${statePath}' does not exist.`);
|
|
142
|
+
} else {
|
|
143
|
+
// Get state value, so like: {val: false, ack: true, ts: 1591117034451, …}
|
|
144
|
+
const stateValueObject = await adapter.getForeignStateAsync(statePath);
|
|
145
|
+
if (! this.isLikeEmpty(stateValueObject)) {
|
|
146
|
+
return stateValueObject;
|
|
147
|
+
} else {
|
|
148
|
+
throw(`Unable to retrieve info from state '${statePath}'.`);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
} catch (error) {
|
|
152
|
+
this.dumpError(`[asyncGetForeignState]`, error);
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
},
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Convert date/time to a local ISO string
|
|
160
|
+
* This function is needed since toISOString() uses UTC +0 (Zulu) as time zone.
|
|
161
|
+
* https://stackoverflow.com/questions/10830357/
|
|
162
|
+
* Mic-M, 04/Apr/2020
|
|
163
|
+
* @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)
|
|
165
|
+
*/
|
|
166
|
+
dateToLocalIsoString(date) {
|
|
167
|
+
const timezoneOffset = date.getTimezoneOffset() * 60000; //offset in milliseconds
|
|
168
|
+
return (new Date(date.getTime() - timezoneOffset)).toISOString().slice(0, -1);
|
|
169
|
+
},
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* For given object of enum objects, get the names and associated ids.
|
|
176
|
+
* enumObj.common.name can be either string like 'Living room' or {en:'Living room', de:'Wohnzimmer', ...}
|
|
177
|
+
* @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
|
|
180
|
+
*/
|
|
181
|
+
enumsGetNamesAndIds(enumObj, allLanguages=false) {
|
|
182
|
+
|
|
183
|
+
try {
|
|
184
|
+
|
|
185
|
+
const result = {};
|
|
186
|
+
for (const id in enumObj) { // id = like 'enum.rooms.bathroom'
|
|
187
|
+
const nameObj = enumObj[id].common.name; // either string like 'Living room' or {en:'Living room', de:'Wohnzimmer', ...}
|
|
188
|
+
if (typeof nameObj === 'string') {
|
|
189
|
+
result[nameObj] = id;
|
|
190
|
+
} else if (typeof nameObj === 'object') {
|
|
191
|
+
if (allLanguages) {
|
|
192
|
+
for (const lpLang in nameObj) {
|
|
193
|
+
result[nameObj[lpLang]] = id;
|
|
194
|
+
}
|
|
195
|
+
} else {
|
|
196
|
+
result[nameObj[adapter.x.systemConfig.language]] = id;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
} else {
|
|
200
|
+
adapter.log.warn(`Getting enum room name for '${id}': type for name must be string or object, but is '${typeof nameObj}'.`);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
if (!this.isLikeEmpty(result)) {
|
|
205
|
+
return result;
|
|
206
|
+
} else {
|
|
207
|
+
return null;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
} catch (error) {
|
|
211
|
+
this.dumpError('[enumsGetNamesAndIds]', error);
|
|
212
|
+
return null;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
},
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Restart the adapter instance.
|
|
219
|
+
* Source: https://github.com/foxriver76/ioBroker.xbox/blob/275e03635d657e7b18762166b4feca96fc4b1b1c/main.js#L630
|
|
220
|
+
*/
|
|
221
|
+
/*
|
|
222
|
+
async asyncRestartAdapter() {
|
|
223
|
+
|
|
224
|
+
try {
|
|
225
|
+
|
|
226
|
+
const resultObject = await adapter.getForeignObjectAsync('system.adapter.' + adapter.namespace);
|
|
227
|
+
if (resultObject) {
|
|
228
|
+
await adapter.setForeignObjectAsync('system.adapter.' + adapter.namespace, resultObject);
|
|
229
|
+
return;
|
|
230
|
+
} else {
|
|
231
|
+
adapter.log.error(`[asyncRestartAdapter()]: getForeignObjectAsync() No object provided from function.`);
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
} catch (error) {
|
|
236
|
+
adapter.log.error(`[asyncRestartAdapter()]: ${error}`);
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
},
|
|
241
|
+
*/
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Verify acknowledge (ack) once a state was changed.
|
|
248
|
+
*
|
|
249
|
+
* In General: Any state changes of states will be ignored, if acknowledge (ack) = false.
|
|
250
|
+
* The reason is that adapters confirm states by the acknowledge "ack" flag (setting to true).
|
|
251
|
+
* Reference: https://forum.iobroker.net/post/448606
|
|
252
|
+
*
|
|
253
|
+
* 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
|
+
* 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
|
|
256
|
+
* own states in the object main tree, like "Messwerte.0". https://forum.iobroker.net/post/461189
|
|
257
|
+
*
|
|
258
|
+
* @param {string} statePath - State Path
|
|
259
|
+
* @param {ioBroker.State|null|undefined} stateObject - State object
|
|
260
|
+
* @return {Promise<object>} {passing: false; msg:'some message'}
|
|
261
|
+
* if state change shall be ignored due to the ack (or error occurred), otherwise true.
|
|
262
|
+
*
|
|
263
|
+
*/
|
|
264
|
+
async isAckPassing(statePath, stateObject) {
|
|
265
|
+
|
|
266
|
+
try {
|
|
267
|
+
|
|
268
|
+
if (!stateObject || !statePath)
|
|
269
|
+
return {passing:false, msg:`Unexpected error: isAckPassing() was no valid statePath or stateObject provided.`};
|
|
270
|
+
|
|
271
|
+
const namespace = `${statePath.split('.')[0]}.${statePath.split('.')[1]}`; // like sonos.1
|
|
272
|
+
|
|
273
|
+
// For any states under this adapter instance (so )smartcontrol.x), we require ack = false;
|
|
274
|
+
// 22-Jul-2020: we allow different adapter instances as well.
|
|
275
|
+
// if (statePath.startsWith(`${adapter.namespace}.`)) {
|
|
276
|
+
if (statePath.match(/^smartcontrol.\d+./)) {
|
|
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`};
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// Handle User States
|
|
285
|
+
let isUserState = false;
|
|
286
|
+
if (statePath.startsWith('javascript.') || statePath.startsWith('0_userdata.0') || statePath.startsWith('alias.')) isUserState = true;
|
|
287
|
+
|
|
288
|
+
if (!isUserState) {
|
|
289
|
+
// Check if state is under a "real" adapter namespace.
|
|
290
|
+
const isRealAdapter = await adapter.getForeignObjectAsync(`system.adapter.${namespace}`);
|
|
291
|
+
if (!isRealAdapter) isUserState = true;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
if (isUserState) {
|
|
295
|
+
|
|
296
|
+
if (!adapter.config.triggerStatesAck || adapter.config.triggerStatesAck == 'false') {
|
|
297
|
+
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`};
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
} else if (adapter.config.triggerStatesAck == 'true') {
|
|
304
|
+
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`};
|
|
308
|
+
}
|
|
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`};
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
} catch (error) {
|
|
324
|
+
this.dumpError('[isAckPassing()]', error);
|
|
325
|
+
return {passing:false, msg:`Unexpected error occurred in isAckPassing()`};
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
},
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* 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
|
+
*
|
|
336
|
+
* @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.
|
|
338
|
+
*/
|
|
339
|
+
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
|
+
},
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* Get the timestamp of an astro name.
|
|
356
|
+
*
|
|
357
|
+
* @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
|
+
*/
|
|
361
|
+
getAstroNameTs(astroName, offsetMinutes=0) {
|
|
362
|
+
|
|
363
|
+
try {
|
|
364
|
+
let ts = adapter.x.mSuncalc.getTimes(new Date(), adapter.x.systemConfig.latitude, adapter.x.systemConfig.longitude)[astroName];
|
|
365
|
+
if (!ts || ts.getTime().toString() === 'NaN') {
|
|
366
|
+
// Fix night / nightEnd per adapter options.
|
|
367
|
+
// In northern areas is no night/nightEnd provided in the Summer.
|
|
368
|
+
// 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
|
|
372
|
+
switch (astroName) {
|
|
373
|
+
case 'night':
|
|
374
|
+
adapter.log.debug(`[getAstroNameTs] No time found for [${astroName}], so we set 00:00 as fallback per adapter config.`);
|
|
375
|
+
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
|
|
379
|
+
}
|
|
380
|
+
} else {
|
|
381
|
+
adapter.log.warn(`[getAstroNameTs] No time found for [${astroName}].`);
|
|
382
|
+
return 0;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
ts = this.roundTimeStampToNearestMinute(ts);
|
|
387
|
+
ts = ts + (offsetMinutes * 60 * 1000);
|
|
388
|
+
return ts;
|
|
389
|
+
} catch (error) {
|
|
390
|
+
this.dumpError('[getAstroNameTs()]', error);
|
|
391
|
+
return 0;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
},
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
/**
|
|
398
|
+
* Get the time stamp of a time string, like '23:30', 'goldenHourEnd', or 'goldenHourEnd+30'
|
|
399
|
+
* Supports times like 'h:ss'/'hh:ss', and also astro names.
|
|
400
|
+
* Astro names can also have an additional offset in minutes, so like "sunriseEnd-40" or "sunriseEnd+120".
|
|
401
|
+
*
|
|
402
|
+
* @param {string} input the input string
|
|
403
|
+
* @param {boolean} [getFullResult=false] if false: returns true if a valid time provided, and false if not.
|
|
404
|
+
* if true: Empty object if nothing found, or object with details.
|
|
405
|
+
* @return {boolean|object} Return value
|
|
406
|
+
*/
|
|
407
|
+
getTimeInfoFromAstroString(input, getFullResult=false) {
|
|
408
|
+
|
|
409
|
+
const currentDateTime = new Date(); // Date object of current date/time
|
|
410
|
+
|
|
411
|
+
input = input.replace(/\s/g,''); // remove all white spaces
|
|
412
|
+
|
|
413
|
+
const returnObject = {
|
|
414
|
+
full: input,
|
|
415
|
+
timestamp: 0,
|
|
416
|
+
hoursMins: '', // like '19:35'
|
|
417
|
+
isAstro: false,
|
|
418
|
+
astroName: '',
|
|
419
|
+
astroHasOffset: false,
|
|
420
|
+
astroOffsetMinutes: 0,
|
|
421
|
+
};
|
|
422
|
+
|
|
423
|
+
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})$/);
|
|
426
|
+
|
|
427
|
+
if (matchTime != null) {
|
|
428
|
+
// No Astro.
|
|
429
|
+
// Time like "19:35" found. Convert to timestamp by using current date
|
|
430
|
+
|
|
431
|
+
const hour = parseInt(matchTime[1]);
|
|
432
|
+
const min = parseInt(matchTime[3]);
|
|
433
|
+
|
|
434
|
+
if ( (input != '24:00') && (hour < 0 || hour > 23 || min < 0 || min > 60 ) ) {
|
|
435
|
+
returnObject.full = '';
|
|
436
|
+
} else {
|
|
437
|
+
|
|
438
|
+
returnObject.timestamp = new Date(
|
|
439
|
+
currentDateTime.getFullYear(),
|
|
440
|
+
currentDateTime.getMonth(),
|
|
441
|
+
currentDateTime.getDate(),
|
|
442
|
+
hour, // hours
|
|
443
|
+
min, // minutes
|
|
444
|
+
).getTime();
|
|
445
|
+
|
|
446
|
+
}
|
|
447
|
+
} else {
|
|
448
|
+
if (matchAstroName != null) {
|
|
449
|
+
// Astro found, with no offset
|
|
450
|
+
returnObject.astroName = input;
|
|
451
|
+
returnObject.isAstro = true;
|
|
452
|
+
returnObject.timestamp = this.getAstroNameTs(input);
|
|
453
|
+
} else if (matchAstroWithOffset != null) {
|
|
454
|
+
// Astro found, with offset
|
|
455
|
+
returnObject.isAstro = true;
|
|
456
|
+
returnObject.astroHasOffset = true;
|
|
457
|
+
returnObject.astroName = matchAstroWithOffset[1];
|
|
458
|
+
returnObject.astroOffsetMinutes = parseInt(matchAstroWithOffset[3]);
|
|
459
|
+
if(matchAstroWithOffset[2] == '-') {
|
|
460
|
+
returnObject.astroOffsetMinutes = returnObject.astroOffsetMinutes * (-1);
|
|
461
|
+
}
|
|
462
|
+
returnObject.timestamp = this.getAstroNameTs(returnObject.astroName, returnObject.astroOffsetMinutes);
|
|
463
|
+
} else {
|
|
464
|
+
// Nothing found
|
|
465
|
+
returnObject.full = '';
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
// Add hourMins string
|
|
470
|
+
returnObject.hoursMins = this.timestampToTimeString(returnObject.timestamp, true);
|
|
471
|
+
|
|
472
|
+
// handle '24:00'. We add a full day.
|
|
473
|
+
if (input == '24:00') {
|
|
474
|
+
returnObject.timestamp = returnObject.timestamp + +1000*60*60*24;
|
|
475
|
+
returnObject.hoursMins = '24:00';
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
if (!getFullResult) {
|
|
480
|
+
if (!returnObject.full) {
|
|
481
|
+
return false;
|
|
482
|
+
} else {
|
|
483
|
+
return true;
|
|
484
|
+
}
|
|
485
|
+
} else {
|
|
486
|
+
return returnObject;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
},
|
|
490
|
+
|
|
491
|
+
/**
|
|
492
|
+
* Converts a given timestamp into European time. E.g. '9:03pm and 45 seconds' -> '21:03:45'
|
|
493
|
+
* @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
|
|
496
|
+
*/
|
|
497
|
+
timestampToTimeString(ts, noSeconds=false) {
|
|
498
|
+
|
|
499
|
+
if(noSeconds) ts = this.roundTimeStampToNearestMinute(ts);
|
|
500
|
+
const inputDate = new Date(ts);
|
|
501
|
+
|
|
502
|
+
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);
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
},
|
|
509
|
+
|
|
510
|
+
|
|
511
|
+
/**
|
|
512
|
+
* Checks if time of '08:30' is between '23:00' and '09:00'.
|
|
513
|
+
* Source/inspired by: https://stackoverflow.com/a/24577309
|
|
514
|
+
*
|
|
515
|
+
* @param {string} start - start string, like: '23:00', '07:30', 9:15'
|
|
516
|
+
* @param {string} end - end string, like: '08:15', '17:23'
|
|
517
|
+
* @param {string} check - to check, like: '17:25', '9:30'
|
|
518
|
+
* @return {boolean} true if in between, false if not
|
|
519
|
+
*
|
|
520
|
+
*/
|
|
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));
|
|
527
|
+
};
|
|
528
|
+
|
|
529
|
+
function getTimeObj (timeString) {
|
|
530
|
+
const t = timeString.split(':');
|
|
531
|
+
const returnObject = {};
|
|
532
|
+
returnObject.hour = parseInt(t[0]);
|
|
533
|
+
returnObject.minutes = parseInt(t[1]);
|
|
534
|
+
returnObject.isGreaterThan = function(other) {
|
|
535
|
+
return (returnObject.hour > other.hour) || (returnObject.hour === other.hour) && (returnObject.minutes > other.minutes);
|
|
536
|
+
};
|
|
537
|
+
return returnObject;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
return timeIsBetween(getTimeObj(start), getTimeObj(end), getTimeObj(check));
|
|
541
|
+
|
|
542
|
+
},
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
/**
|
|
546
|
+
* Gets the time left of 'const xxx = setTimeout()', where xxx is the timer id.
|
|
547
|
+
*
|
|
548
|
+
* @author Mic-M <https://github.com/Mic-M/>
|
|
549
|
+
* @version 0.1 (30 June 2020)
|
|
550
|
+
*
|
|
551
|
+
* @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.
|
|
553
|
+
* To convert ms to seconds, simply use: (timeLeft / 1000).toFixed(0) - where timeLeft is the return value of the function.
|
|
554
|
+
*
|
|
555
|
+
*/
|
|
556
|
+
getTimeoutTimeLeft(timerId) {
|
|
557
|
+
|
|
558
|
+
try {
|
|
559
|
+
|
|
560
|
+
// Return -1 if timer object is undefined/null or if timer is not running
|
|
561
|
+
if (!timerId || timerId._destroyed) return -1;
|
|
562
|
+
|
|
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.
|
|
566
|
+
|
|
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
|
|
570
|
+
|
|
571
|
+
return remaining;
|
|
572
|
+
|
|
573
|
+
} catch (error) {
|
|
574
|
+
this.dumpError('[getTimeoutTimeLeft()]', error);
|
|
575
|
+
return -1;
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
},
|
|
579
|
+
|
|
580
|
+
/**
|
|
581
|
+
* Check if a timestamp is within two times.
|
|
582
|
+
*
|
|
583
|
+
* @param {number} tsGiven Timestamp to be checked if between start and end time
|
|
584
|
+
* @param {string} start Start time, like '18:30', or 'sunrise, or 'sunset+30'
|
|
585
|
+
* @param {string} end End time
|
|
586
|
+
* @param {string} ofWhat Typically zone name. For logging purposes only.
|
|
587
|
+
* @return {boolean} true if within times, and false if not.
|
|
588
|
+
*/
|
|
589
|
+
scheduleIsTimeStampWithinPeriod(tsGiven, start, end, ofWhat) {
|
|
590
|
+
|
|
591
|
+
try {
|
|
592
|
+
|
|
593
|
+
// First: convert potential Astro start time to "normal", so like 'sunset-30' to '18:30'
|
|
594
|
+
const givenFinal = this.timestampToTimeString(tsGiven, true);
|
|
595
|
+
const startFinal = this.getTimeInfoFromAstroString(start, true).hoursMins;
|
|
596
|
+
const endFinal = this.getTimeInfoFromAstroString(end, true).hoursMins;
|
|
597
|
+
|
|
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}'`);
|
|
601
|
+
|
|
602
|
+
// Next, check if given time is in between
|
|
603
|
+
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;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
} catch (error) {
|
|
612
|
+
this.dumpError('[scheduleIsTimeStampWithinPeriod]', error);
|
|
613
|
+
return false;
|
|
614
|
+
}
|
|
615
|
+
},
|
|
616
|
+
|
|
617
|
+
/**
|
|
618
|
+
* Check if current day is within the mon-sun options as set in Execution table.
|
|
619
|
+
*
|
|
620
|
+
* @param {object} row The "Execution" table row which was triggered.
|
|
621
|
+
* @param {number} ts The timestamp to check.
|
|
622
|
+
* @param {string} ofWhat Typically zone name. For logging purposes only.
|
|
623
|
+
* @return {boolean} True if matching, false if not.
|
|
624
|
+
*/
|
|
625
|
+
scheduleIsWeekdayMatching(row, ts, ofWhat) {
|
|
626
|
+
const days = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
|
|
627
|
+
const lpWeekdayGiven = getWeekDayString(ts);
|
|
628
|
+
for (const lpDay of days) {
|
|
629
|
+
if (lpWeekdayGiven == null) {
|
|
630
|
+
adapter.log.error(`[scheduleIsWeekdayMatching()] Unable to calculate day of week for given timestamp '${ts}'`);
|
|
631
|
+
return false;
|
|
632
|
+
} else if ( (row[lpDay] == true) && (lpDay == lpWeekdayGiven) ) {
|
|
633
|
+
adapter.log.debug(`${ofWhat} - Current weekday '${lpWeekdayGiven}' *is* matching Execution table row.`);
|
|
634
|
+
return true;
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
// There was no hit, so we return false.
|
|
638
|
+
adapter.log.debug(`${ofWhat} - Current weekday '${lpWeekdayGiven}' is *not* matching Execution table row.`);
|
|
639
|
+
return false;
|
|
640
|
+
|
|
641
|
+
/**
|
|
642
|
+
* get the week day of a string.
|
|
643
|
+
* Source: https://stackoverflow.com/a/17964373
|
|
644
|
+
* @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.
|
|
646
|
+
*/
|
|
647
|
+
function getWeekDayString(date) {
|
|
648
|
+
const dayOfWeek = new Date(date).getDay();
|
|
649
|
+
return isNaN(dayOfWeek) ? null : ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'][dayOfWeek];
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
},
|
|
653
|
+
|
|
654
|
+
/**
|
|
655
|
+
* JSON Log to smartcontrol.x.info.log.<id>.json
|
|
656
|
+
* @param {string} id - e.g. 'zoneActivations' or 'switchedTargetDevices'
|
|
657
|
+
* @param {object} jsonObj - object to add, e.g. {zone:'xyz', targetDevice:'xyz'}
|
|
658
|
+
* @return {boolean} - false if errors caught, otherwise true.
|
|
659
|
+
*/
|
|
660
|
+
async setJsonLog(id, jsonObj) {
|
|
661
|
+
|
|
662
|
+
try {
|
|
663
|
+
|
|
664
|
+
let maxJsonLength = 0;
|
|
665
|
+
if (adapter.x.helper.isNumber(adapter.config.jsonMaxEntries)) {
|
|
666
|
+
maxJsonLength = parseInt(adapter.config.jsonMaxEntries);
|
|
667
|
+
}
|
|
668
|
+
if (maxJsonLength <= 0) return true;
|
|
669
|
+
|
|
670
|
+
if(!this.isLikeEmpty(adapter.x.jsonLogs[id])) {
|
|
671
|
+
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
|
|
673
|
+
} else {
|
|
674
|
+
adapter.x.jsonLogs[id] = [jsonObj]; // add as array
|
|
675
|
+
}
|
|
676
|
+
adapter.setState(`info.log.${id}.json`, { val: JSON.stringify(adapter.x.jsonLogs[id]), ack: true });
|
|
677
|
+
return true;
|
|
678
|
+
|
|
679
|
+
} catch (error) {
|
|
680
|
+
this.dumpError('[setJsonLog]', error);
|
|
681
|
+
return false;
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
},
|
|
685
|
+
|
|
686
|
+
|
|
687
|
+
/**
|
|
688
|
+
* Checks if an ioBroker state id (path) string is valid.
|
|
689
|
+
* NOTE: This does not verify if the state is existing. It does just some basic checks if the path looks good-
|
|
690
|
+
*
|
|
691
|
+
* @param {string} str String to validate
|
|
692
|
+
* @return {boolean} true/false of validation result
|
|
693
|
+
*/
|
|
694
|
+
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
|
|
702
|
+
return true; // All passed
|
|
703
|
+
},
|
|
704
|
+
|
|
705
|
+
/**
|
|
706
|
+
* Logs information to ioBroker log.
|
|
707
|
+
* If "extendedInfoLog" in adapter settings is disabled, log level is debug.
|
|
708
|
+
* @param {string} msg The log message
|
|
709
|
+
*/
|
|
710
|
+
logExtendedInfo(msg) {
|
|
711
|
+
if(adapter.config.extendedInfoLog) {
|
|
712
|
+
adapter.log.info(msg);
|
|
713
|
+
} else {
|
|
714
|
+
adapter.log.debug(msg);
|
|
715
|
+
}
|
|
716
|
+
},
|
|
717
|
+
|
|
718
|
+
/**
|
|
719
|
+
* Error Message to Log. Handles error object being provided.
|
|
720
|
+
*
|
|
721
|
+
* @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}
|
|
725
|
+
*/
|
|
726
|
+
dumpError(msg, error=undefined, returnMsg=false) {
|
|
727
|
+
let finalMsg = 'undefined';
|
|
728
|
+
if (!error) {
|
|
729
|
+
finalMsg = msg;
|
|
730
|
+
} else {
|
|
731
|
+
if (typeof error === 'object') {
|
|
732
|
+
if (error.stack) {
|
|
733
|
+
finalMsg = `${msg} – ${error.stack}`;
|
|
734
|
+
} else if (error.message) {
|
|
735
|
+
finalMsg = `${msg} – ${error.message}`;
|
|
736
|
+
} else {
|
|
737
|
+
finalMsg = `${msg} – ${JSON.stringify(error)}`;
|
|
738
|
+
}
|
|
739
|
+
} else if (typeof error === 'string') {
|
|
740
|
+
finalMsg = `${msg} – ${error}`;
|
|
741
|
+
} else {
|
|
742
|
+
finalMsg = `[dumpError()] : wrong error argument: ${JSON.stringify(error)}`;
|
|
743
|
+
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
if (returnMsg) {
|
|
747
|
+
return finalMsg;
|
|
748
|
+
} else {
|
|
749
|
+
adapter.log.error(finalMsg);
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
},
|
|
753
|
+
|
|
754
|
+
/**
|
|
755
|
+
* Checks if Array or String is not undefined, null or empty.
|
|
756
|
+
* Array, object, or string containing just white spaces or >'< or >"< or >[< or >]< is considered empty
|
|
757
|
+
* 18-Jun-2020: added check for { and } to also catch empty objects.
|
|
758
|
+
* 08-Sep-2019: added check for [ and ] to also catch arrays with empty strings.
|
|
759
|
+
* @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)
|
|
761
|
+
*/
|
|
762
|
+
isLikeEmpty(inputVar) {
|
|
763
|
+
if (typeof inputVar !== 'undefined' && inputVar !== null) {
|
|
764
|
+
let strTemp = JSON.stringify(inputVar);
|
|
765
|
+
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 >}<
|
|
772
|
+
if (strTemp !== '') {
|
|
773
|
+
return false;
|
|
774
|
+
} else {
|
|
775
|
+
return true;
|
|
776
|
+
}
|
|
777
|
+
} else {
|
|
778
|
+
return true;
|
|
779
|
+
}
|
|
780
|
+
},
|
|
781
|
+
|
|
782
|
+
/**
|
|
783
|
+
* Checks whether variable is number
|
|
784
|
+
* true: 5, '123'
|
|
785
|
+
* false: '123abc', 'q345', null, undefined, false, ' '
|
|
786
|
+
* @source https://stackoverflow.com/questions/1303646/check-whether-variable-is-number-or-string-in-javascript
|
|
787
|
+
* @param {any} n Input variable to check
|
|
788
|
+
* @return {boolean} true if number, false if not.
|
|
789
|
+
*/
|
|
790
|
+
isNumber(n) {
|
|
791
|
+
return /^-?[\d.]+(?:e-?\d+)?$/.test(n);
|
|
792
|
+
},
|
|
793
|
+
|
|
794
|
+
|
|
795
|
+
/**
|
|
796
|
+
* Check a given number against a comparator string, like '>30', '<= 25', etc.
|
|
797
|
+
* @param {any} numToCheck - number to check against comparator
|
|
798
|
+
* @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
|
|
800
|
+
*/
|
|
801
|
+
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
|
+
}
|
|
829
|
+
},
|
|
830
|
+
|
|
831
|
+
|
|
832
|
+
/**
|
|
833
|
+
* Remove certain (forbidden) chars from a string
|
|
834
|
+
* @param {string} str - The input string
|
|
835
|
+
* @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
|
|
838
|
+
*/
|
|
839
|
+
strCharsRemove(str, regex, cleanSpaces=false) {
|
|
840
|
+
let correctedMsg = '';
|
|
841
|
+
let result = str;
|
|
842
|
+
if (result.match(regex)) {
|
|
843
|
+
result = result.replace(regex, '');
|
|
844
|
+
correctedMsg += 'removed certain chars;';
|
|
845
|
+
}
|
|
846
|
+
if (cleanSpaces) {
|
|
847
|
+
// remove multiple spaces
|
|
848
|
+
if (result.match(/ +/g)) {
|
|
849
|
+
result = result.replace(/ +/g, ' '); // remove multiple spaces
|
|
850
|
+
correctedMsg += 'removed multiple spaces;';
|
|
851
|
+
}
|
|
852
|
+
// remove spaces from the start and end
|
|
853
|
+
if (result.startsWith(' ') || result.endsWith(' ')) {
|
|
854
|
+
result = result.trim();
|
|
855
|
+
correctedMsg += 'remove spaces from start and/or end;';
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
return [result, correctedMsg];
|
|
859
|
+
},
|
|
860
|
+
|
|
861
|
+
|
|
862
|
+
|
|
863
|
+
/**
|
|
864
|
+
* Remove Duplicates from Array
|
|
865
|
+
* @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.
|
|
868
|
+
*/
|
|
869
|
+
uniqueArray(inputArray) {
|
|
870
|
+
return inputArray.filter(function(elem, pos) {
|
|
871
|
+
return inputArray.indexOf(elem) == pos;
|
|
872
|
+
});
|
|
873
|
+
},
|
|
874
|
+
|
|
875
|
+
|
|
876
|
+
/**
|
|
877
|
+
* Check if an array contains duplicate values
|
|
878
|
+
* https://stackoverflow.com/a/34192063
|
|
879
|
+
*
|
|
880
|
+
* @param {*} myArray - The given array
|
|
881
|
+
* @return {boolean} - true if it is unique, false otherwise.
|
|
882
|
+
*/
|
|
883
|
+
isArrayUnique(myArray) {
|
|
884
|
+
return myArray.length === new Set(myArray).size;
|
|
885
|
+
},
|
|
886
|
+
|
|
887
|
+
/**
|
|
888
|
+
* Removing Array element(s) by input value.
|
|
889
|
+
* @param {array} arr the input array
|
|
890
|
+
* @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)
|
|
893
|
+
*/
|
|
894
|
+
arrayRemoveElementByValue(arr, valRemove, exact=true) {
|
|
895
|
+
|
|
896
|
+
const arrGiven = [...arr]; // copy array
|
|
897
|
+
|
|
898
|
+
for ( let i = 0; i < arrGiven.length; i++){
|
|
899
|
+
if (exact) {
|
|
900
|
+
if ( arrGiven[i] === valRemove) {
|
|
901
|
+
arrGiven.splice(i, 1);
|
|
902
|
+
i--;
|
|
903
|
+
}
|
|
904
|
+
} else {
|
|
905
|
+
if (arrGiven[i].indexOf(valRemove) != -1) {
|
|
906
|
+
arrGiven.splice(i, 1);
|
|
907
|
+
i--;
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
return arrGiven;
|
|
912
|
+
},
|
|
913
|
+
|
|
914
|
+
/**
|
|
915
|
+
* Remove duplicates from an array of objects by key
|
|
916
|
+
* https://stackoverflow.com/a/58437069
|
|
917
|
+
*
|
|
918
|
+
* @param {array} givenArray
|
|
919
|
+
* @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
|
|
921
|
+
*/
|
|
922
|
+
uniqueArrayObjectByKey(givenArray, key, all=false) {
|
|
923
|
+
|
|
924
|
+
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);
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
},
|
|
931
|
+
|
|
932
|
+
/**
|
|
933
|
+
* Converts string like 'val:'abc', delay:500' to a JSON object
|
|
934
|
+
* If keys 'val' or 'delay' are not existing, return {val: query}
|
|
935
|
+
* @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
|
|
939
|
+
*/
|
|
940
|
+
convertStrToJson(query, keys, flat=false) {
|
|
941
|
+
|
|
942
|
+
if (this.isLikeEmpty(query)) return null;
|
|
943
|
+
|
|
944
|
+
let keyFound = false;
|
|
945
|
+
for (const lpKey of keys) {
|
|
946
|
+
const regex = new RegExp(`'?"?${lpKey}'?"?:\\s?`, '');
|
|
947
|
+
if (regex.test(query)) {
|
|
948
|
+
keyFound = true;
|
|
949
|
+
break;
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
if ( keyFound ) {
|
|
954
|
+
|
|
955
|
+
const arrayOfKeyValues = query.split(',');
|
|
956
|
+
const modifiedArray = [];
|
|
957
|
+
for (const lpEntryStr of arrayOfKeyValues) {
|
|
958
|
+
const lpEntryArr = lpEntryStr.split(':');
|
|
959
|
+
const key = this.strCharsRemove(lpEntryArr[0], /['"`]/g, true)[0];
|
|
960
|
+
const val = this.strCharsRemove(lpEntryArr[1], /['"`]/g, true)[0];
|
|
961
|
+
const newEntryStr = `"${key}":"${val}"`;
|
|
962
|
+
modifiedArray.push(newEntryStr);
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
if (flat) {
|
|
966
|
+
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
|
+
}
|
|
974
|
+
}
|
|
975
|
+
} else {
|
|
976
|
+
const newVal = this.strCharsRemove(query, /['"`]/g, true)[0];
|
|
977
|
+
if (flat) {
|
|
978
|
+
return newVal;
|
|
979
|
+
} else {
|
|
980
|
+
return {val: newVal};
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
},
|
|
985
|
+
|
|
986
|
+
|
|
987
|
+
/**
|
|
988
|
+
* Rounds the given timestamp to the nearest minute
|
|
989
|
+
* Inspired by https://github.com/date-fns/date-fns/blob/master/src/roundToNearestMinutes/index.js
|
|
990
|
+
*
|
|
991
|
+
* @param {number} ts a timestamp
|
|
992
|
+
* @return {number} the resulting timestamp
|
|
993
|
+
*/
|
|
994
|
+
roundTimeStampToNearestMinute(ts) {
|
|
995
|
+
|
|
996
|
+
const date = new Date(ts);
|
|
997
|
+
const minutes = date.getMinutes() + date.getSeconds() / 60;
|
|
998
|
+
const roundedMinutes = Math.floor(minutes);
|
|
999
|
+
const remainderMinutes = minutes % 1;
|
|
1000
|
+
const addedMinutes = Math.round(remainderMinutes);
|
|
1001
|
+
return new Date(
|
|
1002
|
+
date.getFullYear(),
|
|
1003
|
+
date.getMonth(),
|
|
1004
|
+
date.getDate(),
|
|
1005
|
+
date.getHours(),
|
|
1006
|
+
roundedMinutes + addedMinutes
|
|
1007
|
+
).getTime();
|
|
1008
|
+
|
|
1009
|
+
},
|
|
1010
|
+
|
|
1011
|
+
/**
|
|
1012
|
+
* Validate URL
|
|
1013
|
+
* @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}
|
|
1017
|
+
*/
|
|
1018
|
+
validateURL(url, clean=false, returnUrl=false) {
|
|
1019
|
+
if(clean) url = url.replace(/\s/g,''); // remove all white spaces
|
|
1020
|
+
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
|
+
const regex = new RegExp(urlRegexStr);
|
|
1022
|
+
const isUrlValid = url.length < 2083 && regex.test(url);
|
|
1023
|
+
if (returnUrl) {
|
|
1024
|
+
if (isUrlValid) {
|
|
1025
|
+
return url;
|
|
1026
|
+
} else {
|
|
1027
|
+
return null;
|
|
1028
|
+
}
|
|
1029
|
+
} else {
|
|
1030
|
+
return isUrlValid;
|
|
1031
|
+
}
|
|
1032
|
+
},
|
|
1033
|
+
|
|
1034
|
+
/**
|
|
1035
|
+
* Pad a number with leading zeros, like 7 => '007' if 3 places.
|
|
1036
|
+
* @param {string|number} num Input number
|
|
1037
|
+
* @param {number} digits Number of digits
|
|
1038
|
+
* @return {string} The result
|
|
1039
|
+
*/
|
|
1040
|
+
zeroPad(num, digits) {
|
|
1041
|
+
const zero = digits - num.toString().length + 1;
|
|
1042
|
+
return Array(+(zero > 0 && zero)).join('0') + num;
|
|
1043
|
+
},
|
|
1044
|
+
|
|
1045
|
+
/**
|
|
1046
|
+
* Check string against a forbidden chars regex
|
|
1047
|
+
* Mic-M
|
|
1048
|
+
*
|
|
1049
|
+
* @param {string} str - the input string
|
|
1050
|
+
* @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 '[ ] , ? *'
|
|
1052
|
+
*/
|
|
1053
|
+
forbiddenCharsInStr(str, regex) {
|
|
1054
|
+
|
|
1055
|
+
let result = str.match(regex);
|
|
1056
|
+
if (result) {
|
|
1057
|
+
result = this.uniqueArray(result);
|
|
1058
|
+
let returnStr = '';
|
|
1059
|
+
for (const lpCharForbidden of result) {
|
|
1060
|
+
returnStr = returnStr + ' ' + lpCharForbidden;
|
|
1061
|
+
}
|
|
1062
|
+
return (returnStr.trim());
|
|
1063
|
+
} else {
|
|
1064
|
+
return false;
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
},
|
|
1068
|
+
|
|
1069
|
+
};
|
|
1070
1070
|
};
|