iobroker.javascript 9.1.0 → 9.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/README.md +16 -8
  2. package/admin/assets/AiChatPanel-sgt697A2.js +296 -0
  3. package/admin/assets/AiDatapointProvider-B0i3I5Fm.js +2 -0
  4. package/admin/assets/AiDiffView-RPozjjHf.js +1 -0
  5. package/admin/assets/AiInlineProvider-Dd7eKxk4.js +7 -0
  6. package/admin/assets/{Save-Cld9qv9i.js → Save-CkuNSiWL.js} +1 -1
  7. package/admin/assets/{ScriptEditor-BVaX7Hcs.js → ScriptEditor-CH4qJzqq.js} +2 -2
  8. package/admin/assets/ScriptEditorVanillaMonaco-cB_90T0P.js +1 -0
  9. package/admin/assets/{createSvgIcon-DPvF8xqu.js → createSvgIcon-DYs_tNrE.js} +1 -1
  10. package/admin/assets/docs-compact-CKNGiYh2.js +336 -0
  11. package/admin/assets/index-BI3JsAz_.js +1 -0
  12. package/admin/assets/{index-D8iYqogF.js → index-DAkyON1r.js} +5 -5
  13. package/admin/assets/index-DW5CwIma.js +1256 -0
  14. package/admin/assets/index-SHs7_wDh.js +1 -0
  15. package/admin/assets/{index-DlDUIfpA.js → index-dN73sbyQ.js} +1 -1
  16. package/admin/assets/index-hwplVCgv.js +986 -0
  17. package/admin/assets/index-wHNMOf-c.js +5 -0
  18. package/admin/assets/inheritsLoose-CIXm_zPk.js +29 -0
  19. package/admin/assets/{iobroker_javascript__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-QWG5Arqe.js → iobroker_javascript__loadShare___mf_0_mui_mf_1_material__loadShare__.mjs-CV1_X-Lf.js} +1 -1
  20. package/admin/assets/{localSharedImportMap-AxgBkrOR.js → localSharedImportMap-CqvxvyGG.js} +1 -1
  21. package/admin/assets/useTheme-DuTJsNQ-.js +1 -0
  22. package/admin/assets/{virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-C9suQF96.js → virtual_mf-REMOTE_ENTRY_ID_iobroker_javascript__remoteEntry_js-BJ03G6Pu.js} +2 -2
  23. package/admin/custom/assets/{Components-FfVbavBM.js → Components-B9ZyjeRI.js} +1 -1
  24. package/admin/custom/assets/{index-Be7j5wvd.js → index-BVwMgafs.js} +1 -1
  25. package/admin/custom/assets/index-CVIpIckw.js +960 -0
  26. package/admin/custom/assets/{index-DNdWk-cT.js → index-DsIn9jH_.js} +1 -1
  27. package/admin/custom/assets/{localSharedImportMap-BRxFonIn.js → localSharedImportMap-C4qXtGUd.js} +1 -1
  28. package/admin/custom/assets/{virtualExposes-DyedJotb.js → virtualExposes-jSvr-kK3.js} +1 -1
  29. package/admin/custom/assets/{virtual_mf-REMOTE_ENTRY_ID_ConfigCustomJavascriptSet__customComponents_js-BtJxKB87.js → virtual_mf-REMOTE_ENTRY_ID_ConfigCustomJavascriptSet__customComponents_js-DFSXB0v2.js} +2 -2
  30. package/admin/custom/customComponents.js +1 -1
  31. package/admin/google-blockly/own/blocks_words.js +7 -0
  32. package/admin/google-blockly/own/field_oid.js +311 -37
  33. package/admin/i18n/de.json +8 -0
  34. package/admin/i18n/en.json +8 -0
  35. package/admin/i18n/es.json +8 -0
  36. package/admin/i18n/flat.txt +427 -0
  37. package/admin/i18n/fr.json +8 -0
  38. package/admin/i18n/it.json +8 -0
  39. package/admin/i18n/nl.json +8 -0
  40. package/admin/i18n/pl.json +8 -0
  41. package/admin/i18n/pt.json +8 -0
  42. package/admin/i18n/ru.json +8 -0
  43. package/admin/i18n/uk.json +8 -0
  44. package/admin/i18n/zh-cn.json +8 -0
  45. package/admin/img/anthropic.svg +1 -0
  46. package/admin/img/custom.svg +1 -0
  47. package/admin/img/deepseek.svg +1 -0
  48. package/admin/img/gemini.svg +1 -0
  49. package/admin/img/openai.svg +1 -0
  50. package/admin/jsonConfig.json +76 -14
  51. package/admin/mf-manifest.json +1 -1
  52. package/admin/remoteEntry.js +1 -1
  53. package/admin/tab.html +6 -6
  54. package/build/lib/debugger.js +2 -2
  55. package/build/lib/debugger.js.map +1 -1
  56. package/build/lib/inspect.js.map +1 -1
  57. package/build/lib/nodeModulesManagement.js +2 -2
  58. package/build/lib/nodeModulesManagement.js.map +1 -1
  59. package/build/lib/protectFs.js +5 -0
  60. package/build/lib/protectFs.js.map +1 -1
  61. package/build/lib/sandbox.js +2 -2
  62. package/build/lib/sandbox.js.map +1 -1
  63. package/build/main.js +72 -17
  64. package/build/main.js.map +1 -1
  65. package/build/types.d.ts +2 -0
  66. package/docs/de/README.md +21 -8
  67. package/docs/de/blockly.md +34 -0
  68. package/docs/en/README.md +21 -8
  69. package/docs/en/blockly.md +34 -0
  70. package/install/installTypings.js +1 -1
  71. package/io-package.json +27 -66
  72. package/package.json +7 -6
  73. package/admin/assets/OpenAiDialog-Dx-XNET0.js +0 -13
  74. package/admin/assets/ScriptEditorVanillaMonaco-yq11eIYC.js +0 -1
  75. package/admin/assets/docs-BrInh2Pn.js +0 -2036
  76. package/admin/assets/index-CLJ6-h9Q.js +0 -1
  77. package/admin/assets/index-COZhHfBn.js +0 -1230
  78. package/admin/assets/index-Cu-TydZj.js +0 -5
  79. package/admin/assets/index-Dnbw7_L3.js +0 -986
  80. package/admin/assets/index-gIA8x-8f.js +0 -1
  81. package/admin/assets/inheritsLoose-B0Ba5G9z.js +0 -29
  82. package/admin/assets/useTheme-hy6f3gra.js +0 -1
  83. package/admin/custom/assets/index-CYc31Gwg.js +0 -960
@@ -1,2036 +0,0 @@
1
- const e=`### exec - execute some OS command, like \`cp file1 file2\`
2
-
3
- \`\`\`js
4
- exec(cmd, [options], callback);
5
- \`\`\`
6
-
7
- Execute system command and get the outputs.
8
-
9
- \`\`\`js
10
- // reboot linux system :)
11
- exec('reboot');
12
-
13
- // Get the list of files and directories in /var/log
14
- exec('ls /var/log', function (error, stdout, stderr) {
15
- log(\`stdout: \${stdout}\`);
16
- });
17
- \`\`\`
18
-
19
- Node.js uses /bin/sh to execute commands. If you want to use another shell, you can use the option object as described in the [Node.js documentation](https://nodejs.org/api/child_process.html#child_processexeccommand-options-callback) for child_process.exec.
20
- It is the best practice to always use fill path names to commands to make sure the right command is executed.
21
-
22
- **Notice:** you must enable _Enable command "exec"_ option to use this feature!
23
-
24
- ### on - Subscribe on changes or updates of some state
25
-
26
- \`\`\`js
27
- on(pattern, callbackOrId, value);
28
- \`\`\`
29
-
30
- The callback function will return the object as parameter with the following content:
31
-
32
- \`\`\`json
33
- {
34
- "id": "javascript.0.myplayer",
35
- "state": {
36
- "val": "new state",
37
- "ts": 1416149118,
38
- "ack": true,
39
- "lc": 1416149118,
40
- "from": "system.adapter.sonos.0"
41
- },
42
- "oldState": {
43
- "val": "old state",
44
- "ts": 1416148233,
45
- "ack": true,
46
- "lc": 1416145154,
47
- "from": "system.adapter.sonos.0"
48
- }
49
- }
50
- \`\`\`
51
-
52
- **Note:** \`state\` was previously called \`newState\`. That is still working.
53
-
54
- Example:
55
-
56
- \`\`\`js
57
- let timer;
58
-
59
- // Create state "javascript.0.counter"
60
- createState('counter', 0);
61
-
62
- // On change
63
- on('adapter.0.device.channel.sensor', data => {
64
- // But not ofter than 30 seconds
65
- if (!timer) {
66
- timer = setTimeout(() => {
67
- timer = null;
68
- }, 30000);
69
-
70
- // Set acknowledged value
71
- setState('counter', 1 + getState('counter'), true /*ack*/);
72
-
73
- // Or to set unacknowledged command
74
- setState('adapter.0.device.channel.actor', true);
75
- }
76
- });
77
- \`\`\`
78
-
79
- You can use the following parameters to specify the trigger:
80
-
81
- | parameter | type/value | description |
82
- |-------------|------------|-----------------------------------------------------------------------------------------------------------------------------------------------|
83
- | logic | string | "and" or "or" logic to combine the conditions \\(default: "and"\\) |
84
- | | | |
85
- | id | string | id is equal to given one |
86
- | | RegExp | id matched to regular expression |
87
- | | Array | id matched to a list of allowed IDs |
88
- | | | |
89
- | name | string | name is equal to given one |
90
- | | RegExp | name matched to regular expression |
91
- | | Array | name matched to a list of allowed names |
92
- | | | |
93
- | change | string | "eq", "ne", "gt", "ge", "lt", "le", "any" |
94
- | | "eq" | (equal) New value must be equal to old one (state.val == oldState.val) |
95
- | | "ne" | (not equal) New value must be not equal to the old one (state.val != oldState.val) **If pattern is id-string this value is used by default** |
96
- | | "gt" | (greater) New value must be greater than old value (state.val > oldState.val) |
97
- | | "ge" | (greater or equal) New value must be greater or equal to old one (state.val >= oldState.val) |
98
- | | "lt" | (smaller) New value must be smaller than old one (state.val < oldState.val) |
99
- | | "le" | (smaller or equal) New value must be smaller or equal to old value (state.val <= oldState.val) |
100
- | | "any" | Trigger will be raised if just the new value comes |
101
- | | | |
102
- | val | mixed | New value must be equal to given one |
103
- | valNe | mixed | New value must be not equal to given one |
104
- | valGt | mixed | New value must be greater than given one |
105
- | valGe | mixed | New value must be greater or equal to given one |
106
- | valLt | mixed | New value must be smaller than given one |
107
- | valLe | mixed | New value must be smaller or equal to given one |
108
- | | | |
109
- | ack | boolean | Acknowledged state of new value is equal to given one |
110
- | q | number | Quality code state of new value is equal to given one. You can use '\\*' for matching to any code. **If not provided q = 0 is set as pattern!** |
111
- | | | |
112
- | oldVal | mixed | Previous value must be equal to given one |
113
- | oldValNe | mixed | Previous value must be not equal to given one |
114
- | oldValGt | mixed | Previous value must be greater than given one |
115
- | oldValGe | mixed | Previous value must be greater or equal to given one |
116
- | oldValLt | mixed | Previous value must be smaller than given one |
117
- | oldValLe | mixed | Previous value must be smaller or equal to given one |
118
- | | | |
119
- | oldAck | bool | Acknowledged state of previous value is equal to given one |
120
- | oldQ | number | Quality code state of previous value is equal to given one. You can use '\\*' for matching to any code |
121
- | | | |
122
- | ts | string | New value time stamp must be equal to given one (state.ts == ts) |
123
- | tsGt | string | New value time stamp must be not equal to the given one (state.ts != ts) |
124
- | tsGe | string | New value time stamp must be greater than given value (state.ts > ts) |
125
- | tsLt | string | New value time stamp must be greater or equal to given one (state.ts >= ts) |
126
- | tsLe | string | New value time stamp must be smaller than given one (state.ts < ts) |
127
- | | | |
128
- | oldTs | string | Previous time stamp must be equal to given one (oldState.ts == ts) |
129
- | oldTsGt | string | Previous time stamp must be not equal to the given one (oldState.ts != ts) |
130
- | oldTsGe | string | Previous time stamp must be greater than given value (oldState.ts > ts) |
131
- | oldTsLt | string | Previous time stamp must be greater or equal to given one (oldState.ts >= ts) |
132
- | oldTsLe | string | Previous time stamp must be smaller than given one (oldState.ts < ts) |
133
- | | | |
134
- | lc | string | Last change time stamp must be equal to given one (state.lc == lc) |
135
- | lcGt | string | Last change time stamp must be not equal to the given one (state.lc != lc) |
136
- | lcGe | string | Last change time stamp must be greater than given value (state.lc > lc) |
137
- | lcLt | string | Last change time stamp must be greater or equal to given one (state.lc >= lc) |
138
- | lcLe | string | Last change time stamp must be smaller than given one (state.lc < lc) |
139
- | | | |
140
- | oldLc | string | Previous last change time stamp must be equal to given one (oldState.lc == lc) |
141
- | oldLcGt | string | Previous last change time stamp must be not equal to the given one (oldState.lc != lc) |
142
- | oldLcGe | string | Previous last change time stamp must be greater than given value (oldState.lc > lc) |
143
- | oldLcLt | string | Previous last change time stamp must be greater or equal to given one (oldState.lc >= lc) |
144
- | oldLcLe | string | Previous last change time stamp must be smaller than given one (oldState.lc < lc) |
145
- | | | |
146
- | channelId | string | Channel ID must be equal to given one |
147
- | | RegExp | Channel ID matched to regular expression |
148
- | | Array | Channel ID matched to a list of allowed channel IDs |
149
- | | | |
150
- | channelName | string | Channel name must be equal to given one |
151
- | | RegExp | Channel name matched to regular expression |
152
- | | Array | Channel name matched to a list of allowed channel names |
153
- | | | |
154
- | deviceId | string | Device ID must be equal to given one |
155
- | | RegExp | Device ID matched to regular expression |
156
- | | Array | Device ID matched to a list of allowed device IDs |
157
- | | | |
158
- | deviceName | string | Device name must be equal to given one |
159
- | | RegExp | Device name matched to regular expression |
160
- | | Array | Device name matched to a list of allowed device names |
161
- | | | |
162
- | enumId | string | State belongs to given enum |
163
- | | RegExp | One enum ID of the state satisfies the given regular expression |
164
- | | Array | One enum ID of the state is in the given list of enum IDs |
165
- | | | |
166
- | enumName | string | State belongs to given enum |
167
- | | RegExp | One enum name of the state satisfies the given regular expression |
168
- | | Array | One enum name of the state is in the given list of enum names |
169
- | | | |
170
- | from | string | New value is from defined adapter |
171
- | | RegExp | New value is from an adapter that matches the regular expression |
172
- | | Array | New value is from an adapter that appears in the given list of allowed adapters |
173
- | | | |
174
- | fromNe | string | New value is not from defined adapter |
175
- | | RegExp | New value is not from an adapter that matches the regular expression |
176
- | | Array | New value is not from an adapter that appears in the given list of forbidden adapters |
177
- | | | |
178
- | oldFrom | string | Old value is from defined adapter |
179
- | | RegExp | Old value is from an adapter that matches the regular expression |
180
- | | Array | Old value is from an adapter that appears in the given list of allowed adapters |
181
- | | | |
182
- | oldFromNe | string | Old value is not from defined adapter |
183
- | | RegExp | Old value is not from an adapter that matches the regular expression |
184
- | | Array | Old value is not from an adapter that appears in the given list of forbidden adapters |
185
-
186
- Examples:
187
- Trigger on all states with ID \`'*.STATE'\` if they are acknowledged and have new value \`true\`.
188
-
189
- \`\`\`js
190
- {
191
- id: /\\.STATE$/,
192
- val: true,
193
- ack: true,
194
- logic: 'and'
195
- }
196
- \`\`\`
197
-
198
- **Note:** you can use RegExp directly:
199
-
200
- \`\`\`js
201
- on(/^system\\.adapter\\..*\\.\\d+\\.memRss$/, function (obj) {});
202
-
203
- // same as
204
- on({ id: /^system\\.adapter\\..*\\.\\d+\\.memRss$/, change: 'ne' }, function (obj) {});
205
- \`\`\`
206
-
207
- To simply connect two states with each other, write:
208
-
209
- \`\`\`js
210
- on('stateId1', 'stateId2');
211
- \`\`\`
212
-
213
- All changes of _stateId1_ will be written to _stateId2_.
214
-
215
- If the \`value\` parameter is set in combination with state id as the second parameter, on any change the state will filled with the \`value\`.
216
-
217
- \`\`\`js
218
- on('stateId1', 'stateId2', 'triggered');
219
- setState('stateId1', 'new value');
220
-
221
- // stateId2 will be set to 'triggered'.
222
- \`\`\`
223
-
224
- Function \`on\` returns handler back. This handler can be used by unsubscribing.
225
-
226
- _Notice:_ By default only states with quality 0x00 will be passed to callback function. If you want to get all events, add \`{q: '*'}\` to pattern structure.
227
-
228
- _Notice:_ Please note, that by default \`change\` is equal to \`any\`, except when only id as string is set (like \`on('id', () => {});\`). In last case change will be set to "ne".
229
-
230
- _Notice:_ If you want to also get state deletions/expires as trigger, you need to use change with \`ne\` or \`any\` AND q with \`*\` as filter!
231
-
232
- _Notice:_ from 4.3.2 it is possible to write a type of trigger as second parameter: \`on('my.id.0', 'any', obj => log(obj.state.val));\`
233
-
234
- ### once
235
-
236
- Registers a one-time subscription which automatically unsubscribes after the first invocation. Same as [on](#on---subscribe-on-changes-or-updates-of-some-state), but just executed once.
237
-
238
- \`\`\`js
239
- once(pattern, callback);
240
- \`\`\`
241
-
242
- ### subscribe - same as **[on](#on---subscribe-on-changes-or-updates-of-some-state)**
243
-
244
- ### unsubscribe
245
-
246
- \`\`\`js
247
- unsubscribe(id);
248
- // or
249
- unsubscribe(handler);
250
- \`\`\`
251
-
252
- Remove all subscriptions for given object ID or for given handler.
253
-
254
- \`\`\`js
255
- // By handler
256
- let mySubscription = on({ id: 'javascript.0.myState', change: 'any' }, data => {
257
- // unsubscribe after first trigger
258
- if (unsubscribe(mySubscription)) {
259
- log('Subscription deleted');
260
- }
261
- });
262
-
263
- // by Object ID
264
- on({ id: 'javascript.0.myState1', change: 'ne' }, data => {
265
- log('Some event');
266
- });
267
-
268
- on({ id: 'javascript.0.myState1', change: 'any' }, data => {
269
- // unsubscribe
270
- if (unsubscribe('javascript.0.myState1')) {
271
- log('All subscriptions deleted');
272
- }
273
- });
274
- \`\`\`
275
-
276
- ### getSubscriptions
277
-
278
- Get the list of subscriptions.
279
-
280
- Example of a result:
281
-
282
- \`\`\`json
283
- {
284
- "megad.0.dataPointName": [
285
- {
286
- "name" : "script.js.NameOfScript",
287
- "pattern" : {
288
- "id" : "megad.0.dataPointName",
289
- "change" : "ne"
290
- }
291
- }
292
- ]
293
- }
294
- \`\`\`
295
-
296
- ### getFileSubscriptions
297
-
298
- Get the list of file subscriptions.
299
-
300
- Example of a result:
301
-
302
- \`\`\`json
303
- {
304
- "vis.0$%$main/*": [
305
- {
306
- "name" : "script.js.NameOfScript",
307
- "id" : "vis.0",
308
- "fileNamePattern": "main/*"
309
- }
310
- ]
311
- }
312
- \`\`\`
313
-
314
- ### schedule
315
-
316
- \`\`\`js
317
- schedule(pattern, callback);
318
- \`\`\`
319
-
320
- Time scheduler with astro-function.
321
-
322
- #### Time schedule
323
-
324
- Pattern can be a string with [Cron-Syntax](http://en.wikipedia.org/wiki/Cron), which consists of 5 (without seconds) or 6 (with seconds) digits:
325
-
326
- \`\`\`
327
- * * * * * *
328
- │ │ │ │ │ │
329
- │ │ │ │ │ │
330
- │ │ │ │ │ └───── day of week (0 - 6) (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0)
331
- │ │ │ │ └────────── month (1 - 12)
332
- │ │ │ └─────────────── day of month (1 - 31)
333
- │ │ └──────────────────── hour (0 - 23)
334
- │ └───────────────────────── min (0 - 59)
335
- └───────────────────────────── [optional] sec (0 - 59)
336
- \`\`\`
337
-
338
- \`\`\`js
339
- // Example with 5 digits:
340
- schedule('*/2 * * * *', () => {
341
- log('Will be triggered every 2 minutes!');
342
- });
343
-
344
- // Example with 6 digits:
345
- schedule('*/3 * * * * *', () => {
346
- log('Will be triggered every 3 seconds!');
347
- });
348
- \`\`\`
349
-
350
- The pattern can also be an object, it is used especially if seconds are required:
351
-
352
- the object could have the following properties:
353
-
354
- - \`second\`
355
- - \`minute\`
356
- - \`hour\`
357
- - \`date\`
358
- - \`month\`
359
- - \`year\`
360
- - \`dayOfWeek\`
361
-
362
- \`\`\`js
363
- schedule({ second: [20, 25] }, () => {
364
- log('Will be triggered at xx:xx:20 and xx:xx:25 of every minute!');
365
- });
366
-
367
- schedule({ hour: 12, minute: 30 }, () => {
368
- log('Will be triggered at 12:30!');
369
- });
370
- \`\`\`
371
-
372
- Pattern can be a JavaScript Date object (some specific time point) - in this case only it will be triggered only one time.
373
-
374
- If start or end times for a schedule are needed, this could also be implemented with usage of an object. In this scenario the object has the properties:
375
-
376
- - \`start\`
377
- - \`end\`
378
- - \`rule\`
379
-
380
- start and end defines a Date object a DateString or a number of milliseconds since 01 January 1970 00:00:00 UTC.
381
- Rule is a schedule string with [Cron-Syntax](http://en.wikipedia.org/wiki/Cron) or an object:
382
-
383
- \`\`\`js
384
- let startTime = new Date(Date.now() + 5000);
385
- let endTime = new Date(startTime.getTime() + 5000);
386
- schedule({ start: startTime, end: endTime, rule: '*/1 * * * * *' }, () => {
387
- log('It will run after 5 seconds and stop after 10 seconds');
388
- });
389
- \`\`\`
390
-
391
- The rule itself could be also an object:
392
-
393
- \`\`\`js
394
- let today = new Date();
395
- let startTime = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1);
396
- let endTime = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 7);
397
- let ruleData = { hour: 12, minute: 30 };
398
- schedule({ start: startTime, end: endTime, rule: ruleData }, () => {
399
- log('Will be triggered at 12:30, starting tomorow, ending in 7 days');
400
- });
401
- \`\`\`
402
-
403
- #### Astro-function
404
-
405
- Astro-function can be used via "astro" attribute:
406
-
407
- \`\`\`js
408
- schedule({ astro: 'sunrise' }, () => {
409
- log('Sunrise!');
410
- });
411
-
412
- schedule({ astro: 'sunset', shift: 10 }, () => {
413
- log('10 minutes after sunset!');
414
- });
415
- \`\`\`
416
-
417
- The attribute "shift" is the offset in minutes. It can be negative, too, to define time before astro event.
418
-
419
- The following values can be used as attribute in astro-function:
420
-
421
- - \`"sunrise"\`: sunrise (top edge of the sun appears on the horizon)
422
- - \`"sunriseEnd"\`: sunrise ends (bottom edge of the sun touches the horizon)
423
- - \`"goldenHourEnd"\`: morning golden hour (soft light, the best time for photography) ends
424
- - \`"solarNoon"\`: solar noon (sun is in the highest position)
425
- - \`"goldenHour"\`: evening golden hour starts
426
- - \`"sunsetStart"\`: sunset starts (bottom edge of the sun touches the horizon)
427
- - \`"sunset"\`: sunset (sun disappears below the horizon, evening civil twilight starts)
428
- - \`"dusk"\`: dusk (evening nautical twilight starts)
429
- - \`"nauticalDusk"\`: nautical dusk (evening astronomical twilight starts)
430
- - \`"night"\`: night starts (dark enough for astronomical observations)
431
- - \`"nightEnd"\`: night ends (morning astronomical twilight starts)
432
- - \`"nauticalDawn"\`: nautical dawn (morning nautical twilight starts)
433
- - \`"dawn"\`: dawn (morning nautical twilight ends, morning civil twilight starts)
434
- - \`"nadir"\`: nadir (the darkest moment of the night, sun is in the lowest position)
435
-
436
- **Note:** to use "astro"-function the "latitude" and "longitude" must be defined in JavaScript adapter settings.
437
-
438
- **Note:** in some places sometimes it could be so that no night/nightEnd exists. Please read [here](https://github.com/mourner/suncalc/issues/70) about it.
439
-
440
- **Note:** you can use "on" function for schedule with small modification:
441
-
442
- \`\`\`js
443
- on({ time: '*/2 * * * *' }, () => {
444
- log(new Date().toString() + ' - Will be triggered every 2 minutes!');
445
- });
446
-
447
- on({ time: { hour: 12, minute: 30 } }, () => {
448
- log(new Date().toString() + ' - Will be triggered at 12:30!');
449
- });
450
-
451
- on({ astro: 'sunset', shift: 10 }, () => {
452
- log(new Date().toString() + ' - 10 minutes after sunset!');
453
- });
454
- \`\`\`
455
-
456
- ## scheduleById
457
-
458
- \`\`\`js
459
- scheduleById(id, callback);
460
- scheduleById(id, ack, callback);
461
- \`\`\`
462
-
463
- Allows to create a schedule based on a state value. If the state value changes, the old schedule will be deleted and a new schedule is created automatically.
464
-
465
- Supported formats:
466
-
467
- - \`[h]h:[m]m:ss\` (e.g. \`12:42:15\`, \`15:3:12\`, \`3:10:25\`)
468
- - \`[h]h:[m]m\` (e.g. \`13:37\`, \`9:40\`)
469
-
470
- \`\`\`js
471
- scheduleById('0_userdata.0.configurableTimeFormat', () => {
472
- log('Executed!');
473
- });
474
- \`\`\`
475
-
476
- Example: Create state and register schedule on changes:
477
-
478
- \`\`\`js
479
- createState(
480
- '0_userdata.0.myTime',
481
- '00:00:00', // default value
482
- {
483
- type: 'string',
484
- read: true,
485
- write: true,
486
- },
487
- () => {
488
- scheduleById('0_userdata.0.myTime', () => {
489
- log('Executed!');
490
- });
491
- },
492
- );
493
- \`\`\`
494
-
495
- ### getSchedules
496
-
497
- \`\`\`js
498
- const list = getSchedules(true);
499
- \`\`\`
500
-
501
- Returns the list of all CRON jobs and schedules (except astro).
502
- Argument must be \`true\` if you want to get the list for **every running script**. Otherwise, only schedules in the current script will be returned.
503
-
504
- \`\`\`js
505
- const list = getSchedules(true);
506
- list.forEach(schedule => log(JSON.stringify(schedule)));
507
-
508
- // clear all schedules in all scripts!
509
- list.forEach(schedule => clearSchedule(schedule));
510
- \`\`\`
511
-
512
- Example output:
513
-
514
- \`\`\`
515
- 2020-11-01 20:15:19.929 - {"type":"cron","pattern":"0 * * * *","scriptName":"script.js.Heizung","id":"cron_1604258108384_74924"}
516
- 2020-11-01 20:15:19.931 - {"type":"schedule","schedule":"{"period":{}}","scriptName":"script.js.Heizung","id":"schedule_19576"}
517
- \`\`\`
518
-
519
- ### clearSchedule
520
-
521
- If **no** "astro" function is used, you can cancel the schedule later. To allow this, the schedule object must be saved:
522
-
523
- \`\`\`js
524
- let sch = schedule('*/2 * * * *', () => {
525
- /* ... */
526
- });
527
-
528
- // later:
529
- clearSchedule(sch);
530
- \`\`\`
531
-
532
- ### getAttr
533
-
534
- \`\`\`js
535
- getAttr({ attr1: { attr2: 5 } }, 'attr1.attr2');
536
- \`\`\`
537
-
538
- Returns an attribute of the object. Path to attribute can be nested, like in the example.
539
-
540
- If the first attribute is string, the function will try to parse the string as JSON string.
541
-
542
- ### getAstroDate
543
-
544
- \`\`\`js
545
- getAstroDate(pattern, date, offsetMinutes);
546
- \`\`\`
547
-
548
- Returns a javascript Date object for the specified astro-name (e.g. \`"sunrise"\` or \`"sunriseEnd"\`). For valid values, see the list of allowed values in the [Astro](#astro--function) section in the _schedule_ function.
549
-
550
- The returned Date object is calculated for the passed _date_. If no date is provided, the current day is used.
551
-
552
- \`\`\`js
553
- let sunriseEnd = getAstroDate('sunriseEnd');
554
- log(\`Sunrise ends today at \${sunriseEnd.toLocaleTimeString()}\`);
555
-
556
- let today = new Date();
557
- let tomorrow = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1);
558
- let tomorrowNight = getAstroDate('night', tomorrow);
559
- \`\`\`
560
-
561
- **Note: Depending on your geographical location, there can be cases where e.g. 'night'/'nightEnd' do not exist on certain time points (e.g., locations north in May/June each year!**
562
-
563
- You can use webpages like [suncalc.net](http://suncalc.net) to check if the time points are correct.
564
-
565
- ### isAstroDay
566
-
567
- \`\`\`js
568
- isAstroDay();
569
- \`\`\`
570
-
571
- Returns \`true\` if the current time is between the astro sunrise and sunset.
572
-
573
- ### compareTime
574
-
575
- \`\`\`js
576
- compareTime(startTime, endTime, operation, timeToCompare);
577
- \`\`\`
578
-
579
- Compare given time with limits.
580
-
581
- If \`timeToCompare\` is not given, so the actual time will be used.
582
-
583
- The following operations are possible:
584
-
585
- - \`">"\` - if given time is greater than \`startTime\`
586
- - \`">="\` - if given time is greater or equal to \`startTime\`
587
- - \`"<"\` - if given time is less than \`startTime\`
588
- - \`"<="\` - if given time is less or equal to \`startTime\`
589
- - \`"=="\` - if given time is equal to \`startTime\`
590
- - \`"<>"\` - if given time is not equal to \`startTime\`
591
- - \`"between"\` - if given time is between \`startTime\` and \`endTime\`
592
- - \`"not between"\` - if given time is not between \`startTime\` and \`endTime\`
593
-
594
- Time can be Date object or Date with time or just time.
595
-
596
- You can use astro-names for the time definition. All 3 parameters can be set as astro time.
597
- Following values are possible: \`sunrise\`, \`sunset\`, \`sunriseEnd\`, \`sunsetStart\`, \`dawn\`, \`dusk\`, \`nauticalDawn\`, \`nauticalDusk\`, \`nightEnd\`, \`night\`, \`goldenHourEnd\`, \`goldenHour\`.
598
- See [Astro](#astro--function) for detail.
599
-
600
- \`\`\`js
601
- log(compareTime('sunsetStart', 'sunsetEnd', 'between') ? 'Now is sunrise' : 'Now is no sunrise');
602
- \`\`\`
603
-
604
- It is possible to define the time with offset too:
605
-
606
- \`\`\`js
607
- log(
608
- compareTime({ astro: 'sunsetStart', offset: 30 }, { astro: 'sunrise', offset: -30 }, '>')
609
- ? 'Now is at least 30 minutes after sunset'
610
- : 'No idea',
611
- );
612
- \`\`\`
613
-
614
- Structure of an astro object.
615
-
616
- \`\`\`js
617
- {
618
- astro: 'sunsetStart',// mandatory, can be written as string and not as object if offset and date are default
619
- offset: 30, // optional
620
- date: new Date() // optional
621
- }
622
- \`\`\`
623
-
624
- ### setState
625
-
626
- \`\`\`js
627
- setState(id, state, ack, callback);
628
- \`\`\`
629
-
630
- _Note_: The following commands are identical
631
-
632
- \`\`\`js
633
- setState('myState', 1, false);
634
- setState('myState', { val: 1, ack: false });
635
- setState('myState', 1);
636
- \`\`\`
637
-
638
- Please refer to https://github.com/ioBroker/ioBroker/wiki/Adapter-Development-Documentation#commands-and-statuses for usage of \`ack\`.
639
- Short:
640
-
641
- - \`ack = false\`: Script wants to send a command to be executed by the target device/adapter
642
- - \`ack = true\`: Command was successfully executed, and state is updated as a positive result
643
-
644
- ### setStateAsync
645
-
646
- \`\`\`js
647
- await setStateAsync(id, state, ack);
648
- \`\`\`
649
-
650
- Same as setState, but with \`promise\`.
651
-
652
- ### setStateDelayed
653
-
654
- \`\`\`js
655
- setStateDelayed(id, state, isAck, delay, clearRunning, callback);
656
- \`\`\`
657
-
658
- Same as setState but with delay in milliseconds. You can clear all running delays for this ID (by default). E.g.
659
-
660
- \`\`\`js
661
- // Switch ON the light in the kitchen in one second
662
- setStateDelayed('Kitchen.Light.Lamp', true, 1000);
663
-
664
- // Switch OFF the light in the kitchen in 5 seconds and let first timeout run.
665
- setStateDelayed('Kitchen.Light.Lamp', false, 5000, false, () => {
666
- log('Lamp is OFF');
667
- });
668
- \`\`\`
669
-
670
- This function returns the handler of the timer, and this timer can be individually stopped by clearStateDelayed
671
-
672
- ### setStateChanged
673
-
674
- \`\`\`js
675
- await setStateChanged(id, state, ack);
676
- \`\`\`
677
-
678
- Same as setState, but set value only if the value is really changed.
679
-
680
- ### setStateChangedAsync
681
-
682
- \`\`\`js
683
- await setStateChangedAsync(id, state, ack);
684
- \`\`\`
685
-
686
- Same as setStateChanged, but with \`promise\`.
687
-
688
- ### clearStateDelayed
689
-
690
- \`\`\`js
691
- clearStateDelayed(id);
692
- \`\`\`
693
-
694
- Clears all delayed tasks for specified state ID or some specific delayed task.
695
-
696
- \`\`\`js
697
- setStateDelayed('Kitchen.Light.Lamp', false, 10000); // Switch OFF the light in the kitchen in ten second
698
- let timer = setStateDelayed('Kitchen.Light.Lamp', true, 5000, false); // Switch ON the light in the kitchen in five second
699
- clearStateDelayed('Kitchen.Light.Lamp', timer); // Nothing will be switched on
700
- clearStateDelayed('Kitchen.Light.Lamp'); // Clear all running delayed tasks for this ID
701
- \`\`\`
702
-
703
- ### getStateDelayed
704
-
705
- \`\`\`js
706
- getStateDelayed(id);
707
- \`\`\`
708
-
709
- This is a synchronous call, and you will get the list of all running timers (setStateDelayed) for this id.
710
- You can call this function without id and get timers for all IDs.
711
- In case you call this function for some specific object ID, you will get the following answer:
712
-
713
- \`\`\`js
714
- getStateDelayed('hm-rpc.0.LQE91119.1.STATE');
715
-
716
- // returns an array like
717
- [
718
- { timerId: 1, left: 1123, delay: 5000, val: true, ack: false },
719
- { timerId: 2, left: 12555, delay: 15000, val: false, ack: false },
720
- ];
721
- \`\`\`
722
-
723
- If you ask for all IDs, the answer will look like:
724
-
725
- \`\`\`js
726
- getStateDelayed();
727
-
728
- // returns an object like
729
- {
730
- 'hm-rpc.0.LQE91119.1.STATE': [
731
- { timerId: 1, left: 1123, delay: 5000, val: true, ack: false },
732
- { timerId: 2, left: 12555, delay: 15000, val: false, ack: false },
733
- ],
734
- 'hm-rpc.0.LQE91119.2.LEVEL': [
735
- { timerId: 3, left: 5679, delay: 10000, val: 100, ack: false }
736
- ]
737
- }
738
- \`\`\`
739
-
740
- - \`left\` is the time left in milliseconds
741
- - \`delay\` is the initial delay value in milliseconds
742
-
743
- You can ask by timerId directly. In this case, the answer will be:
744
-
745
- \`\`\`js
746
- getStateDelayed(3);
747
-
748
- // returns an object like
749
- { id: 'hm-rpc.0.LQE91119.2.LEVEL', left: 5679, delay: 10000, val: 100, ack: false }
750
- \`\`\`
751
-
752
- ### getState
753
-
754
- \`\`\`js
755
- getState(id);
756
- \`\`\`
757
-
758
- Returns state with the given id in the following form:
759
-
760
- \`\`\`js
761
- {
762
- val: value,
763
- ack: true/false,
764
- ts: timestamp,
765
- lc: lastchanged,
766
- from: origin
767
- }
768
- \`\`\`
769
-
770
- If state does not exist, a warning will be printed in the logs and the object \`{ val: null, notExist: true }\` will be returned.
771
- To suppress the warning check if the state exists before calling getState (see [existsState](#existsState)).
772
-
773
- ### getStateAsync
774
-
775
- \`\`\`js
776
- const stateObject = await getStateAsync(id);
777
- \`\`\`
778
-
779
- Same as getState, but with \`promise\`.
780
-
781
- ### existsState
782
-
783
- \`\`\`js
784
- existsState(id, (err, isExists) => {});
785
- \`\`\`
786
-
787
- If option "Do not subscribe all states on start" is deactivated, you can use simpler call:
788
-
789
- \`\`\`js
790
- existsState(id);
791
- \`\`\`
792
-
793
- the function returns in this case true or false.
794
-
795
- Check if a state exists.
796
-
797
- ### getObject
798
-
799
- \`\`\`js
800
- getObject(id, enumName);
801
- \`\`\`
802
-
803
- Get description of object id as stored in a system.
804
- You can specify the enumeration name. If this is defined, two additional attributes will be added to result: enumIds and enumNames.
805
- These arrays have all enumerations, where ID is a member of. E.g:
806
-
807
- \`\`\`js
808
- getObject('adapter.N.objectName', 'rooms');
809
- \`\`\`
810
-
811
- gives back in enumIds all rooms, where the requested object is a member. You can define "true" as enumName to get back _all_ enumerations.
812
-
813
- ### setObject
814
-
815
- \`\`\`js
816
- setObject(id, obj, callback);
817
- \`\`\`
818
-
819
- Write an object into DB. This command can be disabled in adapter's settings. Use this function carefully, while the global settings can be damaged.
820
-
821
- You should use it to **modify** an existing object you read beforehand, e.g.:
822
-
823
- \`\`\`js
824
- const obj = getObject('adapter.N.objectName');
825
- obj.native.settings = 1;
826
- setObject('adapter.N.objectName', obj, err => {
827
- if (err) log('Cannot write object: ' + err);
828
- });
829
- \`\`\`
830
-
831
- ### existsObject
832
-
833
- \`\`\`js
834
- existsObject(id, function (err, isExists) {});
835
- \`\`\`
836
-
837
- If the option "Do not subscribe all states on start" is deactivated, you can use simpler call:
838
-
839
- \`\`\`js
840
- existsObject(id);
841
- \`\`\`
842
-
843
- the function returns in this case true or false.
844
-
845
- Check if an object exists.
846
-
847
- ### extendObject
848
-
849
- \`\`\`js
850
- extendObject(id, obj, callback);
851
- \`\`\`
852
-
853
- It is almost the same as \`setObject\`, but first it reads the object and tries to merge all settings together.
854
-
855
- Use it like this:
856
-
857
- \`\`\`js
858
- // Stop instance
859
- extendObject('system.adapter.sayit.0', { common: { enabled: false } });
860
- \`\`\`
861
-
862
- ### deleteObject
863
-
864
- \`\`\`js
865
- deleteObject(id, isRecursive, callback);
866
- \`\`\`
867
-
868
- Delete an object from DB by ID. If the object has type \`state\`, the state value will be deleted too.
869
-
870
- Additional parameter \`isRecursive\` could be provided, so all children of given ID will be deleted. Very dangerous!
871
-
872
- Use it like this:
873
-
874
- \`\`\`js
875
- // Delete state
876
- deleteObject('javascript.0.createdState');
877
- \`\`\`
878
-
879
- _Notice: \`isRecursive\` option is available only with js-controller >= 2.2.x_
880
-
881
- ### getIdByName
882
-
883
- \`\`\`js
884
- getIdByName(name, alwaysArray);
885
- \`\`\`
886
-
887
- Returns id of the object with given name.
888
- If there is more than one object with this name, the result will be an array.
889
- If \`alwaysArray\` flag is set, the result will always be an array if some ID found.
890
-
891
- ### getEnums
892
-
893
- \`\`\`js
894
- getEnums(enumName);
895
- \`\`\`
896
-
897
- Get the list of existing enumerations with members, like:
898
-
899
- \`\`\`js
900
- getEnums('rooms');
901
-
902
- // returns:
903
- [
904
- {
905
- id: 'enum.rooms.LivingRoom',
906
- members: ['hm-rpc.0.JEQ0024123.1', 'hm-rpc.0.BidCoS-RF.4'],
907
- name: 'Living room',
908
- },
909
- {
910
- id: 'enum.rooms.Bath',
911
- members: ['hm-rpc.0.JEQ0024124.1', 'hm-rpc.0.BidCoS-RF.5'],
912
- name: 'Bath',
913
- },
914
- ];
915
- \`\`\`
916
-
917
- ### createState
918
-
919
- \`\`\`js
920
- createState(name, initialValue, forceCreation, common, native, callback);
921
- \`\`\`
922
-
923
- Create state and object in \`javascript.0\` space if it does not exist, e.g. \`javascript.0.mystate\`.
924
-
925
- !! Prefer to create own data points with the full ID \`0_userdata.0.mystate\` !!!
926
-
927
- #### Parameters:
928
-
929
- - \`name\`: name of the state without namespace, e.g. \`mystate\`
930
- - \`initialValue\`: variable can be initialized after created. Value "undefined" means do not initialize value.
931
- - \`forceCreation\`: create/overwrite state independent of if state yet exists or not.
932
- - \`common\`: common description of object see description [here](https://github.com/ioBroker/ioBroker/blob/master/doc/SCHEMA.md#state)
933
- - \`native\`: native description of an object. Any specific information.
934
- - \`callback\`: called after state is created and initialized.
935
-
936
- If you set in \`common\` the flag \`alias\` to \`true\`, then alias will be created with the same name (but in \`alias.0\` namespace) as the state.
937
- Alias is created only if it does not exist yet.
938
-
939
- The following settings for aliases are valid too:
940
-
941
- \`\`\`js
942
- common => {
943
- alias: {
944
- id: 'alias.0.myOtherState', // will be created automatically if not already exists
945
- write: 'val * 1000', // convert function for write to created state
946
- read: 'val / 1000' // convert function to read from created state
947
- }
948
- }
949
- \`\`\`
950
-
951
- or
952
-
953
- \`\`\`js
954
- common => {
955
- alias: {
956
- id: 'alias.0.myOtherState', // will be created automatically if not already exists
957
- }
958
- }
959
- \`\`\`
960
-
961
- It is possible short type of createState:
962
-
963
- - \`createState('myDatapoint')\` - simply create datapoint if it does not exist
964
- - \`createState('myDatapoint', 1)\` - create datapoint if it does not exist and initialize it with value 1
965
- - \`createState('myDatapoint', { type: 'string', role: 'json', read: true, write: false }, () => { log('created'); });\` - with common definitions like type, read, write and role
966
- - \`createState('myDatapoint', { name: 'My own datapoint', unit: '°C' }, () => { log('created'); });\`
967
- - \`createState('myDatapoint', 1, { name: 'My own datapoint', unit: '°C' })\` - create datapoint if it does not exist with specific name and units
968
-
969
- ### createStateAsync
970
-
971
- \`\`\`js
972
- await createStateAsync(name, initialValue, forceCreation, common, native);
973
- \`\`\`
974
-
975
- Same as \`createState\`, but the promise will be returned.
976
-
977
- ### deleteState
978
-
979
- \`\`\`js
980
- deleteState(name, callback);
981
- \`\`\`
982
-
983
- Delete state and object in \`javascript.0\` space, e.g. \`javascript.0.mystate\`. States from other adapters cannot be deleted.
984
-
985
- \`\`\`js
986
- deleteState('myDatapoint');
987
- \`\`\`
988
-
989
- simply delete datapoint if exists.
990
-
991
- ### deleteStateAsync
992
-
993
- \`\`\`js
994
- await deleteStateAsync(name);
995
- \`\`\`
996
-
997
- Same as \`deleteState\`, but the promise will be returned.
998
-
999
- ### createAlias
1000
-
1001
- \`\`\`js
1002
- createAlias(name, alias, forceCreation, common, native, callback);
1003
- \`\`\`
1004
-
1005
- Create alias in \`alias.0\` space if it does not exist, e.g. \`javascript.0.myalias\` and reference to a state or read/write states.
1006
- The common definition is taken from the read alias id object, but a provided common takes precedence.
1007
-
1008
- #### Parameters:
1009
-
1010
- - \`name\`: id of the new alias state with (possible without an alias namespace), e.g. \`test.mystate\` (namespace \`alias.0.\` will be added = \`alias.0.test.mystate\`)
1011
- - \`alias\`: can be either an existing state id as string or an object with full alias definition including read/write ids and read/write functions. Note: Alias definitions can not be set as part of the common parameter!
1012
- - \`forceCreation\`: create/overwrite alias independent of if state yet exists or not.
1013
- - \`common\`: common description of alias object see description [here](https://github.com/ioBroker/ioBroker/blob/master/doc/SCHEMA.md#state). Values provided here will take precedence over the common definition of the read alias id object. Not: Alias definitions can not be set as part of this common parameter, see alias parameter!
1014
- - \`native\`: native description of an object. Any specific information.
1015
- - \`callback\`: called after state is created and initialized.
1016
-
1017
- It is possible a short type of createAlias:
1018
-
1019
- - \`createAlias('myAlias', 'myDatapoint')\` - simply create alias.0.myAlias that references to \`javascript.X.myDatapoint\` if it does not exist
1020
- - \`createAlias('myAlias', { id: { read: 'myReadDatapoint', write: 'myWriteDatapoint' }})\` - creates alias and reference to different read/write states
1021
-
1022
- For other details, see createState, it is similar.
1023
-
1024
- ### createAliasAsync
1025
-
1026
- \`\`\`js
1027
- await createAliasAsync(name, alias, forceCreation, common, native);
1028
- \`\`\`
1029
-
1030
- Same as \`createAlias\`, but the promise will be returned.
1031
-
1032
- ### sendTo
1033
-
1034
- \`\`\`js
1035
- sendTo(adapter, command, message, callback);
1036
- sendTo(adapter, command, message, options, callback);
1037
- \`\`\`
1038
-
1039
- Send a message to a specific or all adapter instances. When using the adapter name, the message is sent to all instances.
1040
-
1041
- To get specific information about messages, you must read the documentation for a particular adapter.
1042
-
1043
- Example (with custom timeout):
1044
-
1045
- \`\`\`js
1046
- sendTo('telegram', { user: 'UserName', text: 'Test message' }, { timeout: 2000 });
1047
- \`\`\`
1048
-
1049
- Some adapters also support responses to the sent messages. (e.g. history, SQL, telegram)
1050
- The response is only returned to the callback if the message is sent to a specific instance!
1051
-
1052
- Example (with callback):
1053
-
1054
- \`\`\`js
1055
- sendTo('telegram.0', { user: 'UserName', text: 'Test message' }, res => {
1056
- log(\`Sent to \${res} users\`);
1057
- });
1058
- \`\`\`
1059
-
1060
- _Default timeout is 20000 milliseconds (if a callback function has been defined)_
1061
-
1062
- \`\`\`js
1063
- sendTo('telegram.0', { user: 'UserName', text: 'Test message' }, { timeout: 2000 }, res => {
1064
- log(\`Sent to \${res} users\`);
1065
- });
1066
- \`\`\`
1067
-
1068
- ### sendToAsync
1069
-
1070
- \`\`\`js
1071
- await sendToAsync(adapter, command, message);
1072
- await sendToAsync(adapter, command, message, options);
1073
- \`\`\`
1074
-
1075
- Same as sendTo, but with \`promise\`.
1076
-
1077
- Example:
1078
-
1079
- \`\`\`js
1080
- const res = await sendToAsync('sql.0', 'getEnabledDPs', {});
1081
- log(JSON.stringify(res));
1082
- \`\`\`
1083
-
1084
- ### sendToHost
1085
-
1086
- \`\`\`js
1087
- sendToHost(hostName, command, message, callback);
1088
- \`\`\`
1089
-
1090
- Send a message to controller instance.
1091
-
1092
- The following commands are supported:
1093
-
1094
- - \`"cmdExec"\`
1095
- - \`"getRepository"\`
1096
- - \`"getInstalled"\`
1097
- - \`"getVersion"\`
1098
- - \`"getDiagData"\`
1099
- - \`"getLocationOnDisk"\`
1100
- - \`"getDevList"\`
1101
- - \`"getLogs"\`
1102
- - \`"getHostInfo"\`
1103
-
1104
- It is rather specific commands and are not required often.
1105
-
1106
- Example:
1107
-
1108
- \`\`\`js
1109
- sendToHost('myComputer', 'cmdExec', { data: 'ls /' }, res => {
1110
- log('List of files: ' + res.data);
1111
- });
1112
- \`\`\`
1113
-
1114
- **Notice:** you must enable _Enable command "setObject"_ option to call it.
1115
-
1116
- ### sendToHostAsync
1117
-
1118
- \`\`\`js
1119
- await sendToHostAsync(hostName, command, message);
1120
- \`\`\`
1121
-
1122
- Same as sendToHost, but with \`promise\`.
1123
-
1124
- ### setInterval
1125
-
1126
- \`\`\`js
1127
- setInterval(callback, ms, arg1, arg2, arg3, arg4);
1128
- \`\`\`
1129
-
1130
- Same as javascript \`setInterval\`.
1131
-
1132
- ### clearInterval
1133
-
1134
- \`\`\`js
1135
- clearInterval(id);
1136
- \`\`\`
1137
-
1138
- Same as javascript \`clearInterval\`.
1139
-
1140
- ### setTimeout
1141
-
1142
- \`\`\`js
1143
- setTimeout(callback, ms, arg1, arg2, arg3, arg4);
1144
- \`\`\`
1145
-
1146
- Same as javascript \`setTimeout\`.
1147
-
1148
- ### clearTimeout
1149
-
1150
- \`\`\`js
1151
- clearTimeout(id);
1152
- \`\`\`
1153
-
1154
- Same as javascript \`clearTimeout\`.
1155
-
1156
- ### setImmediate
1157
-
1158
- \`\`\`js
1159
- setImmediate(callback, arg1, arg2, arg3, arg4);
1160
- \`\`\`
1161
-
1162
- Same as javascript \`setImmediate\` and almost the same as \`setTimeout(callback, 0, arg1, arg2, arg3, arg4)\` but with higher priority.
1163
-
1164
- ### formatDate
1165
-
1166
- \`\`\`js
1167
- formatDate(millisecondsOrDate, format);
1168
- \`\`\`
1169
-
1170
- #### Parameters:
1171
-
1172
- - \`millisecondsOrDate\`: number of milliseconds from state.ts or state.lc (Number milliseconds from 1970.01.01 00:00:00) or javascript _new Date()_ object or number of milliseconds from _(new Date().getTime())_
1173
- - \`format\`: Can be \`null\`, so the system time format will be used, otherwise
1174
-
1175
- * YYYY, JJJJ, ГГГГ - full year, e.g 2015
1176
- * YY, JJ, ГГ - short year, e.g 15
1177
- * MM, ММ(cyrillic) - full month, e.g., 01
1178
- * M, М(cyrillic) - short month, e.g., 1
1179
- * DD, TT, ДД - full day, e.g., 02
1180
- * D, T, Д - short day, e.g., 2
1181
- * hh, SS, чч - full hours, e.g., 03
1182
- * h, S, ч - short hours, e.g., 3
1183
- * mm, мм(cyrillic) - full minutes, e.g., 04
1184
- * m, м(cyrillic) - short minutes, e.g., 4
1185
- * ss, сс(cyrillic) - full seconds, e.g., 05
1186
- * s, с(cyrillic) - short seconds, e.g., 5
1187
- * sss, ссс(cyrillic) - milliseconds
1188
- * WW, НН(cyrillic) - full week day as text
1189
- * W, Н(cyrillic) - short week day as text
1190
- * OO, ОО(cyrillic) - full month as text
1191
- * OOO, ООО(cyrillic) - full month as text as genitiv
1192
- * O, О(cyrillic) - short month as text
1193
-
1194
- #### Example
1195
-
1196
- \`\`\`js
1197
- formatDate(new Date(), 'YYYY-MM-DD'); // => Date "2015-02-24"
1198
- formatDate(new Date(), 'hh:mm'); // => Hours and minutes "17:41"
1199
- formatDate(state.ts); // => "24.02.2015"
1200
- formatDate(state.ts, 'JJJJ.MM.TT SS:mm:ss.sss'); // => "2015.02.15 17:41:98.123"
1201
- formatDate(new Date(), 'WW'); // => Day of week "Tuesday"
1202
- formatDate(new Date(), 'W'); // => Day of week "Tu"
1203
- \`\`\`
1204
-
1205
- ### formatTimeDiff
1206
-
1207
- \`\`\`js
1208
- formatTimeDiff(milliseconds, format);
1209
- \`\`\`
1210
-
1211
- #### Parameters:
1212
-
1213
- - \`milliseconds\`: difference in milliseconds\\*
1214
- - \`format\`: Can be \`null\`, so the \`hh:mm:ss\` format will be used, otherwise
1215
-
1216
- * DD, TT, ДД - full day, e.g., 02
1217
- * D, T, Д - short day, e.g., 2
1218
- * hh, SS, чч - full hours, e.g., 03
1219
- * h, S, ч - short hours, e.g., 3
1220
- * mm, мм(cyrillic) - full minutes, e.g., 04
1221
- * m, м(cyrillic) - short minutes, e.g., 4
1222
- * ss, сс(cyrillic) - full seconds, e.g., 05
1223
- * s, с(cyrillic) - short seconds, e.g., 5
1224
-
1225
- #### Example
1226
-
1227
- \`\`\`js
1228
- formatTimeDiff(60000, 'mm:ss'); // => "01:00"
1229
-
1230
- const diff = 172800000 + 10800000 + 540000 + 15000; // 2 days, 3 hours, 9 minutes + 15 secoonds
1231
- formatTimeDiff(diff); // "51:09:15"
1232
- formatTimeDiff(diff, 'DD hh:mm'); // "02 03:09"
1233
- formatTimeDiff(diff, 'D hh:mm'); // "2 03:09"
1234
- formatTimeDiff(diff, 'hh:mm:ss'); // "51:09:15"
1235
- formatTimeDiff(diff, 'h:m:s'); // "51:9:15"
1236
- formatTimeDiff(diff, 'hh:mm'); // "51:09"
1237
- formatTimeDiff(diff, 'mm:ss'); // "3069:15"
1238
- formatTimeDiff(diff, 'hh'); // "51"
1239
- formatTimeDiff(diff, 'mm'); // "3069"
1240
- \`\`\`
1241
-
1242
- ### getDateObject
1243
-
1244
- \`\`\`js
1245
- getDateObject(stringOrNumber);
1246
- \`\`\`
1247
-
1248
- Converts string or number to a Date object.
1249
- If only hours are given, it will add current date to it and will try to convert.
1250
-
1251
- \`\`\`js
1252
- getDateObject('20:00'); // 2024-05-18T18:00:00.000Z
1253
- getDateObject('2024-01-01'); // 2024-01-01T00:00:00.000Z
1254
- \`\`\`
1255
-
1256
- ### formatValue
1257
-
1258
- \`\`\`js
1259
- formatValue(value, decimals, format);
1260
- \`\`\`
1261
-
1262
- Formats any value (strings too) to number. Replaces point with comma if configured in system.
1263
- Decimals specify digits after comma. The default value is 2.
1264
- Format is optional:
1265
-
1266
- - '.,': 1234.567 => 1.234,56
1267
- - ',.': 1234.567 => 1,234.56
1268
- - ' .': 1234.567 => 1 234.56
1269
-
1270
- ### adapterSubscribe
1271
-
1272
- \`\`\`js
1273
- adapterSubscribe(id);
1274
- \`\`\`
1275
-
1276
- It sends to an adapter the message "subscribe" to inform adapter. If adapter has the common flag "subscribable" in case of function "subscribe" this function will be called automatically.
1277
-
1278
- ### adapterUnsubscribe
1279
-
1280
- \`\`\`js
1281
- adapterUnsubscribe(id);
1282
- \`\`\`
1283
-
1284
- It sends to an adapter the message \`unsubscribe\` to inform adapter to not poll the values.
1285
-
1286
- ### $ - Selector
1287
-
1288
- \`\`\`js
1289
- $(selector).on(function (obj) {});
1290
- $(selector).toArray(); // Requires version >= 8.2.0
1291
- $(selector).each(function (id, i) {});
1292
- $(selector).setState(value, ack);
1293
- $(selector).getState();
1294
- \`\`\`
1295
-
1296
- Format of selector:
1297
-
1298
- \`\`\`js
1299
- 'name[commonAttr=something1](enumName=something2){nativeName=something3}[id=idfilter][state.id=idfilter]';
1300
- \`\`\`
1301
-
1302
- name can be: state, channel, device or schedule
1303
- \`idfilter\` can have wildcards '\\*'
1304
-
1305
- Prefixes **_(not implemented - should be discussed)_** :
1306
-
1307
- - \\# - take by name and not by id
1308
- - . - filter by role
1309
- - § - filter by room
1310
-
1311
- **_Example_**:
1312
-
1313
- - \`$('state[id=*.STATE]')\` or \`$('state[state.id=*.STATE]')\` or \`$('*.STATE')\` - select all states where id ends with ".STATE".
1314
- - \`$('state[id='hm-rpc.0.*]')\` or \`$('hm-rpc.0.*')\` - returns all states of adapter instance hm-rpc.0
1315
- - \`$('channel(rooms=Living room)')\` - all states in room "Living room"
1316
- - \`$('channel{TYPE=BLIND}[state.id=*.LEVEL]')\` - Get all shutters of Homematic
1317
- - \`$('channel[role=switch](rooms=Living room)[state.id=*.STATE]').setState(false)\` - Switch all states with .STATE of channels with role "switch" in "Living room" to false
1318
- - \`$('channel[state.id=*.STATE](functions=Windows)').each(function (id, i) {log(id);});\` - print all states of enum "windows" in log
1319
- - \`$('schedule[id=*65]').each(function (id, i) {log(id);});\` - print all schedules with 65 at the end
1320
- - \`$('.switch §"Living room")\` - Take states with all switches in 'Living room' **_(not implemented - should be discussed)_**
1321
- - \`$('channel .switch §"Living room")\` - Take states with all switches in 'Living room' **_(not implemented - should be discussed)_**
1322
-
1323
- **_Explanation_**
1324
- Lets take a look at:
1325
-
1326
- \`\`\`js
1327
- $('channel[role=switch][state.id=*.STATE](rooms=Wohnzimmer)').on(obj => {
1328
- log('New state ' + obj.id + ' = ' + obj.state.val);
1329
- });
1330
- \`\`\`
1331
-
1332
- This code searches in channels.
1333
- Find all channels with \`common.role="switch"\` and belongs to \`enum.rooms.Wohnzimmer\`.
1334
- Take all their states, where id ends with \`".STATE"\` and make subscription on all these states.
1335
- If some of these states change, the callback will be called like for "on" function.
1336
-
1337
- Following functions are possible, setState, getState (only from first), on, each, toArray
1338
-
1339
- \`\`\`js
1340
- // Switch on all switches in "Wohnzimmer"
1341
- $('channel[role=switch][state.id=*.STATE](rooms=Wohnzimmer)').setState(true);
1342
- \`\`\`
1343
-
1344
- You can interrupt the "each" loop by returning the false value, like:
1345
-
1346
- \`\`\`js
1347
- // print two first IDs of on all switches in "Wohnzimmer"
1348
- $('channel[role=switch][state.id=*.STATE](rooms=Wohnzimmer)').each((id, i) => {
1349
- log(id);
1350
- if (i == 1) {
1351
- return false;
1352
- }
1353
- });
1354
- \`\`\`
1355
-
1356
- Or you can get a usual array of IDs and process it your own way:
1357
-
1358
- \`\`\`js
1359
- // get some state and filter only which has an \`true\` value
1360
- const enabled = $('channel[role=switch][state.id=*.STATE](rooms=Wohnzimmer)')
1361
- .toArray()
1362
- .filter(id => getState(id)?.val === true);
1363
- \`\`\`
1364
-
1365
- ### readFile
1366
-
1367
- \`\`\`js
1368
- readFile(adapter, fileName, (error, bytes) => {});
1369
- \`\`\`
1370
-
1371
- The result will be given in callback.
1372
- Read a file from DB from folder \`javascript.0\`.
1373
-
1374
- Argument _adapter_ can be omitted.
1375
-
1376
- \`\`\`js
1377
- // read vis views
1378
- readFile('vis.0', '/main/vis-views.json', (error, data) => {
1379
- log(data.substring(0, 50));
1380
- });
1381
-
1382
- // The same as
1383
- //readFile('/../vis.0/main/vis-views.json', (error, data) => {
1384
- // log(data.substring(0, 50));
1385
- //});
1386
- \`\`\`
1387
-
1388
- By default, working directory/adapter is \`javascript.0\`.
1389
-
1390
- ### writeFile
1391
-
1392
- \`\`\`js
1393
- writeFile(adapter, fileName, bytes, error => {});
1394
- \`\`\`
1395
-
1396
- The optional error code will be given in callback. Argument _adapter_ can be omitted.
1397
- \`fileName\` is the name of file in DB. If \`adapter\` is not set, all files are stored in the folder \`javascript.0\`.
1398
-
1399
- The file that looks like \`'/subfolder/file.txt'\` will be stored under \`"/javascript/subfolder/file.txt"\` and can be accessed over web server with \`"http://ip:8082/javascript/subfolder/file.txt"\`
1400
-
1401
- \`\`\`js
1402
- // store screenshot in DB
1403
- const fs = require('node:fs');
1404
- let data = fs.readFileSync('/tmp/screenshot.png');
1405
- writeFile(null, '/screenshots/1.png', data, error => {
1406
- log('file written');
1407
- });
1408
-
1409
- // The same as
1410
- //writeFile('/screenshots/1.png', data, function (error) {
1411
- // log('file written');
1412
- //});
1413
- \`\`\`
1414
-
1415
- \`\`\`js
1416
- // store file in '/vis.0' in DB
1417
- const fs = require('node:fs');
1418
- let data = fs.readFileSync('/tmp/screenshot.png');
1419
- writeFile('vis.0', '/screenshots/1.png', data, error => {
1420
- log('file written');
1421
- });
1422
- \`\`\`
1423
-
1424
- ### delFile
1425
-
1426
- \`\`\`js
1427
- delFile(adapter, fileName, error => {});
1428
- \`\`\`
1429
-
1430
- Delete file or directory. fileName is the name of file or directory in DB.
1431
-
1432
- The alternative name of this method is \`unlink\`.
1433
-
1434
- ### renameFile
1435
-
1436
- \`\`\`js
1437
- renameFile(adapter, oldName, newName, error => {});
1438
- \`\`\`
1439
-
1440
- Rename file or directory. oldName is the name of file or directory in DB and is renamed to newName.
1441
-
1442
- The alternative name of this method is \`rename\`.
1443
-
1444
- ### onFile
1445
-
1446
- \`\`\`js
1447
- onFile(id, fileName, withFile, (id, fileName, size, fileData, mimeType) => {});
1448
- // or
1449
- onFile(id, fileName, (id, fileName, size) => {});
1450
- \`\`\`
1451
-
1452
- Subscribe to file changes:
1453
-
1454
- - \`id\` is ID of an object of type \`meta\`, like \`vis.0\`
1455
- - \`fileName\` is file name or pattern, like \`main/*\` or \`main/vis-view.json\`
1456
- - \`withFile\` if the content of file should be delivered in callback or not. the delivery of file content costs memory and time, so if you want to be just informed about changes, set \`withFile\`to false.
1457
-
1458
- Arguments in callback:
1459
-
1460
- - \`id\` - ID of \`meta\` object;
1461
- - \`fileName\` - file name (not pattern);
1462
- - \`size\` - new file size;
1463
- - \`fileData\` - file content of type \`Buffer\` if file is binary (detected by extension) or \`string\`. Delivered only if \`withFile\`;
1464
- - \`mimeType\` - mime type of file, like \`image/jpeg\`. Delivered only if \`withFile\`;
1465
-
1466
- **Important**: this functionality is only available with js-controller@4.1.x or newer.
1467
-
1468
- ### offFile
1469
-
1470
- \`\`\`js
1471
- offFile(id, fileName);
1472
- // or
1473
- onFile(id, fileName);
1474
- \`\`\`
1475
-
1476
- Unsubscribe from file changes:
1477
-
1478
- - \`id\` is ID of an object of type \`meta\`, like \`vis.0\`
1479
- - \`fileName\` is file name or pattern, like \`main/*\` or \`main/vis-view.json\`
1480
-
1481
- **Important**: this functionality is only available with js-controller@4.1.x or newer.
1482
-
1483
- ### onStop
1484
-
1485
- \`\`\`js
1486
- onStop(() => {
1487
- /* do something when script is stopped */
1488
- }, timeout);
1489
- \`\`\`
1490
-
1491
- Install callback, that will be called if a script stopped. Used, e.g., to stop communication or to close connections.
1492
-
1493
- \`\`\`js
1494
- // establish connection
1495
- const conn = require('net');
1496
- // ...
1497
-
1498
- // close connection if script stopped
1499
- onStop(callback => {
1500
- if (conn) {
1501
- // close connection
1502
- conn.destroy();
1503
- }
1504
- callback();
1505
- }, 2000 /*ms*/);
1506
- \`\`\`
1507
-
1508
- \`timeout\` is 1000ms by default.
1509
-
1510
- ### getHistory
1511
-
1512
- \`\`\`js
1513
- getHistory(instance, options, (error, result, options, instance) => {});
1514
- \`\`\`
1515
-
1516
- Read history from specified instance. If no instance is specified, the system default history instance will be taken.
1517
-
1518
- \`\`\`js
1519
- // Read history of 'system.adapter.admin.0.memRss' from sql driver
1520
- const end = new Date().getTime();
1521
- getHistory(
1522
- 'sql.0',
1523
- {
1524
- id: 'system.adapter.admin.0.memRss',
1525
- start: end - 3600000,
1526
- end: end,
1527
- aggregate: 'm4',
1528
- timeout: 2000,
1529
- },
1530
- (err, result) => {
1531
- if (err) console.error(err);
1532
- if (result) {
1533
- for (let i = 0; i < result.length; i++) {
1534
- log(result[i].id + ' ' + new Date(result[i].ts).toISOString());
1535
- }
1536
- }
1537
- },
1538
- );
1539
- \`\`\`
1540
-
1541
- Possible options you can find [here](https://github.com/ioBroker/ioBroker.history#access-values-from-javascript-adapter).
1542
-
1543
- Additionally, to these parameters you must specify "id" and you may specify timeout (default: 20000ms).
1544
-
1545
- One more example:
1546
-
1547
- \`\`\`js
1548
- // Get last 50 entries from default history instance with no aggregation:
1549
- getHistory(
1550
- {
1551
- id: 'system.adapter.admin.0.alive',
1552
- aggregate: 'none',
1553
- count: 50,
1554
- },
1555
- (err, result) => {
1556
- if (err) console.error(err);
1557
- if (result) {
1558
- for (let i = 0; i < result.length; i++) {
1559
- log(result[i].id + ' ' + new Date(result[i].ts).toISOString());
1560
- }
1561
- }
1562
- },
1563
- );
1564
- \`\`\`
1565
-
1566
- **Note: ** of course, history must be first enabled for selected ID in admin.
1567
-
1568
- ### runScript
1569
-
1570
- \`\`\`js
1571
- runScript('scriptName', () => {
1572
- // Callback is optional
1573
- log('Srcipt started, but not yet executed');
1574
- });
1575
- \`\`\`
1576
-
1577
- Starts or restarts other scripts (and itself too) by name.
1578
-
1579
- \`\`\`js
1580
- // restart script
1581
- runScript('groupName.scriptName1');
1582
- \`\`\`
1583
-
1584
- ### runScriptAsync
1585
-
1586
- Same as runScript, but with \`promise\`.
1587
-
1588
- \`\`\`js
1589
- runScriptAsync('scriptName').then(() => log('Script started, but not yet executed'));
1590
-
1591
- // or
1592
-
1593
- await runScriptAsync('scriptName');
1594
- log(\`Script was restarted\`);
1595
- \`\`\`
1596
-
1597
- ### startScript
1598
-
1599
- \`\`\`js
1600
- startScript('scriptName', ignoreIfStarted, callback);
1601
- \`\`\`
1602
-
1603
- It starts the script. If \`ignoreIfStarted\` set to true, nothing will be done if a script yet running, otherwise the script will be restarted.
1604
-
1605
- \`\`\`js
1606
- startScript('scriptName', true); // start script if not started
1607
- \`\`\`
1608
-
1609
- ### startScriptAsync
1610
-
1611
- Same as runScript, but with \`promise\`.
1612
-
1613
- \`\`\`js
1614
- startScriptAsync('scriptName', ignoreIfStarted).then(started =>
1615
- log(\`Script was \${started ? 'started' : 'already started'}\`),
1616
- );
1617
-
1618
- // or
1619
-
1620
- const started = await startScriptAsync('scriptName', ignoreIfStarted);
1621
- log(\`Script was \${started ? 'started' : 'already started'}\`);
1622
- \`\`\`
1623
-
1624
- It starts the script. If \`ignoreIfStarted\` set to true, nothing will be done if a script yet running, otherwise the script will be restarted.
1625
-
1626
- \`\`\`js
1627
- startScript('scriptName', true); // start script if not started
1628
- \`\`\`
1629
-
1630
- ### stopScript
1631
-
1632
- \`\`\`js
1633
- stopScript('scriptName', callback);
1634
- \`\`\`
1635
-
1636
- If stopScript is called without arguments, it will stop itself:
1637
-
1638
- \`\`\`js
1639
- stopScript();
1640
- \`\`\`
1641
-
1642
- ### stopScriptAsync
1643
-
1644
- Same as stopScript, but with \`promise\`:
1645
-
1646
- \`\`\`js
1647
- stopScriptAsync('scriptName').then(stopped => log(\`Script was \${stopped ? 'stopped' : 'already stopped'}\`));
1648
-
1649
- //or
1650
- const stopped = await stopScriptAsync('scriptName');
1651
- log(\`Script was \${stopped ? 'stopped' : 'already stopped'}\`);
1652
- \`\`\`
1653
-
1654
- If stopScript is called without arguments, it will stop itself:
1655
-
1656
- \`\`\`js
1657
- stopScript();
1658
- \`\`\`
1659
-
1660
- ### isScriptActive
1661
-
1662
- \`\`\`js
1663
- isScriptActive('scriptName');
1664
- \`\`\`
1665
-
1666
- Returns if a script enabled or disabled. Please note that that does not give back if the script is now running or not.
1667
- The script can be finished, but still activated.
1668
-
1669
- It is not a function. It is a variable with \`javascript\` instance, that is visible in script's scope.
1670
-
1671
- ### toInt
1672
-
1673
- ### toFloat
1674
-
1675
- ### toBoolean
1676
-
1677
- ### jsonataExpression
1678
-
1679
- ### wait
1680
-
1681
- Just pause the execution of the script.
1682
- Warning this function is \`promise\` and must be called as follows:
1683
-
1684
- \`\`\`js
1685
- await wait(1000);
1686
- \`\`\`
1687
-
1688
- ### sleep
1689
-
1690
- Same as [wait](#wait)
1691
-
1692
- ### messageTo
1693
-
1694
- \`\`\`js
1695
- messageTo(
1696
- { instance: 'instance', script: 'script.js.common.scriptName', message: 'messageName' },
1697
- data,
1698
- { timeout: 1000 },
1699
- result => log(JSON.stringify(result)),
1700
- );
1701
- \`\`\`
1702
-
1703
- It sends via the "message bus" the message to some other script. Or even to some handler in the same script.
1704
-
1705
- Timeout for callback is 5 seconds by default.
1706
-
1707
- The target could be shorted to:
1708
-
1709
- \`\`\`js
1710
- messageTo('messageName', data, result => {
1711
- log(JSON.stringify(result));
1712
- });
1713
- \`\`\`
1714
-
1715
- Callback and options are optional and timeout is by default 5000 milliseconds (if callback provided).
1716
-
1717
- \`\`\`js
1718
- messageTo('messageName', dataWithNoResponse);
1719
- \`\`\`
1720
-
1721
- ### messageToAsync
1722
-
1723
- \`\`\`js
1724
- onMessage('myTopic', async (data, callback) => {
1725
- log(data);
1726
-
1727
- if (!data.myPayload) {
1728
- // return error (promise reject)
1729
- callback({ error: 'something went wrong!!' });
1730
- } else {
1731
- // return result (promise resolve)
1732
- callback({ result: 'ok' });
1733
- }
1734
- });
1735
-
1736
- (async () => {
1737
- try {
1738
- const msg = await messageToAsync(
1739
- { instance: 0, script: 'script.js.test2', message: 'myTopic' },
1740
- { myPayload: true },
1741
- { timeout: 1000 },
1742
- );
1743
- log(\`Done with: \${JSON.stringify(msg)}\`);
1744
- } catch (error) {
1745
- // contents of result.error
1746
- console.error(error);
1747
- }
1748
- })();
1749
- \`\`\`
1750
-
1751
- ### onMessage
1752
-
1753
- \`\`\`js
1754
- onMessage('messageName', (data, callback) => {
1755
- log(\`Received data: \${data}\`);
1756
- callback({ result: Date.now() });
1757
- });
1758
- \`\`\`
1759
-
1760
- Subscribes on JavaScript adapter message bus and delivers response via callback.
1761
- The response from script which sends response as first will be accepted as answer, all other answers will be ignored.
1762
-
1763
- To send a message to a JavaScript script which is then received by this handler, use [messageTo](#messageTo).
1764
-
1765
- To send a message from any other adapter use
1766
-
1767
- \`\`\`js
1768
- adapter.sendTo('javascript.0', 'toScript', {
1769
- script: 'script.js.messagetest',
1770
- message: 'messageName',
1771
- data: {
1772
- flag: true,
1773
- },
1774
- });
1775
- \`\`\`
1776
-
1777
- to send a message from CLI use
1778
-
1779
- \`\`\`bash
1780
- iob message javascript.0 toScript '{"script": "script.js.messagetest", "message": "messageName", "data": { "flag": true }}'
1781
- \`\`\`
1782
-
1783
- ### onMessageUnregister
1784
-
1785
- \`\`\`js
1786
- const id = onMessage('messageName', (data, callback) => {
1787
- log(data);
1788
- callback(Date.now());
1789
- });
1790
-
1791
- // unsubscribe specific handler
1792
- onMessageUnregister(id);
1793
- // or unsubscribe by name
1794
- onMessageUnregister('messageName');
1795
- \`\`\`
1796
-
1797
- Unsubscribes from this message.
1798
-
1799
- ### onLog
1800
-
1801
- \`\`\`js
1802
- onLog('error', data => {
1803
- sendTo('telegram.0', { user: 'UserName', text: data.message });
1804
- log('Following was sent to telegram: ' + data.message);
1805
- });
1806
- \`\`\`
1807
-
1808
- Subscribe on logs with specified severity.
1809
-
1810
- _Important:_ you cannot output logs in handler with the same severity to avoid infinite loops.
1811
-
1812
- E.g., this will produce no logs:
1813
-
1814
- \`\`\`js
1815
- onLog('error', data => {
1816
- console.error('Error: ' + data.message);
1817
- });
1818
- \`\`\`
1819
-
1820
- To receive all logs the \`*\` could be used. In this case, the log output in handler will be disabled completely.
1821
-
1822
- \`\`\`js
1823
- onLog('*', data => {
1824
- console.error('Error: ' + data.message); // will produce no logs
1825
- });
1826
- \`\`\`
1827
-
1828
- ### onLogUnregister
1829
-
1830
- \`\`\`js
1831
- function logHandler(data) {
1832
- console.error('Error: ' + data.message);
1833
- }
1834
- const id = onLog('warn', logHandler);
1835
-
1836
- // unsubscribe by ID
1837
- onLogUnregister(id);
1838
- // or unsubscribe by function handler
1839
- onLogUnregister(logHandler);
1840
- // or unsubscribe all handlers with specific severity
1841
- onLogUnregister('warn');
1842
- \`\`\`
1843
-
1844
- Unsubscribes from these logs.
1845
-
1846
- ### httpGet
1847
-
1848
- _Requires version >= 7.9.0_
1849
-
1850
- \`\`\`js
1851
- httpGet('http://jsonplaceholder.typicode.com/posts', { timeout: 1000 }, (err, response) => {
1852
- if (!err) {
1853
- console.log(response.statusCode);
1854
- console.log(response.data);
1855
- } else {
1856
- console.error(err);
1857
- }
1858
- });
1859
- \`\`\`
1860
-
1861
- Download file to ioBroker file system:
1862
-
1863
- \`\`\`js
1864
- httpGet('http://1.2.3.4/image.jpg', { responseType: 'arraybuffer' }, async (err, response) => {
1865
- if (!err) {
1866
- writeFile('0_userdata.0', 'test.jpg', response.data, err => {
1867
- if (err) {
1868
- console.error(err);
1869
- }
1870
- });
1871
- } else {
1872
- console.error(err);
1873
- }
1874
- });
1875
- \`\`\`
1876
-
1877
- Disable certificate validation - _Requires version >= 8.4.0_
1878
-
1879
- \`\`\`js
1880
- httpGet('http://jsonplaceholder.typicode.com/posts', { validateCertificate: false }, (err, response) => {
1881
- if (!err) {
1882
- console.log(response.statusCode);
1883
- console.log(response.data);
1884
- } else {
1885
- console.error(err);
1886
- }
1887
- });
1888
- \`\`\`
1889
-
1890
- ### httpPost
1891
-
1892
- _Requires version >= 7.9.0_
1893
-
1894
- \`\`\`js
1895
- httpPost(
1896
- 'http://jsonplaceholder.typicode.com/posts',
1897
- { title: 'foo', body: 'bar', userId: 1 },
1898
- { timeout: 1000 },
1899
- (error, response) => {
1900
- if (!error) {
1901
- console.log(response.statusCode);
1902
- console.log(response.data);
1903
- console.log(response.headers);
1904
- } else {
1905
- console.error(error);
1906
- }
1907
- },
1908
- );
1909
- \`\`\`
1910
-
1911
- With custom headers and authentication
1912
-
1913
- \`\`\`js
1914
- httpPost(
1915
- 'http://jsonplaceholder.typicode.com/posts',
1916
- {
1917
- title: 'foo',
1918
- body: 'bar',
1919
- userId: 1,
1920
- },
1921
- {
1922
- timeout: 2000,
1923
- basicAuth: {
1924
- user: 'admin',
1925
- password: 'dg2LdALNznHFNo',
1926
- },
1927
- headers: {
1928
- Cookie: 'PHPSESSID=298zf09hf012fh2; csrftoken=u32t4o3tb3gg43; _gat=1',
1929
- },
1930
- },
1931
- (error, response) => {
1932
- if (!error) {
1933
- console.log(response.statusCode);
1934
- console.log(response.data);
1935
- console.log(response.headers);
1936
- } else {
1937
- console.error(error);
1938
- }
1939
- },
1940
- );
1941
- \`\`\`
1942
-
1943
- ### createTempFile
1944
-
1945
- _Requires version >= 8.3.0_
1946
-
1947
- \`\`\`js
1948
- httpGet(
1949
- 'https://raw.githubusercontent.com/ioBroker/ioBroker.javascript/master/admin/javascript.svg',
1950
- { responseType: 'arraybuffer' },
1951
- async (err, response) => {
1952
- if (err) {
1953
- console.error(err);
1954
- } else {
1955
- const tempFilePath = createTempFile('javascript.svg', response.data);
1956
- console.log(\`Saved to \${tempFilePath}\`);
1957
-
1958
- // Use the new path in other scripts (e.g. sendTo)
1959
- }
1960
- },
1961
- );
1962
- \`\`\`
1963
-
1964
- \`\`\`js
1965
- onFile('0_userdata.0', 'test.jpg', true, async (id, fileName, size, data, mimeType) => {
1966
- const tempFilePath = createTempFile(fileName, response.data);
1967
-
1968
- // Use the new path in other scripts (e.g. sendTo)
1969
- });
1970
- \`\`\`
1971
-
1972
- ## Global script variables
1973
-
1974
- ### scriptName
1975
-
1976
- \`scriptName\` - The name of the script.
1977
-
1978
- \`\`\`js
1979
- log(\`Script \${scriptName} started!\`);
1980
- \`\`\`
1981
-
1982
- ### instance
1983
-
1984
- \`instance\` - The JavaScript instance where thia script is executed (e.g. \`0\`).
1985
-
1986
- \`\`\`js
1987
- log(\`Script \${scriptName} started started by \${instance}\`);
1988
- \`\`\`
1989
-
1990
- ### defaultDataDir
1991
-
1992
- \`defaultDataDir\` - Absolute path to iobroker-data.
1993
-
1994
- \`\`\`js
1995
- log(\`Data dir: \${defaultDataDir}\`);
1996
- \`\`\`
1997
-
1998
- ### verbose
1999
-
2000
- \`verbose\` - Verbose mode enabled?
2001
-
2002
- \`\`\`js
2003
- log(\`Verbose mode: \${verbose ? 'enabled' : 'disabled'}\`);
2004
-
2005
- // Example
2006
- if (verbose) {
2007
- log('...');
2008
- }
2009
- \`\`\`
2010
-
2011
- ## Option - "Do not subscribe all states on start"
2012
-
2013
- There are two modes of subscribing to states:
2014
-
2015
- - Adapter subscribes to all changes at start and receives all changes of all states (it is easy to use getStates(id), but requires more CPU and RAM):
2016
-
2017
- \`\`\`js
2018
- log(getState('someID').val);
2019
- \`\`\`
2020
-
2021
- - Adapter subscribes every time on specified ID if "on/subscribe" called. In this mode, the adapter receives only updates for desired states.
2022
- It is very performed and RAM efficiency, but you cannot access states directly in getState. You must use callback to get the result of state:
2023
-
2024
- \`\`\`js
2025
- getState('someID', (error, state) => {
2026
- log(state.val);
2027
- });
2028
- \`\`\`
2029
-
2030
- It is because the adapter does not have the value of state in RAM and must ask central DB for the value.
2031
-
2032
- ## Scripts activity
2033
-
2034
- There is a possibility to enable and disable scripts via states. For every script, the state will be created with the name \`javascript.INSTANCE.scriptEnabled.SCRIPT_NAME\`.
2035
- Scripts can be activated and deactivated by controlling this state with \`ack=false\`.
2036
- `;export{e as default};