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