iobroker.digitalstrom 2.3.0 → 3.0.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.
@@ -0,0 +1,3390 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.DSSStructure = void 0;
37
+ const dssConstants = __importStar(require("./constants"));
38
+ const dssQueue_1 = require("./dssQueue");
39
+ const dssSmartHomeSync_1 = require("./dssSmartHomeSync");
40
+ const configUtils_1 = require("./configUtils");
41
+ const SMART_HOME_METER_RETRY_BASE = 5 * 60 * 1000;
42
+ const SMART_HOME_METER_RETRY_MAX = 60 * 60 * 1000;
43
+ /**
44
+ * Eine apartmentStatusChanged-Meldung sagt nur, DASS sich etwas geaendert hat - und sie
45
+ * kommt im Normalbetrieb im Sekundentakt (jede Zaehleraenderung erzeugt eine, gemessen:
46
+ * 17 Meldungen in 75 s). Alles, was ueber Szenen und Taster laeuft, melden die
47
+ * klassischen Events laengst gezielt. Der Abgleich per Notification faengt nur den Rest
48
+ * (z.B. eine Dritt-App, die direkt einen Ausgang setzt) und darf deshalb hoechstens
49
+ * alle fuenf Minuten einen 59-KB-Statusread kosten.
50
+ */
51
+ const OUTPUT_RECONCILE_MIN_INTERVAL = 5 * 60 * 1000;
52
+ /**
53
+ * Device sensor types read once at startup when the dSS marks them invalid:
54
+ * 4 Active Power (1 W), 5 Output Current (1 mA), 65 Apparent Power (1 VA).
55
+ * Linear 12 bit encodings - the native value of device/getSensorValue equals the
56
+ * float a deviceSensorValue event would deliver. Energy meter (6) and high range
57
+ * current (64) natives have unverified resolutions and are left to the events.
58
+ */
59
+ const INITIAL_READ_SENSOR_TYPES = new Set([4, 5, 65]);
60
+ /**
61
+ * buttonInputMode values that make a device with push-button inputs the master of a
62
+ * 2-way button pair, as Device::is2WayMaster() of the dSS decides it: 6/10 pair input 1
63
+ * with input 2 ("2-way down/up with input 2"), 8/12 input 3 with input 4, and 13/14 only
64
+ * on an even dSID. The partner is always the next dSID (Device::tryGetPartnerDevice), and
65
+ * the dSS leaves it out of every device list ("do not render slave devices") - the
66
+ * installation manual says the coupled input is not listed. Its states are still in
67
+ * /usr/states (dss-mainline src/model/device.cpp, src/web/handler/jsonhelper.cpp).
68
+ * A SW-UMR200 pairs its outputs by outputMode instead and is not recognised here.
69
+ */
70
+ const TWO_WAY_MASTER_BUTTON_MODES = new Set([6, 8, 10, 12]);
71
+ const TWO_WAY_MASTER_BUTTON_MODES_EVEN_DSID = new Set([13, 14]);
72
+ /** A dSUID derived from a dSID: dSID[0..11], eight zero digits, dSID[12..23], "00". */
73
+ const DSID_BASED_DSUID = /^[0-9a-f]{12}0{8}[0-9a-f]{12}00$/;
74
+ /**
75
+ * The dSUID one dSID below the given one - the device a further input of the same
76
+ * terminal block counts up from. Only a dSUID derived from a dSID has a serial number to
77
+ * count with; a vDC device has a name based dSUID, and "one below" means nothing there.
78
+ */
79
+ function previousDsidDsuid(dSUID) {
80
+ if (typeof dSUID !== 'string' || !DSID_BASED_DSUID.test(dSUID)) {
81
+ return undefined;
82
+ }
83
+ // the last four bytes of the dSID are its serial number (= the DisplayID)
84
+ const serial = parseInt(dSUID.slice(24, 32), 16);
85
+ if (!serial) {
86
+ return undefined;
87
+ }
88
+ return `${dSUID.slice(0, 24)}${(serial - 1).toString(16).padStart(8, '0')}${dSUID.slice(32)}`;
89
+ }
90
+ /**
91
+ * The name the dSS gives a sensor state a dSS app keeps for a room:
92
+ * zone.zone<zone id>.group<group id>.type<sensor type>.<identifier>. The dSS publishes it
93
+ * under /usr/addon-states/<app>/, not under /usr/states, and reports its changes as a
94
+ * plain stateChange (dss-mainline src/model/state.cpp StateSensor and
95
+ * publishToPropertyTree, src/event/event_create.cpp createStateChangeEvent). The
96
+ * user-defined states end in a timestamp, the climate control in "passiveCooling".
97
+ */
98
+ const ZONE_SENSOR_STATE = /^zone\.zone(\d+)\.group(\d+)\.type(\d+)\.([^.]+)$/;
99
+ /**
100
+ * The characters js-controller replaces in an object id (FORBIDDEN_CHARS of its tools). The
101
+ * identifier of such a sensor state is whatever the app passed to zone.addStateSensor(),
102
+ * and only setObject/extendObject clean it: setState keeps the raw id, so the value would
103
+ * land next to its object, and the object would be created anew at every start.
104
+ */
105
+ const FORBIDDEN_ID_CHARS = /[^._\-/ :!#$%&()+=@^{}|~\p{Ll}\p{Lu}\p{Nd}]+/gu;
106
+ /**
107
+ * The Smart Home API sometimes returns numbers as strings. Empty strings, null and
108
+ * non-finite values must not silently become a real meter value (notably null -> 0).
109
+ */
110
+ function finiteMeterValue(value) {
111
+ if (typeof value === 'number') {
112
+ return Number.isFinite(value) ? value : undefined;
113
+ }
114
+ if (typeof value !== 'string' || !value.trim()) {
115
+ return undefined;
116
+ }
117
+ const numeric = Number(value);
118
+ return Number.isFinite(numeric) ? numeric : undefined;
119
+ }
120
+ /**
121
+ * Converts the meter reading of a circuit from watt seconds to kilowatt hours, rounded to
122
+ * whole watt hours.
123
+ *
124
+ * The plain division left values such as 4009.7331175000004 kWh in every write - digits
125
+ * below a watt hour that no meter of a dSM measures, and a float tail that made two equal
126
+ * readings look different. The total is rounded, not the step, so nothing adds up.
127
+ *
128
+ * @param wattSeconds meter value as the dSS reports it
129
+ * @returns kWh with at most three decimals
130
+ */
131
+ function wattSecondsToKwh(wattSeconds) {
132
+ return Math.round(wattSeconds / 3600) / 1000;
133
+ }
134
+ /**
135
+ * Turns the HTML codes older dSS firmware put into names back into the characters.
136
+ *
137
+ * The dSS ran each name set through its JSON API through escapeHTML() and handed the stored
138
+ * text out unchanged, so getCircuits answered "Schlafen &amp; Bad" (dss-mainline
139
+ * src/util.cpp escapeHTML(), src/web/handler/circuitrequesthandler.cpp setName). A name
140
+ * stored back then stays that way until it is set again, also with current firmware. One
141
+ * pass on purpose: escapeHTML() replaced "&" first, so "&amp;lt;" was a literal "&lt;" and
142
+ * has to stay one. "&#39;" is accepted as the short spelling of the same apostrophe.
143
+ *
144
+ * @param text name as the dSS stored it
145
+ * @returns the name as it was typed in the dSS
146
+ */
147
+ function decodeDssEntities(text) {
148
+ const entities = { amp: '&', quot: '"', '#039': "'", '#39': "'", lt: '<', gt: '>' };
149
+ return text.replace(/&(amp|quot|#0?39|lt|gt);/g, (match, entity) => entities[entity]);
150
+ }
151
+ class DSSStructure {
152
+ options;
153
+ dss;
154
+ adapter;
155
+ dssQueue;
156
+ smartHome;
157
+ smartHomeSync;
158
+ smartHomeMeterFailures;
159
+ smartHomeMeterRetryAfter;
160
+ smartHomeMeterRetryBase;
161
+ smartHomeMeterRetryMax;
162
+ now;
163
+ /** zuletzt gemeldeter Weg, verhindert Wiederholungen */
164
+ lastMeteringApi;
165
+ /** dito fuer die Output-Werte (info.outputApi) */
166
+ lastOutputApi;
167
+ stateMap;
168
+ dssObjects;
169
+ initialObjectValues;
170
+ processedZones;
171
+ zoneDevices;
172
+ initialScenes;
173
+ /** jedes gueltige Geraet, fuer den Abgleich per Notification */
174
+ devicesByDsuid;
175
+ /** "zone.group.scene" -> vom Nutzer vergebener Szenenname (neue API) */
176
+ scenarioNames;
177
+ /** Zonen-Id (als String) -> State-Praefix der Zonen-Sensoren */
178
+ zoneSensorBaseIds;
179
+ lastOutputReconcileAt;
180
+ outputReconcileMinInterval;
181
+ // The answers of the DSS JSON API, untyped by nature - see DssResponse in configUtils
182
+ apartmentStructure;
183
+ apartmentCircuits;
184
+ sensorValues;
185
+ temperatureControlStatus;
186
+ propertyUserStates;
187
+ propertyStates;
188
+ userActions;
189
+ reachableGroups;
190
+ groupTypes;
191
+ basicRoomScenes;
192
+ reportedOutputReadErrors;
193
+ publishedValues;
194
+ /** vDC devices the dSS rejected for the named channel read */
195
+ vdcChannelReadRejected;
196
+ /** devices with a named channel read in flight - one answer serves all channels */
197
+ vdcChannelReadPending;
198
+ /** devices whose outputs are re-read after a scene, registered once */
199
+ sceneRefreshDevices;
200
+ /**
201
+ * The apartment user states, by ioBroker id: their name in the dSS and the value
202
+ * it holds as far as the adapter knows. Kept current from both directions - what
203
+ * is written to the dSS and what the dSS reports back - so a write that would
204
+ * change nothing there can be skipped.
205
+ */
206
+ userStates;
207
+ skippedStatePrefixes;
208
+ matchedPropertyStates;
209
+ /**
210
+ * The sensor states of dSS apps other than the user-defined states, read from
211
+ * /usr/addon-states at startup - see readAddonSensorStates().
212
+ */
213
+ addonSensorStates;
214
+ addonSensorStatesRead;
215
+ pendingTimeouts;
216
+ objectsReady;
217
+ constructor(options) {
218
+ this.options = options || {};
219
+ this.dss = options.dss;
220
+ this.adapter = options.adapter;
221
+ this.dssQueue = options.dssQueue;
222
+ // Client der neuen API, null wenn die Option aus ist. Wird fuer die Zaehler und
223
+ // die Output-Werte benutzt - alles andere laeuft weiter ueber die klassische API.
224
+ this.smartHome = options.smartHome || null;
225
+ // Buendelt Output-Reads zu EINER Statusabfrage der neuen API. Ohne Client null,
226
+ // dann laufen alle Reads unveraendert klassisch.
227
+ this.smartHomeSync = this.smartHome
228
+ ? new dssSmartHomeSync_1.SmartHomeOutputSync({
229
+ structure: this,
230
+ smartHome: this.smartHome,
231
+ adapter: options.adapter,
232
+ ...(options.smartHomeSyncOptions || {}),
233
+ })
234
+ : null;
235
+ // A failed optional API must not add another failed request to every classic poll.
236
+ // Retries use the normal polling cycle, so no additional timer is needed.
237
+ this.smartHomeMeterFailures = 0;
238
+ this.smartHomeMeterRetryAfter = 0;
239
+ this.smartHomeMeterRetryBase = options.smartHomeMeterRetryBase || SMART_HOME_METER_RETRY_BASE;
240
+ this.smartHomeMeterRetryMax = options.smartHomeMeterRetryMax || SMART_HOME_METER_RETRY_MAX;
241
+ this.now = options.now || Date.now;
242
+ this.lastMeteringApi = null;
243
+ this.lastOutputApi = null;
244
+ this.stateMap = {};
245
+ this.dssObjects = {};
246
+ this.initialObjectValues = {};
247
+ this.processedZones = {};
248
+ this.zoneDevices = {};
249
+ this.initialScenes = {};
250
+ this.devicesByDsuid = {};
251
+ this.scenarioNames = {};
252
+ this.zoneSensorBaseIds = {};
253
+ // -Infinity statt 0: der allererste Abgleich darf nie an der Ratenbremse haengen
254
+ this.lastOutputReconcileAt = -Infinity;
255
+ this.outputReconcileMinInterval = options.outputReconcileMinInterval || OUTPUT_RECONCILE_MIN_INTERVAL;
256
+ this.apartmentStructure = null;
257
+ this.apartmentCircuits = null;
258
+ this.sensorValues = null;
259
+ this.temperatureControlStatus = null;
260
+ this.propertyUserStates = null;
261
+ this.propertyStates = null;
262
+ this.userActions = null;
263
+ this.reachableGroups = null;
264
+ // Private copy per structure instance: apartment specific cluster names are merged
265
+ // into this map (see parseData). Using the shared constants object directly would
266
+ // leak the cluster names of one apartment into every other adapter instance of the
267
+ // same compact process - and would permanently modify the module constants.
268
+ this.groupTypes = { ...dssConstants.groupTypes };
269
+ this.basicRoomScenes = [
270
+ 0, 5, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
271
+ ];
272
+ // Devices/channels whose output value could not be read - reported only once
273
+ this.reportedOutputReadErrors = new Set();
274
+ // The value last published to ioBroker per state id. Only the polling and
275
+ // reconciling paths consult it (setStateSafe with skipUnchanged): they re-assert
276
+ // a value the dSS still reports, which on a real installation was 7661 of 11015
277
+ // writes in three hours. An event-driven value is never suppressed - "the dSS
278
+ // reported this now" is a message even when the number repeats - and neither is
279
+ // the confirmation of a user command, which has to reach its ack.
280
+ this.publishedValues = new Map();
281
+ this.vdcChannelReadRejected = new Set();
282
+ this.vdcChannelReadPending = new Map();
283
+ this.sceneRefreshDevices = new Set();
284
+ this.userStates = new Map();
285
+ // Prefixes of zones and groups THIS adapter decided not to build objects for -
286
+ // a zone the dSS reports as not present, a group no zone can reach, a zone 0
287
+ // group without devices. Their states have no object by our own choice, so they
288
+ // are not "unassignable" and must not be reported as such.
289
+ this.skippedStatePrefixes = new Set();
290
+ // Names of the property states that were claimed by a device, circuit, zone, group
291
+ // or the apartment. Everything left over is reported by reportUnmappedStates().
292
+ this.matchedPropertyStates = new Set();
293
+ this.addonSensorStates = [];
294
+ // true once readAddonSensorStates() got an answer - only then is a room sensor state
295
+ // that is not in it really gone, see createZoneSensorStates()
296
+ this.addonSensorStatesRead = false;
297
+ this.pendingTimeouts = new Set();
298
+ // becomes true once all ioBroker objects have been created
299
+ this.objectsReady = false;
300
+ }
301
+ setClearableTimeout(func, delay) {
302
+ const timeout = setTimeout(() => {
303
+ this.pendingTimeouts.delete(timeout);
304
+ func();
305
+ }, delay);
306
+ this.pendingTimeouts.add(timeout);
307
+ return timeout;
308
+ }
309
+ clearTimeouts() {
310
+ this.pendingTimeouts.forEach(timeout => clearTimeout(timeout));
311
+ this.pendingTimeouts.clear();
312
+ this.smartHomeSync && this.smartHomeSync.stop();
313
+ }
314
+ /**
315
+ * One classic output read, written back exactly like the original inline callbacks:
316
+ * the brightness of a light goes through the light helper (it also maintains the
317
+ * boolean .state including the switch threshold), everything else lands rounded in
318
+ * the channel state. Channels without a fixed channelIndex have no classic read.
319
+ *
320
+ * options.report = false keeps info.outputApi untouched: reads the Smart Home sync
321
+ * hands over for single channels the status cannot deliver must not flip the state
322
+ * to "classic" while the Smart Home API stays in charge of everything else.
323
+ */
324
+ queueClassicOutputRead(dev, outputType, prio = 'medium', options = {}) {
325
+ const report = options.report !== false;
326
+ // A vDC device (Hue, Sonos, ...) answers ONLY the named channel read. Its
327
+ // outputs have no offset the dSS could address - getOutputValue returns
328
+ // "Could not find item. deviceOutputIndex:255" no matter which channelIndex
329
+ // the role map declares, so this comes BEFORE the offset path.
330
+ if (this.queueVdcChannelRead(dev, outputType, prio, report)) {
331
+ return;
332
+ }
333
+ const roleDef = dssConstants.outputChannelUnitRoleMap[outputType];
334
+ if (!roleDef || !roleDef.native || roleDef.native.channelIndex === undefined) {
335
+ // Channels without a fixed channelIndex never had a working offset read:
336
+ // getOutputValue needs the offset, and the getConfig fallback reads the
337
+ // class 64 bank, which only holds the shade values
338
+ this.adapter.log.debug(`No classic read for output channel ${outputType} of ${dev.dSUID}`);
339
+ return;
340
+ }
341
+ this.dssQueue.queueUpdateOutputValue(dev, roleDef.native.channelIndex, roleDef.native.nativeMax, prio, (err, value) => {
342
+ if (err) {
343
+ this.logOutputReadError(dev, outputType, err);
344
+ return;
345
+ }
346
+ if (outputType === 'brightness' && typeof dev.applyNativeLightValue === 'function') {
347
+ dev.applyNativeLightValue(value, { skipUnchanged: true });
348
+ report && this.reportOutputApi('classic');
349
+ return;
350
+ }
351
+ if (roleDef.native.nativeMax && roleDef.max) {
352
+ value = Math.round((value * roleDef.max) / roleDef.native.nativeMax);
353
+ }
354
+ const stateId = dev.outputChannelList && dev.outputChannelList[outputType];
355
+ if (!stateId) {
356
+ return;
357
+ }
358
+ this.setStateSafe(stateId, value, { skipUnchanged: true });
359
+ this.initialObjectValues[stateId] = value;
360
+ report && this.reportOutputApi('classic');
361
+ });
362
+ }
363
+ /**
364
+ * Named channel read for a vDC device: device/getOutputChannelValue2 answers with
365
+ * EVERY channel of the device in the official channel scale. Native dS terminals
366
+ * are filtered by the structure flag, and a dSS that still rejects the call
367
+ * ("This call is currently only supported on vDCs") is remembered per device.
368
+ *
369
+ * @param dev the device
370
+ * @param outputType the channel that asked - the answer serves all of them
371
+ * @param prio priority of the read
372
+ * @param report whether a successful read may flip info.outputApi
373
+ * @returns true when a read serves this channel (queued now or in flight)
374
+ */
375
+ queueVdcChannelRead(dev, outputType, prio, report) {
376
+ if (!dev || dev.isVdcDevice !== true || this.vdcChannelReadRejected.has(dev.dSUID)) {
377
+ return false;
378
+ }
379
+ const pending = this.vdcChannelReadPending.get(dev.dSUID);
380
+ if (pending) {
381
+ // One answer carries every channel - the running read serves this one too.
382
+ // Its answer may predate this trigger by the request duration; the next
383
+ // trigger refreshes, the same bound every offset read has always had.
384
+ // A joiner that is allowed to report upgrades the running read.
385
+ pending.report = pending.report || report;
386
+ return true;
387
+ }
388
+ const flags = { report };
389
+ this.vdcChannelReadPending.set(dev.dSUID, flags);
390
+ this.dssQueue.queueReadOutputChannels(dev, prio, (err, channels) => {
391
+ this.vdcChannelReadPending.delete(dev.dSUID);
392
+ if (this.isAdapterStopping()) {
393
+ return;
394
+ }
395
+ if (err) {
396
+ // requestAsync delivers an ok:false answer as a thrown DSSError -
397
+ // the rejection text sits in its message
398
+ const message = err.message || String(err);
399
+ if (message.includes('only supported on vDCs')) {
400
+ this.vdcChannelReadRejected.add(dev.dSUID);
401
+ this.adapter.log.debug(`No named channel read for ${dev.dSUID}: ${message}`);
402
+ }
403
+ else {
404
+ this.logOutputReadError(dev, outputType, err);
405
+ }
406
+ return;
407
+ }
408
+ let applied = 0;
409
+ for (const [channel, entry] of Object.entries(channels)) {
410
+ if (!dev.outputChannelList || !dev.outputChannelList[channel]) {
411
+ continue;
412
+ }
413
+ if (!entry || typeof entry.value !== 'number' || !isFinite(entry.value)) {
414
+ continue;
415
+ }
416
+ if (this.applyChannelScaleValue(dev, channel, entry.value) === 'applied') {
417
+ applied++;
418
+ }
419
+ }
420
+ applied && flags.report && this.reportOutputApi('classic');
421
+ });
422
+ return true;
423
+ }
424
+ /**
425
+ * Re-reads the outputs of a device after every scene, through the bundled status
426
+ * request - a whole room coalesces into ONE read. For device types without a read
427
+ * path of their own (jokers, and everything the type dispatch leaves generic) this
428
+ * is the only way their values follow a scene instead of waiting for the next
429
+ * reconciliation. Without the sync nothing is registered: one named read per device
430
+ * would be a burst, and that is what the reconciliation is there for.
431
+ *
432
+ * Registered once per device - createJokerDevice can be reached from two paths.
433
+ */
434
+ registerSceneOutputRefresh(dev) {
435
+ if (!this.adapter.config.initializeOutputValues || !this.smartHomeSync) {
436
+ return;
437
+ }
438
+ if (!dev.outputChannelList || !Object.keys(dev.outputChannelList).length) {
439
+ return;
440
+ }
441
+ if (this.sceneRefreshDevices.has(dev.dSUID) || !this.dss || typeof this.dss.on !== 'function') {
442
+ return;
443
+ }
444
+ const sync = this.smartHomeSync;
445
+ this.sceneRefreshDevices.add(dev.dSUID);
446
+ this.dss.on(dev.dSUID, data => {
447
+ if (data.name === 'callScene' || data.name === 'undoScene') {
448
+ sync.requestDeviceSync(dev);
449
+ }
450
+ });
451
+ }
452
+ /**
453
+ * Initial read for a device the type dispatch left generic - that is vDC hardware
454
+ * (Hue, Sonos) and a few exotic terminals, which have no typed create*Device path
455
+ * of their own and therefore never read their outputs at all.
456
+ *
457
+ * One bundled status request of the Smart Home API covers every channel of every
458
+ * device; without it a vDC device is served by its named channel read, which also
459
+ * carries all of its channels at once. A native terminal gets false here and keeps
460
+ * the offset read it always had.
461
+ *
462
+ * @param dev the device
463
+ * @param outputType any channel of the device - both reads cover all of them
464
+ * @returns true when a read is on its way
465
+ */
466
+ queueGenericInitialRead(dev, outputType) {
467
+ // ONLY a vDC device may hand its initial read over. A native terminal in this
468
+ // branch has no second way in: its channels have no fixed channelIndex, the
469
+ // caller below reads them through the channelIndex the DEVICE declares, and
470
+ // every fallback of the sync goes through queueClassicOutputRead, which gives
471
+ // up exactly there. Handing it over would lose the value silently.
472
+ if (dev.isVdcDevice !== true) {
473
+ return false;
474
+ }
475
+ if (this.smartHomeSync && this.smartHomeSync.requestDeviceSync(dev)) {
476
+ return true;
477
+ }
478
+ return this.queueVdcChannelRead(dev, outputType, 'medium', true);
479
+ }
480
+ /**
481
+ * Writes one output value that already comes in the official channel scale
482
+ * (brightness 0..100, colortemp 100..1000, ...) - the scale of the Smart Home
483
+ * API status AND of device/getOutputChannelValue2. Counterpart of the
484
+ * native-scale write in the queueClassicOutputRead callback; the same rules as
485
+ * SmartHomeOutputSync.applyValue (kept separate there for its own test rig).
486
+ */
487
+ applyChannelScaleValue(dev, outputType, value) {
488
+ const roleDef = dssConstants.outputChannelUnitRoleMap[outputType];
489
+ const stateId = dev.outputChannelList && dev.outputChannelList[outputType];
490
+ if (!roleDef || !stateId) {
491
+ return 'unsupported';
492
+ }
493
+ if (outputType === 'brightness' && typeof dev.applyNativeLightValue === 'function') {
494
+ // The light helper also maintains the boolean .state (switch threshold!),
495
+ // so the value goes back to the native 0..255 scale it expects
496
+ dev.applyNativeLightValue(Math.round(value * 2.55), { skipUnchanged: true });
497
+ return 'applied';
498
+ }
499
+ if (roleDef.type === 'boolean') {
500
+ // Boolean channel semantics are not verified against the channel scale
501
+ return 'unsupported';
502
+ }
503
+ if (outputType === 'x' || outputType === 'y') {
504
+ // CIE x/y arrive as 0..1 in the channel scale (measured live: 0.225/0.3944),
505
+ // the states hold 0..10000 (max 10000 / nativeMax 65535) - the same factor
506
+ // the offset read applies as value*max/nativeMax. Without it Math.round
507
+ // would collapse every coordinate to 0 or 1.
508
+ value *= 10000;
509
+ }
510
+ const rounded = Math.round(value);
511
+ this.setStateSafe(stateId, rounded, { skipUnchanged: true });
512
+ this.initialObjectValues[stateId] = rounded;
513
+ return 'applied';
514
+ }
515
+ /**
516
+ * Uebernimmt Sollwert und Stellgroesse der Raumtemperaturregelung aus einer
517
+ * Apartment-Status-Antwort - derselben Antwort, die ohnehin fuer die Output-Werte
518
+ * geholt wurde, es entsteht kein zusaetzlicher Request. Modus und Betriebsart
519
+ * bleiben beim klassischen Weg: ihre Zahlensemantik ist gegen die neue API nicht
520
+ * verifiziert, Grad Celsius und Prozent dagegen schon (gegen echte Anlage geprueft).
521
+ *
522
+ * @param status Antwort von getApartmentStatus()
523
+ * @returns Anzahl geschriebener Werte
524
+ */
525
+ applyZoneTemperatureStatus(status) {
526
+ const zones = (status && status.included && status.included.zones) || [];
527
+ let written = 0;
528
+ for (const zone of zones) {
529
+ const baseId = zone && this.zoneSensorBaseIds[String(zone.id)];
530
+ if (!baseId) {
531
+ continue;
532
+ }
533
+ const applications = (zone.attributes && zone.attributes.applications) || [];
534
+ const temperature = applications.find((app) => app && app.id === 'temperature');
535
+ if (!temperature) {
536
+ continue;
537
+ }
538
+ for (const [field, stateName] of [
539
+ ['setpoint', 'NominalValue'],
540
+ ['controlValue', 'ControlValue'],
541
+ ]) {
542
+ const value = temperature[field];
543
+ const stateId = `${baseId}.${stateName}`;
544
+ if (typeof value !== 'number' || !isFinite(value) || !this.dssObjects[stateId]) {
545
+ continue;
546
+ }
547
+ // Counted only when it really went out: with the comparison in front of
548
+ // setStateSafe the old unconditional count reported attempts, not writes
549
+ if (this.setStateSafe(stateId, value, { skipUnchanged: true })) {
550
+ written++;
551
+ }
552
+ }
553
+ }
554
+ return written;
555
+ }
556
+ /**
557
+ * Die Reaktion auf eine apartmentStatusChanged-Meldung des Websockets: alle
558
+ * Geraete mit Ausgaengen einmal ueber den Sync abgleichen. Hart ratenbegrenzt,
559
+ * siehe OUTPUT_RECONCILE_MIN_INTERVAL.
560
+ *
561
+ * @returns true wenn ein Abgleich angestossen wurde
562
+ */
563
+ reconcileOutputValues() {
564
+ if (!this.smartHomeSync || !this.adapter.config || !this.adapter.config.initializeOutputValues) {
565
+ return false;
566
+ }
567
+ if (this.now() - this.lastOutputReconcileAt < this.outputReconcileMinInterval) {
568
+ return false;
569
+ }
570
+ let requested = false;
571
+ for (const dev of Object.values(this.devicesByDsuid)) {
572
+ if (dev.outputChannelList && Object.keys(dev.outputChannelList).length) {
573
+ requested = this.smartHomeSync.requestDeviceSync(dev) || requested;
574
+ }
575
+ }
576
+ if (requested) {
577
+ this.lastOutputReconcileAt = this.now();
578
+ }
579
+ return requested;
580
+ }
581
+ /**
582
+ * Records which API delivered the last output values - the counterpart of
583
+ * reportMeteringApi() for info.outputApi, with the same "last successful
584
+ * writer" semantics and the same change-only reporting.
585
+ */
586
+ reportOutputApi(api) {
587
+ if (this.lastOutputApi === api) {
588
+ return;
589
+ }
590
+ this.lastOutputApi = api;
591
+ this.adapter.setState && this.adapter.setState('info.outputApi', api, true);
592
+ this.adapter.log.info(`Output values are now read via the ${api === 'smarthome' ? 'Smart Home' : 'classic'} API`);
593
+ }
594
+ init(callback) {
595
+ // Die Klarnamen der Szenen kennt nur die neue API - einmalig am Start geholt,
596
+ // bevor die Zonen verarbeitet werden. Ohne sie bleiben die bisherigen Namen.
597
+ this.loadScenarioNames(() => this.initClassicStructure(callback));
598
+ }
599
+ /**
600
+ * Laedt die vom Nutzer in digitalSTROM vergebenen Szenennamen ueber die neue API.
601
+ * Jeder Fehler ist folgenlos: die Benennung faellt auf die klassischen
602
+ * userSceneNames und die generischen Preset-Namen zurueck.
603
+ *
604
+ * @param callback laeuft immer, auch bei Fehlern
605
+ */
606
+ loadScenarioNames(callback) {
607
+ if (!this.smartHome || this.isAdapterStopping()) {
608
+ return void callback();
609
+ }
610
+ this.smartHome.getScenarios().then(answer => {
611
+ const scenarios = (answer && answer.scenarios) || [];
612
+ let named = 0;
613
+ for (const scenario of scenarios) {
614
+ const match = scenario && typeof scenario.id === 'string'
615
+ ? scenario.id.match(/^applicationZone-z(\d+)-g(\d+)-s(\d+)$/)
616
+ : null;
617
+ const name = scenario && scenario.attributes && scenario.attributes.name;
618
+ if (!match || typeof name !== 'string' || !name.trim()) {
619
+ continue;
620
+ }
621
+ this.scenarioNames[`${match[1]}.${match[2]}.${match[3]}`] = name.trim();
622
+ named++;
623
+ }
624
+ named && this.adapter.log.debug(`Loaded ${named} scene names from the Smart Home API`);
625
+ callback();
626
+ }, err => {
627
+ this.adapter.log.debug(`Could not load the scene names from the Smart Home API: ${(0, configUtils_1.errorMessage)(err)}`);
628
+ callback();
629
+ });
630
+ }
631
+ initClassicStructure(callback) {
632
+ this.dss.requestAsync('apartment', 'getStructure').then(res => {
633
+ if (!res || !res.ok || !res.result || !res.result.apartment) {
634
+ return void (callback &&
635
+ setImmediate(() => callback(`Error on apartment/getStructure: ${res?.message || res?.status_code || JSON.stringify(res)}`)));
636
+ }
637
+ this.apartmentStructure = res.result.apartment;
638
+ this.adapter.log.debug(`getStructure:${JSON.stringify(this.apartmentStructure)}`);
639
+ this.dss.requestAsync('apartment', 'getCircuits').then(res => {
640
+ if (!res || !res.ok || !res.result || !res.result.circuits) {
641
+ return void (callback &&
642
+ callback(`Error on apartment/getCircuits: ${res?.message || res?.status_code || JSON.stringify(res)}`));
643
+ }
644
+ this.apartmentCircuits = res.result.circuits;
645
+ this.adapter.log.debug(`getCircuits:${JSON.stringify(this.apartmentCircuits)}`);
646
+ this.dss.requestAsync('apartment', 'getSensorValues').then(res => {
647
+ if (!res || !res.ok || !res.result) {
648
+ return void (callback &&
649
+ callback(`Error on apartment/getSensorValues: ${res?.message || res?.status_code || JSON.stringify(res)}`));
650
+ }
651
+ this.sensorValues = res.result;
652
+ this.adapter.log.debug(`getSensorValues: ${JSON.stringify(this.sensorValues)}`);
653
+ this.dss.requestAsync('apartment', 'getTemperatureControlStatus').then(res => {
654
+ if (!res || !res.ok || !res.result) {
655
+ return void (callback &&
656
+ callback(`Error on apartment/getTemperatureControlStatus: ${res?.message || res?.status_code || JSON.stringify(res)}`));
657
+ }
658
+ this.temperatureControlStatus = res.result;
659
+ this.adapter.log.debug(`getTemperatureControlStatus: ${JSON.stringify(this.temperatureControlStatus)}`);
660
+ this.dss
661
+ .requestAsync('property', 'query', {
662
+ query: '/usr/addon-states/system-addon-user-defined-states/*(*)',
663
+ })
664
+ .then(res => {
665
+ if (!res || !res.ok || !res.result) {
666
+ return void (callback &&
667
+ callback(`Error on query user-defined-states: ${res?.message ||
668
+ res?.status_code ||
669
+ JSON.stringify(res)}`));
670
+ }
671
+ this.propertyUserStates = Array.isArray(res.result['system-addon-user-defined-states'])
672
+ ? res.result['system-addon-user-defined-states']
673
+ : [];
674
+ this.adapter.log.debug(`property user states: ${JSON.stringify(this.propertyUserStates)}`);
675
+ this.dss
676
+ .requestAsync('property', 'query', {
677
+ query: '/usr/states/*(*)',
678
+ })
679
+ .then(res => {
680
+ if (!res || !res.ok || !res.result) {
681
+ return void (callback &&
682
+ callback(`Error on query states: ${res?.message ||
683
+ res?.status_code ||
684
+ JSON.stringify(res)}`));
685
+ }
686
+ this.propertyStates = Array.isArray(res.result.states)
687
+ ? res.result.states
688
+ : [];
689
+ this.adapter.log.debug(`property states: ${JSON.stringify(this.propertyStates)}`);
690
+ this.dss
691
+ .requestAsync('property', 'query', {
692
+ query: '/usr/events/*(*)/*(*)/*(*)/*(*)/*(*)',
693
+ })
694
+ .then(res => {
695
+ if (!res || !res.ok || !res.result) {
696
+ return void (callback &&
697
+ callback(`Error on query user actions: ${res?.message ||
698
+ res?.status_code ||
699
+ JSON.stringify(res)}`));
700
+ }
701
+ this.userActions = Array.isArray(res.result.events)
702
+ ? res.result.events
703
+ : [];
704
+ this.adapter.log.debug(`property user actions: ${JSON.stringify(this.userActions)}`);
705
+ this.dss
706
+ .requestAsync('apartment', 'getReachableGroups', { id: 0 })
707
+ .then(res => {
708
+ if (!res ||
709
+ !res.ok ||
710
+ !res.result) {
711
+ return void (callback &&
712
+ callback(`Error on apartment/getReachableGroups: ${res?.message ||
713
+ res?.status_code ||
714
+ JSON.stringify(res)}`));
715
+ }
716
+ this.reachableGroups =
717
+ res.result;
718
+ this.adapter.log.debug(`getReachableGroups: ${JSON.stringify(this.reachableGroups)}`);
719
+ // Optional, it never fails the start
720
+ void this.readAddonSensorStates().then(() => this.parseData(callback));
721
+ }, err => {
722
+ return void (callback &&
723
+ callback(`Error on apartment/getReachableGroups: ${(err &&
724
+ err.message) ||
725
+ JSON.stringify(err)}`));
726
+ });
727
+ }, err => {
728
+ return void (callback &&
729
+ callback(`Error on apartment/getReachableGroups: ${(err && err.message) ||
730
+ JSON.stringify(err)}`));
731
+ });
732
+ }, err => {
733
+ return void (callback &&
734
+ callback(`Error on query states: ${(err && err.message) || JSON.stringify(err)}`));
735
+ });
736
+ }, err => {
737
+ return void (callback &&
738
+ callback(`Error on query user-defined-states: ${(err && err.message) || JSON.stringify(err)}`));
739
+ });
740
+ }, err => {
741
+ return void (callback &&
742
+ callback(`Error on apartment/getTemperatureControlStatus: ${(err && err.message) || JSON.stringify(err)}`));
743
+ });
744
+ }, err => {
745
+ return void (callback &&
746
+ callback(`Error on apartment/getSensorValues: ${(err && err.message) || JSON.stringify(err)}`));
747
+ });
748
+ }, err => {
749
+ return void (callback &&
750
+ callback(`Error on apartment/getCircuits: ${(err && err.message) || JSON.stringify(err)}`));
751
+ });
752
+ }, err => {
753
+ return void (callback &&
754
+ callback(`Error on apartment/getStructure: ${(err && err.message) || JSON.stringify(err)}`));
755
+ });
756
+ }
757
+ convertObject(data, nameField, prefilled) {
758
+ const res = prefilled || {};
759
+ if (!data || !Array.isArray(data)) {
760
+ return res;
761
+ }
762
+ data.forEach(el => {
763
+ if (typeof el !== 'object' || el[nameField] === undefined) {
764
+ return;
765
+ }
766
+ res[el[nameField]] = el;
767
+ });
768
+ return res;
769
+ }
770
+ parseData(callback) {
771
+ const apt = {
772
+ clusters: this.convertObject(this.apartmentStructure.clusters, 'id'),
773
+ floors: this.convertObject(this.apartmentStructure.floors, 'id'),
774
+ zones: this.convertObject(this.apartmentStructure.zones, 'id'),
775
+ };
776
+ Object.keys(apt.clusters).forEach(groupId => {
777
+ if (!this.groupTypes[groupId]) {
778
+ this.groupTypes[groupId] = apt.clusters[groupId].name;
779
+ }
780
+ });
781
+ if (apt.zones[0]) {
782
+ apt.zone0 = apt.zones[0]; // Zone 0 contains everything
783
+ delete apt.zones[0];
784
+ }
785
+ else {
786
+ return void (callback && setImmediate(() => callback('No devices returned in Zone 0')));
787
+ }
788
+ apt.groups = this.convertObject(apt.zone0.groups, 'id'); // enhance groups from zone 0
789
+ this.createUserActions();
790
+ this.createDevices(apt.zone0.devices, () => {
791
+ const reachableZoneGroups = this.convertObject(this.reachableGroups.zones, 'zoneID');
792
+ this.sensorValues.zones = this.convertObject(this.sensorValues.zones, 'id');
793
+ this.temperatureControlStatus.zones = this.convertObject(this.temperatureControlStatus.zones, 'id');
794
+ this.createApartment(apt, reachableZoneGroups, () => {
795
+ this.reportUnmappedStates(apt.zone0.devices);
796
+ callback && callback(null);
797
+ });
798
+ });
799
+ }
800
+ /**
801
+ * Reads the sensor states that dSS apps keep per room.
802
+ *
803
+ * The climate control keeps zone.zone<id>.group0.type9.passiveCooling for a room it
804
+ * regulates: active while the room is above its passive cooling threshold. The dSS
805
+ * publishes such states under /usr/addon-states/<app>/ and reports their changes as a
806
+ * plain stateChange, so they are neither in /usr/states nor among the user-defined
807
+ * states. A room that stays on one side of its threshold sends no event for weeks,
808
+ * so the value has to be read at startup. One property/query2 answers
809
+ * {<app>: {<state name>: {name, value, state, callOrigin}}} (dss-mainline
810
+ * src/propertyquery.cpp runFor2).
811
+ *
812
+ * Optional: a dSS without that node or without query2 only leaves the list empty. It
813
+ * never throws and never fails the start.
814
+ */
815
+ async readAddonSensorStates() {
816
+ try {
817
+ const res = await this.dss.requestAsync('property', 'query2', {
818
+ query: '/usr/addon-states/*(*)/*(*)',
819
+ });
820
+ if (!res || !res.ok || !res.result || typeof res.result !== 'object') {
821
+ this.adapter.log.debug(`No sensor states of dSS apps: ${(res && (res.message || res.status_code)) || JSON.stringify(res)}`);
822
+ return;
823
+ }
824
+ this.addonSensorStates = DSSStructure.collectAddonSensorStates(res.result);
825
+ this.addonSensorStatesRead = true;
826
+ this.adapter.log.debug(`sensor states of dSS apps: ${JSON.stringify(this.addonSensorStates)}`);
827
+ }
828
+ catch (err) {
829
+ this.adapter.log.debug(`Could not read the sensor states of dSS apps: ${(0, configUtils_1.errorMessage)(err)}`);
830
+ }
831
+ }
832
+ /**
833
+ * The room sensor states in a property/query2 answer of /usr/addon-states.
834
+ *
835
+ * The user-defined states are left out, they already are apartment.userStates. So is
836
+ * everything not named like a room sensor state: helper states such as
837
+ * "<dSUID>_open-tilded" have no object on purpose, and the sensor states of a device
838
+ * are named once when they change, like every other state without an object.
839
+ *
840
+ * @param tree answer of the query, keyed by app and
841
+ * state name
842
+ */
843
+ static collectAddonSensorStates(tree) {
844
+ const result = [];
845
+ if (!tree || typeof tree !== 'object') {
846
+ return result;
847
+ }
848
+ // A dSS20 1.19.13 lists its climate control twice, as system-addon-heating-controller
849
+ // and as heating-controller, with the very same states (measured with probe-states.js).
850
+ // A state name is unique in the dSS - an event carries nothing else - so the first
851
+ // entry wins. A second one would become a second object, "<identifier>_type9", and
852
+ // take the events away from the first.
853
+ const seen = new Set();
854
+ Object.keys(tree).forEach(addon => {
855
+ const states = tree[addon];
856
+ if (addon === 'system-addon-user-defined-states' || !states || typeof states !== 'object') {
857
+ return;
858
+ }
859
+ Object.keys(states).forEach(key => {
860
+ const entry = states[key];
861
+ if (!entry || typeof entry !== 'object') {
862
+ return;
863
+ }
864
+ const name = typeof entry.name === 'string' && entry.name ? entry.name : key;
865
+ const match = ZONE_SENSOR_STATE.exec(name);
866
+ if (!match || seen.has(name)) {
867
+ return;
868
+ }
869
+ seen.add(name);
870
+ result.push({
871
+ ...entry,
872
+ name,
873
+ addon,
874
+ zoneId: parseInt(match[1], 10),
875
+ groupId: parseInt(match[2], 10),
876
+ sensorType: parseInt(match[3], 10),
877
+ identifier: match[4],
878
+ });
879
+ });
880
+ });
881
+ return result;
882
+ }
883
+ /**
884
+ * Reports property states that no part of the structure claimed.
885
+ *
886
+ * The DSS delivers all user states of `/usr/states` in one list. They are assigned by
887
+ * their name prefix: `dev.<dSUID>.` to a device, `dsm.<dSUID>.` to a circuit,
888
+ * `zone.<id>.` to a room, `zone.<id>.group.<id>.` to a group, everything without a dot
889
+ * to the apartment. A state whose prefix belongs to none of them - for example a
890
+ * sensor that is bound to a device the DSS does not list in the apartment structure -
891
+ * would silently have no object at all.
892
+ *
893
+ * Reported once at info level with the exact names, so such a state can be assigned
894
+ * afterwards instead of just being missing. The coupled input of a 2-way button is
895
+ * not missing, the dSS hides it on purpose; it is named on debug with its device.
896
+ * A room sensor state of a dSS app that got no object is named in the same line.
897
+ *
898
+ * @param [structureDevices] all devices of zone 0, including the ones this
899
+ * adapter skipped - the partner of a 2-way button is recognised by its neighbour
900
+ */
901
+ reportUnmappedStates(structureDevices) {
902
+ if (!Array.isArray(this.propertyStates)) {
903
+ return;
904
+ }
905
+ const leftOver = this.propertyStates
906
+ .filter(state => state && typeof state.name === 'string' && !this.matchedPropertyStates.has(state.name))
907
+ .map(state => state.name);
908
+ const skippedPrefixes = [...this.skippedStatePrefixes];
909
+ const notSkipped = leftOver.filter(name => !skippedPrefixes.some(prefix => name.startsWith(prefix)));
910
+ // The sensor states of dSS apps (see readAddonSensorStates) get an object only in
911
+ // group 0 of a room this adapter built. Their names spell zone and group
912
+ // differently ("zone.zone4.group48."), so a skipped zone or group is compared by id.
913
+ const addonLeftOver = this.addonSensorStates.filter(state => !this.matchedPropertyStates.has(state.name));
914
+ const addonNotSkipped = addonLeftOver.filter(state => !this.skippedStatePrefixes.has(`zone.${state.zoneId}.`) &&
915
+ !this.skippedStatePrefixes.has(`zone.${state.zoneId}.group.${state.groupId}.`));
916
+ const skipped = leftOver.length - notSkipped.length + addonLeftOver.length - addonNotSkipped.length;
917
+ if (skipped) {
918
+ // Worth a line, but not one that asks anybody to open an issue: on a real
919
+ // installation 42 of 45 leftovers were of this kind and buried the three
920
+ // names that really belonged to nobody.
921
+ this.adapter.log.debug(`${skipped} DSS state(s) belong to zones or groups this adapter skipped on purpose and are not reported`);
922
+ }
923
+ const devicesByDsuid = new Map();
924
+ (Array.isArray(structureDevices) ? structureDevices : []).forEach(dev => {
925
+ dev && typeof dev.dSUID === 'string' && devicesByDsuid.set(dev.dSUID, dev);
926
+ });
927
+ // Those three names turned out not to belong to nobody either: each was the
928
+ // second input of a GR-KL300 whose push buttons are wired as a 2-way switch. The
929
+ // dSS couples that input to the first one and hides it from getStructure, while
930
+ // the binary input state of its alternative use (a 230 V sensor) stays in
931
+ // /usr/states. There is nothing to map - wired as a 2-way switch that input is a
932
+ // push button, not a sensor - so it is named on debug, with its device.
933
+ const hiddenPartners = [];
934
+ const unmapped = [];
935
+ notSkipped.forEach(name => {
936
+ const master = DSSStructure.twoWayMasterOf(name, devicesByDsuid);
937
+ if (master) {
938
+ const hwInfo = master.hwInfo ? `, ${master.hwInfo}` : '';
939
+ hiddenPartners.push(`${name} (2nd input of "${master.name || master.dSUID}"${hwInfo})`);
940
+ }
941
+ else {
942
+ unmapped.push(name);
943
+ }
944
+ });
945
+ if (hiddenPartners.length) {
946
+ this.adapter.log.debug(`${hiddenPartners.length} DSS state(s) belong to the coupled input of a 2-way button, ` +
947
+ `which the dSS does not list as a device, and have no object: ${hiddenPartners.join(', ')}`);
948
+ }
949
+ addonNotSkipped.forEach(state => unmapped.push(state.name));
950
+ if (!unmapped.length) {
951
+ return;
952
+ }
953
+ this.adapter.log.info(`${unmapped.length} DSS state(s) could not be assigned to a device, circuit, room, group or the apartment ` +
954
+ `and therefore have no object: ${JSON.stringify(unmapped)}. ` +
955
+ 'Please report these names in a GitHub issue so they can be mapped.');
956
+ }
957
+ /**
958
+ * The device whose hidden 2-way partner owns a `dev.<dSUID>.` state, if that is what
959
+ * the state is. Only with positive evidence from the structure, never by the shape of
960
+ * the name alone: the dSUID itself must be missing from the structure, the one a dSID
961
+ * below must be a dS device (no vDC) and that device must be a 2-way master by its
962
+ * own buttonInputMode - exactly the pair the dSS hides.
963
+ *
964
+ * @param stateName name of the state in the dSS, `dev.<dSUID>.<state>` for a device
965
+ * @param devicesByDsuid all devices of the apartment structure
966
+ * @returns the master device of the pair
967
+ */
968
+ static twoWayMasterOf(stateName, devicesByDsuid) {
969
+ const match = /^dev\.([0-9a-f]{34})\./.exec(stateName);
970
+ if (!match || devicesByDsuid.has(match[1])) {
971
+ return undefined;
972
+ }
973
+ const previous = previousDsidDsuid(match[1]);
974
+ const master = previous && devicesByDsuid.get(previous);
975
+ if (!master || master.isVdcDevice) {
976
+ return undefined;
977
+ }
978
+ const mode = master.buttonInputMode;
979
+ if (TWO_WAY_MASTER_BUTTON_MODES.has(mode)) {
980
+ return master;
981
+ }
982
+ if (TWO_WAY_MASTER_BUTTON_MODES_EVEN_DSID.has(mode) && parseInt(master.dSUID.slice(24, 32), 16) % 2 === 0) {
983
+ return master;
984
+ }
985
+ return undefined;
986
+ }
987
+ findStates(checkRegEx) {
988
+ const regEx = new RegExp(checkRegEx);
989
+ const res = [];
990
+ if (!Array.isArray(this.propertyStates)) {
991
+ return res;
992
+ }
993
+ this.propertyStates.forEach(state => {
994
+ if (!state || typeof state.name !== 'string') {
995
+ return;
996
+ }
997
+ const match = state.name.match(regEx);
998
+ if (!match) {
999
+ return;
1000
+ }
1001
+ if (match && match[1]) {
1002
+ state.matchedName = match[1];
1003
+ }
1004
+ this.matchedPropertyStates.add(state.name);
1005
+ res.push(state);
1006
+ });
1007
+ return res;
1008
+ }
1009
+ /**
1010
+ * Liest die Zaehlerwerte ueber die neue API - EIN Request fuer alle Klemmen.
1011
+ *
1012
+ * Die alte API braucht dafuer zwei Requests je Klemme. Einheit und Zaehlerstand sind
1013
+ * nachweislich identisch (gegen einen dSS 1.19.13 verglichen: fuenf von sechs Klemmen
1014
+ * auf die Wattsekunde gleich, die sechste um genau den Zeitversatz daneben), die
1015
+ * Umrechnung bleibt deshalb dieselbe wie im klassischen Weg.
1016
+ */
1017
+ async updateMeterDataViaSmartHome() {
1018
+ const meteredCircuits = (this.apartmentCircuits || []).filter(circuit => circuit.hasMetering);
1019
+ if (!meteredCircuits.length || this.isAdapterStopping()) {
1020
+ return { attempted: false, succeeded: true, missingCircuits: [] };
1021
+ }
1022
+ if (!this.smartHome) {
1023
+ return { attempted: false, succeeded: false, missingCircuits: meteredCircuits };
1024
+ }
1025
+ if (this.smartHomeMeterRetryAfter > this.now()) {
1026
+ return { attempted: false, succeeded: false, missingCircuits: meteredCircuits };
1027
+ }
1028
+ let values;
1029
+ try {
1030
+ const answer = await this.smartHome.getMeteringValues();
1031
+ if (this.isAdapterStopping()) {
1032
+ return { attempted: false, succeeded: true, missingCircuits: [] };
1033
+ }
1034
+ values = answer && answer.values;
1035
+ if (!Array.isArray(values)) {
1036
+ throw new Error('the response contains no values array');
1037
+ }
1038
+ }
1039
+ catch (err) {
1040
+ if ((err && typeof err === 'object' && 'shutdown' in err && err.shutdown === true) ||
1041
+ this.isAdapterStopping()) {
1042
+ return { attempted: false, succeeded: true, missingCircuits: [] };
1043
+ }
1044
+ this.deferSmartHomeMeterRetry(err);
1045
+ return { attempted: true, succeeded: false, missingCircuits: meteredCircuits };
1046
+ }
1047
+ const byId = new Map();
1048
+ for (const entry of values) {
1049
+ if (entry && typeof entry.id === 'string') {
1050
+ byId.set(entry.id, finiteMeterValue(entry.attributes && entry.attributes.value));
1051
+ }
1052
+ }
1053
+ const missingCircuits = [];
1054
+ for (const circuit of meteredCircuits) {
1055
+ const power = byId.get(`dsm-${circuit.dSUID}-power`);
1056
+ const energy = byId.get(`dsm-${circuit.dSUID}-energy`);
1057
+ if (power === undefined || energy === undefined) {
1058
+ missingCircuits.push(circuit);
1059
+ continue;
1060
+ }
1061
+ // A poll, not an event: an unchanged reading is not written again (the counter
1062
+ // in info.apiActivity shows that the reads go on)
1063
+ this.setStateSafe(`devices.${circuit.dSUID}.PowerConsumption`, power, { skipUnchanged: true });
1064
+ // Gleiche Umrechnung wie im klassischen Weg: Wattsekunden -> Kilowattstunden.
1065
+ // Die API deklariert "Wh", das ist nachweislich falsch.
1066
+ this.setStateSafe(`devices.${circuit.dSUID}.EnergyMeterValue`, wattSecondsToKwh(energy), {
1067
+ skipUnchanged: true,
1068
+ });
1069
+ }
1070
+ if (meteredCircuits.length && missingCircuits.length === meteredCircuits.length) {
1071
+ // Die Antwort enthaelt keine einzige der bekannten Klemmen - dann stimmt die
1072
+ // Zuordnung nicht und der alte Weg ist der verlaesslichere
1073
+ this.deferSmartHomeMeterRetry(new Error('the response contains no value for any known circuit'));
1074
+ return { attempted: true, succeeded: false, missingCircuits: meteredCircuits };
1075
+ }
1076
+ this.resetSmartHomeMeterRetry();
1077
+ // Auch ein teilweiser Erfolg ist ein Erfolg der neuen API - die fehlenden Klemmen
1078
+ // meldet gleich darauf der klassische Weg
1079
+ this.reportMeteringApi(missingCircuits.length ? 'classic' : 'smarthome');
1080
+ if (missingCircuits.length) {
1081
+ this.adapter.log.debug(`${missingCircuits.length} of ${meteredCircuits.length} circuits are incomplete in the Smart Home API answer; reading only those circuits through the classic API`);
1082
+ }
1083
+ return { attempted: true, succeeded: true, missingCircuits };
1084
+ }
1085
+ /**
1086
+ * Delays the next optional Smart Home attempt exponentially. Authentication errors use
1087
+ * the maximum delay immediately; saving corrected settings restarts the adapter anyway.
1088
+ */
1089
+ deferSmartHomeMeterRetry(err) {
1090
+ this.smartHomeMeterFailures++;
1091
+ const status = err && typeof err === 'object' && 'status' in err ? err.status : undefined;
1092
+ const exponent = Math.min(this.smartHomeMeterFailures - 1, 10);
1093
+ // 404 means the firmware does not offer /api/v1 at all - retrying more often
1094
+ // than the maximum makes as little sense as it does for a rejected key
1095
+ const permanent = status === 401 || status === 403 || status === 404;
1096
+ const delay = permanent
1097
+ ? this.smartHomeMeterRetryMax
1098
+ : Math.min(this.smartHomeMeterRetryBase * 2 ** exponent, this.smartHomeMeterRetryMax);
1099
+ this.smartHomeMeterRetryAfter = this.now() + delay;
1100
+ const minutes = Math.max(1, Math.ceil(delay / 60000));
1101
+ const reason = status === 404
1102
+ ? 'the dSS does not offer the Smart Home API (HTTP 404), it needs a newer firmware'
1103
+ : (0, configUtils_1.errorMessage)(err);
1104
+ const message = `Meter values could not be read completely via the Smart Home API (${reason}); using the classic API and retrying the Smart Home API in ${minutes} minute${minutes === 1 ? '' : 's'}`;
1105
+ // A permanently failing API would otherwise warn once per hour, forever
1106
+ if (this.smartHomeMeterFailures === 1) {
1107
+ this.adapter.log.warn(message);
1108
+ }
1109
+ else {
1110
+ this.adapter.log.debug(message);
1111
+ }
1112
+ }
1113
+ resetSmartHomeMeterRetry() {
1114
+ this.smartHomeMeterFailures = 0;
1115
+ this.smartHomeMeterRetryAfter = 0;
1116
+ }
1117
+ /**
1118
+ * Records which API delivered the meter values.
1119
+ *
1120
+ * Without this the fallback is invisible: the adapter keeps running, just quietly on
1121
+ * the classic path. A single log line at startup does not answer "is the new API
1122
+ * actually working right now" - a state does, and it can be watched and charted.
1123
+ */
1124
+ reportMeteringApi(api) {
1125
+ if (this.lastMeteringApi === api) {
1126
+ return;
1127
+ }
1128
+ this.lastMeteringApi = api;
1129
+ this.adapter.setState && this.adapter.setState('info.meteringApi', api, true);
1130
+ this.adapter.log.info(`Meter values are now read via the ${api === 'smarthome' ? 'Smart Home' : 'classic'} API`);
1131
+ }
1132
+ isAdapterStopping() {
1133
+ return !!(this.adapter && typeof this.adapter.isStopping === 'function' && this.adapter.isStopping());
1134
+ }
1135
+ updateMeterData(callback) {
1136
+ // main.js plant den naechsten Poll-Zyklus ausschliesslich in diesem Callback -
1137
+ // er muss deshalb genau einmal laufen, auch wenn ein Handler unerwartet wirft
1138
+ let settled = false;
1139
+ const finish = (failed, total) => {
1140
+ if (settled) {
1141
+ return;
1142
+ }
1143
+ settled = true;
1144
+ callback && callback(failed, total);
1145
+ };
1146
+ if (this.isAdapterStopping()) {
1147
+ callback && setImmediate(() => finish(0, 0));
1148
+ return;
1149
+ }
1150
+ if (this.smartHome) {
1151
+ this.updateMeterDataViaSmartHome()
1152
+ .then(result => {
1153
+ if (this.isAdapterStopping()) {
1154
+ finish(0, 0);
1155
+ return;
1156
+ }
1157
+ if (result.succeeded && !result.missingCircuits.length) {
1158
+ // Bewusst (0, 0) statt (0, 1): main.js leitet aus diesem Callback
1159
+ // info.connection ab. Dieser Zyklus hat die klassische API gar nicht
1160
+ // angefasst, darf ueber ihren Zustand also nichts behaupten. Faellt
1161
+ // sie aus, meldet das der Event-Kanal ueber eventError - und faellt
1162
+ // der dSS ganz aus, scheitert auch die neue API und der klassische
1163
+ // Weg unten liefert das Urteil.
1164
+ finish(0, 0);
1165
+ return;
1166
+ }
1167
+ const smartFailed = result.attempted && !result.succeeded ? 1 : 0;
1168
+ const smartTotal = result.attempted ? 1 : 0;
1169
+ this.updateMeterDataViaClassicApi((failed, total) => finish(failed + smartFailed, total + smartTotal), result.missingCircuits);
1170
+ }, err => {
1171
+ if ((err && err.shutdown === true) || this.isAdapterStopping()) {
1172
+ finish(0, 0);
1173
+ return;
1174
+ }
1175
+ this.adapter.log.debug(`Smart Home meter read failed unexpectedly: ${(0, configUtils_1.errorMessage)(err)}`);
1176
+ this.deferSmartHomeMeterRetry(err);
1177
+ this.updateMeterDataViaClassicApi((failed, total) => finish(failed + 1, total + 1), (this.apartmentCircuits || []).filter(circuit => circuit.hasMetering));
1178
+ })
1179
+ .catch(err => {
1180
+ if (settled) {
1181
+ // Der Fehler kam aus dem Poll-Callback von main.js. Ihn nur zu
1182
+ // loggen koennte die Poll-Kette still beenden (der naechste Zyklus
1183
+ // wird IM Callback geplant) - frueher endete er als unhandled
1184
+ // rejection und js-controller startete den Adapter neu. Dieses
1185
+ // Sicherheitsnetz bleibt erhalten.
1186
+ this.adapter.log.error(`The meter poll callback threw (${(0, configUtils_1.errorMessage)(err)}); restarting the adapter so the polling cannot silently stop`);
1187
+ if (typeof this.adapter.restartAdapter === 'function') {
1188
+ this.adapter.restartAdapter(30000, 'the meter poll callback threw');
1189
+ }
1190
+ else {
1191
+ setImmediate(() => {
1192
+ throw err;
1193
+ });
1194
+ }
1195
+ return;
1196
+ }
1197
+ this.adapter.log.error(`Meter update failed unexpectedly: ${(0, configUtils_1.errorMessage)(err)}`);
1198
+ finish(1, 1);
1199
+ });
1200
+ return;
1201
+ }
1202
+ this.updateMeterDataViaClassicApi(finish);
1203
+ }
1204
+ updateMeterDataViaClassicApi(callback, circuits) {
1205
+ if (this.isAdapterStopping()) {
1206
+ callback && setImmediate(() => callback(0, 0));
1207
+ return;
1208
+ }
1209
+ const meteredCircuits = (circuits || this.apartmentCircuits || []).filter(circuit => circuit.hasMetering);
1210
+ if (meteredCircuits.length) {
1211
+ this.reportMeteringApi('classic');
1212
+ }
1213
+ const totalCounter = meteredCircuits.length * 2;
1214
+ let updateCounter = totalCounter;
1215
+ let errorCounter = 0;
1216
+ let callbackCalled = false;
1217
+ const finishOne = (failed) => {
1218
+ if (failed) {
1219
+ errorCounter++;
1220
+ }
1221
+ updateCounter--;
1222
+ if (updateCounter || callbackCalled) {
1223
+ return;
1224
+ }
1225
+ callbackCalled = true;
1226
+ callback && callback(errorCounter, totalCounter);
1227
+ };
1228
+ if (!updateCounter) {
1229
+ callback && setImmediate(() => callback(0, 0));
1230
+ return;
1231
+ }
1232
+ meteredCircuits.forEach(circuit => {
1233
+ let consumptionFinished = false;
1234
+ this.dssQueue.pushQueryQueue(circuit.dSUID, 'getConsumption', {
1235
+ dssClass: 'circuit',
1236
+ dssFunction: 'getConsumption',
1237
+ params: {
1238
+ dsuid: circuit.dSUID,
1239
+ },
1240
+ }, 'low', (err, res) => {
1241
+ if (consumptionFinished) {
1242
+ return;
1243
+ }
1244
+ consumptionFinished = true;
1245
+ const value = !err && res && res.ok && res.result ? finiteMeterValue(res.result.consumption) : undefined;
1246
+ if (value !== undefined) {
1247
+ this.setStateSafe(`devices.${circuit.dSUID}.PowerConsumption`, value, {
1248
+ skipUnchanged: true,
1249
+ });
1250
+ }
1251
+ finishOne(value === undefined);
1252
+ });
1253
+ let energyFinished = false;
1254
+ this.dssQueue.pushQueryQueue(circuit.dSUID, 'getEnergyMeterValue', {
1255
+ dssClass: 'circuit',
1256
+ dssFunction: 'getEnergyMeterValue',
1257
+ params: {
1258
+ dsuid: circuit.dSUID,
1259
+ },
1260
+ }, 'low', (err, res) => {
1261
+ if (energyFinished) {
1262
+ return;
1263
+ }
1264
+ energyFinished = true;
1265
+ const value = !err && res && res.ok && res.result ? finiteMeterValue(res.result.meterValue) : undefined;
1266
+ if (value !== undefined) {
1267
+ this.setStateSafe(`devices.${circuit.dSUID}.EnergyMeterValue`, wattSecondsToKwh(value), {
1268
+ skipUnchanged: true,
1269
+ });
1270
+ }
1271
+ finishOne(value === undefined);
1272
+ });
1273
+ });
1274
+ }
1275
+ createDevices(devices, callback) {
1276
+ this.addFolderObject('devices', 'Devices');
1277
+ this.apartmentCircuits.forEach(circuit => {
1278
+ this.addFolderObject(`devices.${circuit.dSUID}`, circuit.name || 'Circuit');
1279
+ if (!circuit.hasMetering) {
1280
+ return;
1281
+ }
1282
+ this.addStateObject(`devices.${circuit.dSUID}.PowerConsumption`, {
1283
+ name: 'Power Consumption',
1284
+ type: 'number',
1285
+ role: 'value.power',
1286
+ unit: 'W',
1287
+ read: true,
1288
+ write: false,
1289
+ });
1290
+ this.addStateObject(`devices.${circuit.dSUID}.EnergyMeterValue`, {
1291
+ name: 'Energy Meter',
1292
+ type: 'number',
1293
+ role: 'value.power.consumption',
1294
+ unit: 'kWh',
1295
+ read: true,
1296
+ write: false,
1297
+ });
1298
+ const circuitStates = this.findStates(`^dsm\\.${circuit.dSUID}\\.(.*)$`);
1299
+ if (circuitStates && circuitStates.length) {
1300
+ this.addFolderObject(`devices.${circuit.dSUID}.states`, 'DSM States', 'channel');
1301
+ circuitStates.forEach(state => {
1302
+ if (!state.matchedName) {
1303
+ return;
1304
+ }
1305
+ const stateId = `devices.${circuit.dSUID}.states.${state.matchedName}`;
1306
+ this.addStateObject(stateId, state.name, {
1307
+ name: state.matchedName,
1308
+ role: 'indicator',
1309
+ type: 'string',
1310
+ read: true,
1311
+ write: false,
1312
+ }, value => {
1313
+ value = DSSStructure.toBoolean(value);
1314
+ this.dssQueue.pushQueryQueue(circuit.dSUID, {
1315
+ dssClass: 'state',
1316
+ dssFunction: 'set',
1317
+ params: {
1318
+ name: state.name,
1319
+ value: value,
1320
+ },
1321
+ }, 'high', (err, res) => {
1322
+ if (err || (res && !res.ok)) {
1323
+ this.logQueueError(`Error while set State for ${circuit.dSUID}: ${err || JSON.stringify(res)}`, err);
1324
+ }
1325
+ });
1326
+ });
1327
+ this.initialObjectValues[stateId] = DSSStructure.initialStateValue(state);
1328
+ });
1329
+ }
1330
+ });
1331
+ let deviceCounter = 0;
1332
+ devices.forEach(dev => {
1333
+ deviceCounter++;
1334
+ setImmediate(() => this.createDevice(dev, () => {
1335
+ !--deviceCounter && callback && callback(null);
1336
+ }));
1337
+ });
1338
+ !deviceCounter && callback && setImmediate(() => callback(null));
1339
+ }
1340
+ createDevice(dev, callback) {
1341
+ if (!dev.isValid || !dev.isPresent) {
1342
+ this.adapter.log.debug(`IGNORE DEVICE ${dev.dSUID} because invalid`);
1343
+ callback && setImmediate(() => callback(null));
1344
+ return;
1345
+ }
1346
+ this.zoneDevices[dev.zoneID] = this.zoneDevices[dev.zoneID] || {};
1347
+ dev.groups &&
1348
+ dev.groups.forEach((group) => {
1349
+ this.zoneDevices[dev.zoneID][group] = this.zoneDevices[dev.zoneID][group] || [];
1350
+ this.zoneDevices[dev.zoneID][group].push(dev.dSUID);
1351
+ });
1352
+ this.devicesByDsuid[dev.dSUID] = dev;
1353
+ const devId = `devices.${dev.meterDSUID}.${dev.dSUID}`;
1354
+ const devName = dev.name ? `${dev.name}(${dev.hwInfo})` : dev.hwInfo;
1355
+ // An unknown output mode used to end up in the object name as the literal
1356
+ // "(undefined)" - six devices carried that on the installation this was found on.
1357
+ // The name is written without the suffix instead, and the unknown mode is logged
1358
+ // once so the next one is noticed instead of being cast into a name forever.
1359
+ const outputRole = dssConstants.outputModeToRoleMap[dev.outputMode];
1360
+ if (outputRole === undefined) {
1361
+ this.adapter.log.debug(`Unknown outputMode ${dev.outputMode} on ${dev.hwInfo || 'device'} ${dev.dSUID} - name written without the role suffix`);
1362
+ }
1363
+ this.addFolderObject(devId, outputRole ? `${devName} (${outputRole})` : devName, 'device');
1364
+ if (dev.sensorInputCount) {
1365
+ let realSensors = false;
1366
+ dev.sensors.forEach((sensor, idx) => {
1367
+ if (!dssConstants.sensorUnitRoleMap[sensor.type]) {
1368
+ return;
1369
+ }
1370
+ if (!realSensors) {
1371
+ this.addFolderObject(`${devId}.sensors`, 'Device Sensor Channels', 'channel');
1372
+ realSensors = true;
1373
+ }
1374
+ const sensorId = `${devId}.sensors.${idx}`;
1375
+ this.addStateObject(sensorId, `${dev.dSUID}.sensors.${idx}`, dssConstants.sensorUnitRoleMap[sensor.type]);
1376
+ if (sensor.valid) {
1377
+ this.initialObjectValues[sensorId] = sensor.value;
1378
+ }
1379
+ else if (INITIAL_READ_SENSOR_TYPES.has(sensor.type)) {
1380
+ // The dSS marks the sensor invalid: its value only ever arrives with
1381
+ // a deviceSensorValue event, and a device with constant consumption
1382
+ // (a printer in standby) may not send one for months. One low
1383
+ // priority bus read fills the state. Only the metering types whose
1384
+ // native 12 bit value IS the event float (1 W / 1 mA / 1 VA steps) -
1385
+ // energy meter and high range current natives have unverified
1386
+ // resolutions and stay with the events.
1387
+ this.dssQueue.queueReadSensorValue(dev, idx, 'low', (err, value) => {
1388
+ if (err || this.isAdapterStopping()) {
1389
+ err && this.adapter.log.debug(`No initial sensor read ${idx} of ${dev.dSUID}: ${err}`);
1390
+ return;
1391
+ }
1392
+ if (typeof value === 'number' && isFinite(value)) {
1393
+ this.setStateSafe(sensorId, value);
1394
+ this.initialObjectValues[sensorId] = value;
1395
+ }
1396
+ });
1397
+ }
1398
+ });
1399
+ }
1400
+ if (dev.binaryInputCount) {
1401
+ this.addFolderObject(`${devId}.binaryInputs`, 'Device Binary Inputs', 'channel');
1402
+ dev.binaryInputs.forEach((input, idx) => {
1403
+ if (!dssConstants.binaryInputTypeNames[input.inputType] &&
1404
+ input.inputType === 0 &&
1405
+ !this.groupTypes[input.targetGroup]) {
1406
+ this.adapter.log.warn(` INVALID BINARYINPUT TYPE ${input.inputType} / ${input.targetGroup}`);
1407
+ }
1408
+ const inputId = `${devId}.binaryInputs.${idx}`;
1409
+ this.addStateObject(inputId, `${dev.dSUID}.binaryInputs.${idx}`, {
1410
+ name: dssConstants.binaryInputTypeNames[input.inputType] ||
1411
+ this.groupTypes[input.targetGroup] ||
1412
+ 'Unknown',
1413
+ type: 'number',
1414
+ role: 'value',
1415
+ states: dssConstants.windowHandleInputTypes.includes(input.inputType)
1416
+ ? dssConstants.windowHandleStateNames
1417
+ : dssConstants.binaryInputStateNames,
1418
+ read: true,
1419
+ write: false,
1420
+ });
1421
+ this.initialObjectValues[inputId] = input.state;
1422
+ });
1423
+ }
1424
+ const devStates = this.findStates(`^dev\\.${dev.dSUID}\\.(.*)$`);
1425
+ if (devStates && devStates.length) {
1426
+ this.addFolderObject(`${devId}.states`, 'Device States', 'channel');
1427
+ devStates.forEach(state => {
1428
+ if (!state.matchedName) {
1429
+ return;
1430
+ }
1431
+ const stateId = `${devId}.states.${state.matchedName}`;
1432
+ this.addStateObject(stateId, state.name, {
1433
+ name: state.matchedName,
1434
+ role: 'indicator',
1435
+ type: 'string',
1436
+ read: true,
1437
+ write: false,
1438
+ }, value => {
1439
+ this.dssQueue.pushQueryQueue(dev.dSUID, {
1440
+ dssClass: 'state',
1441
+ dssFunction: 'set',
1442
+ params: {
1443
+ name: state.name,
1444
+ value: value,
1445
+ },
1446
+ }, 'high', (err, res) => {
1447
+ if (err || (res && !res.ok)) {
1448
+ this.logQueueError(`Error while set State for ${dev.dSUID}: ${err || JSON.stringify(res)}`, err);
1449
+ }
1450
+ });
1451
+ });
1452
+ this.initialObjectValues[stateId] = DSSStructure.initialStateValue(state);
1453
+ });
1454
+ }
1455
+ dev.outputChannelList = {};
1456
+ if (dev.outputMode && dev.outputChannels && dev.outputChannels.length) {
1457
+ dev.outputChannels.forEach((output) => {
1458
+ if (!dssConstants.outputChannelUnitRoleMap[output.channelType]) {
1459
+ // Channels without a channelType (e.g. the media channels of dS audio
1460
+ // devices) are simply not supported - that is not an error worth a warning.
1461
+ if (!output.channelType) {
1462
+ this.adapter.log.debug(`Unsupported output channel without type for ${dev.dSUID}: ${JSON.stringify(output)}`);
1463
+ }
1464
+ else {
1465
+ this.adapter.log.info(`Unsupported output channel type "${output.channelType}" for ${dev.dSUID}: ${JSON.stringify(output)}`);
1466
+ }
1467
+ return;
1468
+ }
1469
+ const outputChannelId = `${devId}.${output.channelId}`;
1470
+ this.addStateObject(outputChannelId, `${dev.dSUID}.${output.channelId}`, dssConstants.outputChannelUnitRoleMap[output.channelType]);
1471
+ dev.outputChannelList[output.channelType] = outputChannelId;
1472
+ // TODO find generic way to get Output value - currently implemented per device type later (light/shade)
1473
+ // TODO add way to SET values!!
1474
+ /* values:/device/getOutputChannelValue2?dsuid=5a11caa06212578280d826428d15c3d700 ((OPTIONAL &channels=brightness;saturation;hue))
1475
+
1476
+ const channelList = dev.outputChannels.map(output => output.channelId).join(';');
1477
+ dss.requestAsync('device', 'getOutputChannelValue' , {dsid: dev.id, channels: channelList}).then((outputChannelValues) => {
1478
+ this.adapter.log.debug('getOutputChannelValue for ' + dev.dSUID + ' AND ' + channelList + ': ' + JSON.stringify(outputChannelValues));
1479
+ outputChannelValues = this.convertObject(outputChannelValues.result.channels, 'index');
1480
+
1481
+ queueUpdateOutputValue(dev, dssConstants.outputChannelUnitRoleMap[output.channelType].channelIndex, 'medium', (err, value) => {
1482
+
1483
+ });
1484
+
1485
+ set /device/setOutputChannelValue2?dsuid=5a11caa06212578280d826428d15c3d700&channels={”brightness”: {”value”: 10, ”automatic”: false}, ”saturation”: {”value”: 100}, ”hue”: {”value”: 235}}
1486
+ */
1487
+ });
1488
+ }
1489
+ if (dev.outputMode) {
1490
+ // DEVICE. state (button) true= 5, false = 0
1491
+ // sendSceneCommand
1492
+ // setDeviceScene: '/device/callScene?dsid=%s&sceneNumber=%s&category=manual',
1493
+ // setDeviceValue: '/device/setConfig?&dsuid=%1&class=%2&index=%3&value=%4&category=manual'
1494
+ this.addFolderObject(`${devId}.scenes`, 'Device Scenes', 'channel');
1495
+ const sceneList = {};
1496
+ Object.keys(dssConstants.zoneSceneCommands).forEach(scene => {
1497
+ const sceneId = `${devId}.scenes.${this.convertSceneName(dssConstants.zoneSceneCommands[Number(scene)])}`;
1498
+ sceneList[scene] = dssConstants.zoneSceneCommands[Number(scene)];
1499
+ this.addStateObject(sceneId, `${dev.dSUID}.scenes.${scene}`, {
1500
+ name: dssConstants.zoneSceneCommands[Number(scene)],
1501
+ type: 'boolean',
1502
+ role: 'switch',
1503
+ }, value => {
1504
+ value = DSSStructure.toBoolean(value);
1505
+ this.dssQueue.pushQueryQueue(dev.meterDSUID, {
1506
+ dssClass: 'device',
1507
+ dssFunction: value ? 'callScene' : 'undoScene',
1508
+ params: {
1509
+ dsuid: dev.dSUID,
1510
+ sceneNumber: scene,
1511
+ category: 'manual',
1512
+ },
1513
+ }, 'high', (err, res) => {
1514
+ if (err || (res && !res.ok)) {
1515
+ this.logQueueError(`Error while ${value ? 'callScene' : 'undoScene'} for ${dev.dSUID}: ${err || JSON.stringify(res)}`, err);
1516
+ }
1517
+ });
1518
+ });
1519
+ this.initialObjectValues[sceneId] = false;
1520
+ });
1521
+ for (let sceneId = 67; sceneId <= 70; sceneId++) {
1522
+ const sceneStateId = `${devId}.scenes.${this.convertSceneName(dssConstants.apartmentScenes[sceneId])}`;
1523
+ sceneList[sceneId] = dssConstants.apartmentScenes[sceneId];
1524
+ this.addStateObject(sceneStateId, `${dev.dSUID}.scenes.${sceneId}`, {
1525
+ name: dssConstants.apartmentScenes[sceneId],
1526
+ type: 'boolean',
1527
+ role: 'switch',
1528
+ }, value => {
1529
+ value = DSSStructure.toBoolean(value);
1530
+ this.dssQueue.pushQueryQueue('zone', {
1531
+ dssClass: 'device',
1532
+ dssFunction: value ? 'callScene' : 'undoScene',
1533
+ params: {
1534
+ dsuid: dev.dSUID,
1535
+ sceneNumber: sceneId,
1536
+ category: 'manual',
1537
+ },
1538
+ }, 'high', (err, res) => {
1539
+ if (err || (res && !res.ok)) {
1540
+ this.logQueueError(`Error while ${value ? 'callScene' : 'undoScene'} for ${dev.dSUID}: ${err || JSON.stringify(res)}`, err);
1541
+ }
1542
+ });
1543
+ });
1544
+ this.initialObjectValues[sceneStateId] = false;
1545
+ }
1546
+ if (Object.keys(sceneList).length) {
1547
+ this.addStateObject(`${devId}.scenes.sceneId`, {
1548
+ name: 'Device Scene ID',
1549
+ type: 'number',
1550
+ role: 'state',
1551
+ states: sceneList,
1552
+ }, value => {
1553
+ if (!sceneList[value]) {
1554
+ this.adapter.log.warn(`Invalid Scene ID ${value} for ${dev.dSUID}.scenes.sceneId`);
1555
+ return;
1556
+ }
1557
+ this.dssQueue.pushQueryQueue(dev.meterDSUID, {
1558
+ dssClass: 'device',
1559
+ dssFunction: 'callScene',
1560
+ params: {
1561
+ dsuid: dev.dSUID,
1562
+ sceneNumber: value,
1563
+ category: 'manual',
1564
+ },
1565
+ }, 'high', (err, res) => {
1566
+ if (err || (res && !res.ok)) {
1567
+ this.logQueueError(`Error while callScene for ${dev.dSUID}: ${err || JSON.stringify(res)}`, err);
1568
+ }
1569
+ });
1570
+ });
1571
+ }
1572
+ }
1573
+ if (dev.buttonActiveGroup > 0 && dev.buttonActiveGroup <= 8) {
1574
+ this.addStateObject(`${devId}.button`, `${dev.dSUID}.0.button`, {
1575
+ name: `${dev.name} Button State`,
1576
+ type: 'boolean',
1577
+ role: 'indicator',
1578
+ read: true,
1579
+ write: false,
1580
+ });
1581
+ this.initialObjectValues[`${devId}.button`] = false;
1582
+ }
1583
+ if (dev.hwInfo.startsWith('SW-') || dev.hwInfo.startsWith('IC SW-')) {
1584
+ // Joker / Tasten
1585
+ this.createJokerDevice(dev, devId, callback);
1586
+ }
1587
+ else if ((dev.hwInfo.startsWith('GE-') || dev.hwInfo.startsWith('IC GE-')) && !dev.hwInfo.includes('-UMV')) {
1588
+ // Yellow: Light
1589
+ this.createLightDevice(dev, devId, callback);
1590
+ }
1591
+ else if (dev.hwInfo.startsWith('GR-') || dev.hwInfo.startsWith('IC GR-')) {
1592
+ // Gray: Shades
1593
+ this.createShaderDevice(dev, devId, callback);
1594
+ }
1595
+ else {
1596
+ if (dev.outputMode && dev.outputChannels && dev.outputChannels.length) {
1597
+ if (dev.outputChannels.length === 1) {
1598
+ const output = dev.outputChannels[0];
1599
+ const outputStateId = `${devId}.${output.channelId}`;
1600
+ if (dssConstants.outputChannelUnitRoleMap[output.channelType] &&
1601
+ dssConstants.outputChannelUnitRoleMap[output.channelType].native) {
1602
+ const roleDef = dssConstants.outputChannelUnitRoleMap[output.channelType];
1603
+ const channelIndex = roleDef.native.channelIndex !== undefined
1604
+ ? roleDef.native.channelIndex
1605
+ : output.channelIndex;
1606
+ const nativeMax = roleDef.native.nativeMax;
1607
+ if (output &&
1608
+ this.adapter.config.initializeOutputValues &&
1609
+ !this.queueGenericInitialRead(dev, output.channelType)) {
1610
+ this.dssQueue.queueUpdateOutputValue(dev, channelIndex, nativeMax, // a channel without native scale reads a single byte, see the queue
1611
+ 'medium', (err, value) => {
1612
+ if (err) {
1613
+ this.logOutputReadError(dev, output.channelType, err);
1614
+ return;
1615
+ }
1616
+ if (roleDef.native.nativeMax && roleDef.max) {
1617
+ value = Math.round((value * roleDef.max) / roleDef.native.nativeMax);
1618
+ }
1619
+ this.setStateSafe(outputStateId, value);
1620
+ // Auch dieser dritte klassische Lesepfad zaehlt fuer
1621
+ // info.outputApi - sonst bliebe der State bei Anlagen
1622
+ // leer, deren Ausgaenge nur solche Geraete sind
1623
+ this.reportOutputApi('classic');
1624
+ });
1625
+ }
1626
+ this.dssObjects[outputStateId].onChange = value => {
1627
+ // Some output channels are declared as boolean (e.g. airLouverAuto /
1628
+ // airFlowAuto - the ventilation swing and auto intensity switches).
1629
+ // The DSS represents them as a 0/1 output channel value.
1630
+ if (roleDef.type === 'boolean') {
1631
+ if (typeof value !== 'boolean' &&
1632
+ typeof value !== 'number' &&
1633
+ typeof value !== 'string') {
1634
+ this.adapter.log.warn(`Only booleans are allowed to set for ${outputStateId}, got ${typeof value}`);
1635
+ return;
1636
+ }
1637
+ const boolValue = DSSStructure.toBoolean(value);
1638
+ this.dssQueue.queueSetOutputValue(dev, channelIndex, 1, boolValue ? 1 : 0, 'high', err => {
1639
+ if (err) {
1640
+ this.logOutputWriteError(dev, err);
1641
+ }
1642
+ else {
1643
+ this.setStateSafe(outputStateId, boolValue);
1644
+ }
1645
+ });
1646
+ return;
1647
+ }
1648
+ if (typeof value !== 'number') {
1649
+ this.adapter.log.warn(`Only numbers are allowed to set for ${outputStateId}`);
1650
+ return;
1651
+ }
1652
+ if (nativeMax) {
1653
+ // For Min or Max use the scenes - but not if device is an GE/BL-UMV
1654
+ if (!dev.hwInfo.includes('-UMV') &&
1655
+ roleDef.max !== undefined &&
1656
+ (value === roleDef.min || value === roleDef.max)) {
1657
+ value = value > roleDef.min;
1658
+ this.dssQueue.pushQueryQueue(dev.meterDSUID, {
1659
+ dssClass: 'device',
1660
+ dssFunction: 'callScene',
1661
+ params: {
1662
+ dsuid: dev.dSUID,
1663
+ sceneNumber: value ? 14 : 13,
1664
+ category: 'manual',
1665
+ },
1666
+ }, 'high', (err, res) => {
1667
+ if (err || (res && !res.ok)) {
1668
+ this.logQueueError(`Error while ${value ? 'callScene' : 'undoScene'} for ${dev.dSUID}: ${err || JSON.stringify(res)}`, err);
1669
+ }
1670
+ else {
1671
+ this.setStateSafe(outputStateId, value ? roleDef.max : roleDef.min);
1672
+ }
1673
+ });
1674
+ }
1675
+ else {
1676
+ const normalizedValue = Math.round((value * nativeMax) / roleDef.max);
1677
+ this.dssQueue.queueSetOutputValue(dev, channelIndex, nativeMax, normalizedValue, 'high', err => {
1678
+ if (err) {
1679
+ this.logOutputWriteError(dev, err);
1680
+ }
1681
+ else {
1682
+ this.setStateSafe(outputStateId, value);
1683
+ }
1684
+ });
1685
+ }
1686
+ }
1687
+ else {
1688
+ // send value directly
1689
+ this.dssQueue.queueSetOutputValue(dev, channelIndex, 1, value, 'high', err => {
1690
+ if (err) {
1691
+ this.logOutputWriteError(dev, err);
1692
+ }
1693
+ else {
1694
+ this.setStateSafe(outputStateId, value);
1695
+ }
1696
+ });
1697
+ }
1698
+ };
1699
+ }
1700
+ else {
1701
+ this.adapter.log.warn(`Invalid output channel definition for device ${dev.dSUID}: ${JSON.stringify(output)}`);
1702
+ }
1703
+ }
1704
+ else {
1705
+ // More than one channel: WRITING needs a per-channel handler, which
1706
+ // only the typed devices have. READING works for all of them - the
1707
+ // bundled status request and the named channel read each carry every
1708
+ // channel of the device in one answer.
1709
+ const knownChannel = Object.keys(dev.outputChannelList)[0];
1710
+ const served = this.adapter.config.initializeOutputValues &&
1711
+ knownChannel !== undefined &&
1712
+ this.queueGenericInitialRead(dev, knownChannel);
1713
+ if (!served) {
1714
+ // A static property of the device, not an error - one line per device would
1715
+ // flood the log on every start.
1716
+ this.adapter.log.debug(`${dev.outputChannels.length} Output values for device ${dev.dSUID} are unsupported: ${dev.outputChannels
1717
+ .map((output) => output.channelId)
1718
+ .join(', ')}`);
1719
+ }
1720
+ }
1721
+ // A scene changes these outputs as well - re-read them, see
1722
+ // registerSceneOutputRefresh. Without the sync a vDC device still gets
1723
+ // its own named read, but only for a DEVICE scene: that reaches exactly
1724
+ // this dSUID and costs one request, while a zone or apartment scene is
1725
+ // fanned out to every device of the room.
1726
+ this.registerSceneOutputRefresh(dev);
1727
+ if (!this.smartHomeSync &&
1728
+ this.adapter.config.initializeOutputValues &&
1729
+ dev.isVdcDevice === true &&
1730
+ Object.keys(dev.outputChannelList).length &&
1731
+ this.dss &&
1732
+ typeof this.dss.on === 'function') {
1733
+ this.dss.on(dev.dSUID, data => {
1734
+ if ((data.name === 'callScene' || data.name === 'undoScene') &&
1735
+ data.source &&
1736
+ data.source.isDevice) {
1737
+ this.queueVdcChannelRead(dev, Object.keys(dev.outputChannelList)[0], 'low', true);
1738
+ }
1739
+ });
1740
+ }
1741
+ if (dev.buttonActiveGroup === 8) {
1742
+ this.createJokerDevice(dev, devId, callback);
1743
+ }
1744
+ else {
1745
+ callback && setImmediate(() => callback());
1746
+ }
1747
+ }
1748
+ else {
1749
+ if (dev.buttonActiveGroup === 8) {
1750
+ this.createJokerDevice(dev, devId, callback);
1751
+ }
1752
+ else {
1753
+ callback && setImmediate(() => callback());
1754
+ }
1755
+ }
1756
+ }
1757
+ }
1758
+ createJokerDevice(dev, devId, callback) {
1759
+ // The state of button 0 belongs to buttonClickType/buttonHoldCount below: the event
1760
+ // handler in main.js aborts the whole buttonClick when it is missing, so creating only
1761
+ // two of the three states silently swallowed every press of the first button on
1762
+ // devices whose buttonActiveGroup is outside 1..8 (unassigned, broadcast, or > 8).
1763
+ if (!this.dssObjects[`${devId}.button`]) {
1764
+ this.addStateObject(`${devId}.button`, `${dev.dSUID}.0.button`, {
1765
+ name: `${dev.name} Button State`,
1766
+ type: 'boolean',
1767
+ role: 'indicator',
1768
+ read: true,
1769
+ write: false,
1770
+ });
1771
+ this.initialObjectValues[`${devId}.button`] = false;
1772
+ }
1773
+ this.addStateObject(`${devId}.buttonClickType`, `${dev.dSUID}.0.buttonClickType`, {
1774
+ name: `${dev.name} Button Click Type`,
1775
+ type: 'number',
1776
+ role: 'indicator',
1777
+ states: {
1778
+ 0: 'Single Tip',
1779
+ 1: 'Double Tip',
1780
+ 2: 'Triple Tip',
1781
+ 3: 'Quadruple Tip',
1782
+ 4: 'Hold Start',
1783
+ 5: 'Hold Repeat',
1784
+ 6: 'Hold End',
1785
+ 7: 'Single Click',
1786
+ 8: 'Double Click',
1787
+ 9: 'Triple Click',
1788
+ 10: 'Single Tip (Off)',
1789
+ 11: 'Single Tip (On/Down)',
1790
+ 12: 'Single Tip (On/Up)',
1791
+ 14: 'Single Tip (Stop)',
1792
+ },
1793
+ });
1794
+ this.initialObjectValues[`${devId}.buttonClickType`] = null;
1795
+ this.addStateObject(`${devId}.buttonHoldCount`, `${dev.dSUID}.0.buttonHoldCount`, {
1796
+ name: `${dev.name} Button Hold Count`,
1797
+ type: 'number',
1798
+ role: 'indicator',
1799
+ unit: 'ms',
1800
+ read: true,
1801
+ write: false,
1802
+ });
1803
+ this.initialObjectValues[`${devId}.buttonHoldCount`] = 0;
1804
+ if (dev.buttonInputCount > 1) {
1805
+ for (let cnt = 1; cnt < dev.buttonInputCount; cnt++) {
1806
+ this.addStateObject(`${devId}.button-${cnt}`, `${dev.dSUID}.${cnt}.button`, {
1807
+ name: `${dev.name} Button State`,
1808
+ type: 'boolean',
1809
+ role: 'indicator',
1810
+ read: true,
1811
+ write: false,
1812
+ });
1813
+ this.initialObjectValues[`${devId}.button-${cnt}`] = false;
1814
+ this.addStateObject(`${devId}.buttonClickType-${cnt}`, `${dev.dSUID}.${cnt}.buttonClickType`, {
1815
+ name: `${dev.name} Button Click Type`,
1816
+ type: 'number',
1817
+ role: 'indicator',
1818
+ states: {
1819
+ 0: 'Single Tip',
1820
+ 1: 'Double Tip',
1821
+ 2: 'Triple Tip',
1822
+ 3: 'Quadruple Tip',
1823
+ 4: 'Hold Start',
1824
+ 5: 'Hold Repeat',
1825
+ 6: 'Hold End',
1826
+ 7: 'Single Click',
1827
+ 8: 'Double Click',
1828
+ 9: 'Triple Click',
1829
+ 10: 'Single Tip (Off)',
1830
+ 11: 'Single Tip (On/Down)',
1831
+ 12: 'Single Tip (On/Up)',
1832
+ 14: 'Single Tip (Stop)',
1833
+ },
1834
+ });
1835
+ this.initialObjectValues[`${devId}.buttonClickType-${cnt}`] = null;
1836
+ this.addStateObject(`${devId}.buttonHoldCount-${cnt}`, `${dev.dSUID}.${cnt}.buttonHoldCount`, {
1837
+ name: `${dev.name} Button Hold Count`,
1838
+ type: 'number',
1839
+ role: 'indicator',
1840
+ unit: 'ms',
1841
+ read: true,
1842
+ write: false,
1843
+ });
1844
+ this.initialObjectValues[`${devId}.buttonHoldCount-${cnt}`] = 0;
1845
+ }
1846
+ }
1847
+ // A joker with an output - a switched socket, for instance - had no read for it
1848
+ // at all: its value only ever arrived with the next reconciliation, up to five
1849
+ // minutes after it was switched. The bundled status request is its only working
1850
+ // read (the channel has no offset the dSS answers, and the named read is for vDC
1851
+ // hardware), so it is asked at startup and right after a scene. A whole room
1852
+ // coalesces into ONE status read, and without the sync nothing happens at all -
1853
+ // exactly the behaviour of before.
1854
+ if (this.adapter.config.initializeOutputValues &&
1855
+ this.smartHomeSync &&
1856
+ dev.outputChannelList &&
1857
+ Object.keys(dev.outputChannelList).length) {
1858
+ this.smartHomeSync.requestDeviceSync(dev);
1859
+ }
1860
+ this.registerSceneOutputRefresh(dev);
1861
+ callback && setImmediate(() => callback());
1862
+ }
1863
+ createLightDevice(dev, devId, callback) {
1864
+ // options is passed straight through to setStateSafe. The read paths hand in
1865
+ // skipUnchanged, the write callbacks below deliberately do not: a command has to
1866
+ // reach its acknowledgement even when it sets the value that is already there.
1867
+ const setLightValue = (outputType, value, options) => {
1868
+ if (outputType !== 'brightness') {
1869
+ this.adapter.log.warn(`Not supported ${outputType} for ${dev.dSUID}`);
1870
+ return;
1871
+ }
1872
+ const percentValue = Math.round((value * 100) / 255);
1873
+ if (dev.outputMode === 16 && dev.outputSwitchThreshold !== undefined) {
1874
+ this.setStateSafe(`${devId}.state`, value >= dev.outputSwitchThreshold, options);
1875
+ this.initialObjectValues[`${devId}.state`] = value >= dev.outputSwitchThreshold;
1876
+ }
1877
+ else {
1878
+ this.setStateSafe(`${devId}.state`, !!percentValue, options);
1879
+ this.initialObjectValues[`${devId}.state`] = !!percentValue;
1880
+ }
1881
+ if (this.stateMap[`${dev.dSUID}.brightness`]) {
1882
+ this.setStateSafe(this.stateMap[`${dev.dSUID}.brightness`], percentValue, options);
1883
+ this.initialObjectValues[this.stateMap[`${dev.dSUID}.brightness`]] = percentValue;
1884
+ }
1885
+ };
1886
+ // The Smart Home sync and queueClassicOutputRead() deliver through the same
1887
+ // helper, so the boolean .state stays consistent no matter which API answered
1888
+ dev.applyNativeLightValue = (value, options) => setLightValue('brightness', value, options);
1889
+ if (dev.outputMode === 16 && dev.outputSwitchThreshold === undefined) {
1890
+ this.dssQueue.pushQueryQueue(dev.meterDSUID, {
1891
+ dssClass: 'device',
1892
+ dssFunction: 'getSwitchThreshold',
1893
+ params: {
1894
+ dsuid: dev.dSUID,
1895
+ category: 'manual',
1896
+ },
1897
+ }, 'high', (err, res) => {
1898
+ if (err || !res || !res.ok || !res.result || typeof res.result.threshold !== 'number') {
1899
+ this.logQueueError(`Can not get SwitchThreshold for ${dev.dSUID}, assume 50%`, err);
1900
+ dev.outputSwitchThreshold = 128;
1901
+ }
1902
+ else {
1903
+ dev.outputSwitchThreshold = res.result.threshold;
1904
+ }
1905
+ this.createLightDevice(dev, devId, callback);
1906
+ });
1907
+ return;
1908
+ }
1909
+ this.addStateObject(`${devId}.state`, {
1910
+ name: `${dev.name} State`,
1911
+ type: 'boolean',
1912
+ role: 'switch.light',
1913
+ }, value => {
1914
+ value = DSSStructure.toBoolean(value);
1915
+ this.dssQueue.pushQueryQueue(dev.meterDSUID, {
1916
+ dssClass: 'device',
1917
+ dssFunction: 'callScene',
1918
+ params: {
1919
+ dsuid: dev.dSUID,
1920
+ sceneNumber: value ? 14 : 13,
1921
+ category: 'manual',
1922
+ },
1923
+ }, 'high', (err, res) => {
1924
+ if (err || (res && !res.ok)) {
1925
+ this.logQueueError(`Error while ${value ? 'callScene' : 'undoScene'} for ${dev.dSUID}: ${err || JSON.stringify(res)}`, err);
1926
+ }
1927
+ else {
1928
+ setLightValue('brightness', value ? 255 : 0);
1929
+ }
1930
+ });
1931
+ });
1932
+ if (this.dssObjects[`${devId}.brightness`]) {
1933
+ this.dssObjects[`${devId}.brightness`].onChange = value => {
1934
+ if (value === 0 || value === 100) {
1935
+ value = DSSStructure.toBoolean(value);
1936
+ this.dssQueue.pushQueryQueue(dev.meterDSUID, {
1937
+ dssClass: 'device',
1938
+ dssFunction: 'callScene',
1939
+ params: {
1940
+ dsuid: dev.dSUID,
1941
+ sceneNumber: value ? 14 : 13,
1942
+ category: 'manual',
1943
+ },
1944
+ }, 'high', (err, res) => {
1945
+ if (err || (res && !res.ok)) {
1946
+ this.logQueueError(`Error while ${value ? 'callScene' : 'undoScene'} for ${dev.dSUID}: ${err || JSON.stringify(res)}`, err);
1947
+ }
1948
+ else {
1949
+ setLightValue('brightness', value ? 255 : 0);
1950
+ }
1951
+ });
1952
+ }
1953
+ else {
1954
+ value = Math.round((value * dssConstants.outputChannelUnitRoleMap.brightness.native.nativeMax) / 100);
1955
+ this.dssQueue.queueSetOutputValue(dev, dssConstants.outputChannelUnitRoleMap.brightness.native.channelIndex, dssConstants.outputChannelUnitRoleMap.brightness.native.nativeMax, value, 'high', (err, value) => {
1956
+ if (err) {
1957
+ this.logOutputWriteError(dev, err);
1958
+ }
1959
+ else {
1960
+ setLightValue('brightness', value);
1961
+ }
1962
+ });
1963
+ }
1964
+ };
1965
+ }
1966
+ if (dev.outputChannelList && this.adapter.config.initializeOutputValues) {
1967
+ // One status request of the new API covers every channel of every device.
1968
+ // Only without it (or when it fails) the classic per-channel reads run.
1969
+ if (!(this.smartHomeSync && this.smartHomeSync.requestDeviceSync(dev))) {
1970
+ Object.keys(dev.outputChannelList).forEach(outputType => this.queueClassicOutputRead(dev, outputType, 'medium'));
1971
+ }
1972
+ }
1973
+ this.dss.on(dev.dSUID, data => {
1974
+ this.adapter.log.debug(`DEVICE event ${JSON.stringify(data)}`);
1975
+ if (data.name !== 'callScene' && data.name !== 'undoScene') {
1976
+ return;
1977
+ }
1978
+ let brightness;
1979
+ if (this.adapter.config.usePresetValues) {
1980
+ brightness = dssConstants.lightSceneValueMap[data.properties.sceneID];
1981
+ if (brightness !== null && brightness !== undefined) {
1982
+ setLightValue('brightness', brightness);
1983
+ }
1984
+ }
1985
+ // Same semantics as for shades: initializeOutputValues controls the reads
1986
+ if (!this.adapter.config.initializeOutputValues) {
1987
+ return;
1988
+ }
1989
+ if (this.smartHomeSync && this.smartHomeSync.requestDeviceSync(dev, ['brightness'])) {
1990
+ return;
1991
+ }
1992
+ const prio = (brightness !== null && brightness !== undefined) || data.source.isGroup ? 'low' : 'medium';
1993
+ // Every channel, not just brightness: a scene may carry colour values as
1994
+ // well. For native lights the extra channels are no-ops (no offset read),
1995
+ // for vDC lights they coalesce into the ONE named channel read anyway.
1996
+ for (const outputType of Object.keys(dev.outputChannelList || { brightness: true })) {
1997
+ this.queueClassicOutputRead(dev, outputType, prio);
1998
+ }
1999
+ });
2000
+ callback && setImmediate(() => callback());
2001
+ }
2002
+ createShaderDevice(dev, devId, callback) {
2003
+ // Both stay null on a blind that declares no such channel - a blind without tilt
2004
+ // has no angle at all, and the handlers below check for exactly that.
2005
+ let positionName = null;
2006
+ let angleName = null;
2007
+ // The write handlers are registered independently of initializeOutputValues.
2008
+ // That option only controls whether output values are READ from the DSS - a blind
2009
+ // must stay controllable (position and angle) even when reading is switched off.
2010
+ if (dev.outputChannelList) {
2011
+ Object.keys(dev.outputChannelList).forEach(outputType => {
2012
+ let relevant = false;
2013
+ if (!positionName && outputType.includes('Position')) {
2014
+ positionName = outputType;
2015
+ relevant = true;
2016
+ }
2017
+ else if (!angleName && outputType.includes('Angle')) {
2018
+ angleName = outputType;
2019
+ relevant = true;
2020
+ }
2021
+ if (!relevant) {
2022
+ return;
2023
+ }
2024
+ this.dssObjects[dev.outputChannelList[outputType]].onChange = value => {
2025
+ const originalValue = value;
2026
+ if (outputType === positionName && (value === 0 || value === 100)) {
2027
+ value = DSSStructure.toBoolean(value);
2028
+ this.dssQueue.pushQueryQueue(dev.meterDSUID, {
2029
+ dssClass: 'device',
2030
+ dssFunction: 'callScene',
2031
+ params: {
2032
+ dsuid: dev.dSUID,
2033
+ sceneNumber: value ? 14 : 13,
2034
+ category: 'manual',
2035
+ },
2036
+ }, 'high', (err, res) => {
2037
+ if (err || (res && !res.ok)) {
2038
+ this.logQueueError(`Error while ${value ? 'callScene' : 'undoScene'} for ${dev.dSUID}: ${err || JSON.stringify(res)}`, err);
2039
+ }
2040
+ else {
2041
+ this.setStateSafe(dev.outputChannelList[outputType], originalValue);
2042
+ }
2043
+ });
2044
+ }
2045
+ else {
2046
+ value = Math.round((value * dssConstants.outputChannelUnitRoleMap[outputType].native.nativeMax) / 100);
2047
+ this.dssQueue.queueSetOutputValue(dev, dssConstants.outputChannelUnitRoleMap[outputType].native.channelIndex, dssConstants.outputChannelUnitRoleMap[outputType].native.nativeMax, value, 'high', err => {
2048
+ if (err) {
2049
+ this.logOutputWriteError(dev, err);
2050
+ }
2051
+ else {
2052
+ this.setStateSafe(dev.outputChannelList[outputType], originalValue);
2053
+ }
2054
+ });
2055
+ }
2056
+ };
2057
+ // Only the initial read depends on the option
2058
+ if (this.adapter.config.initializeOutputValues) {
2059
+ if (!(this.smartHomeSync && this.smartHomeSync.requestDeviceSync(dev, [outputType]))) {
2060
+ this.queueClassicOutputRead(dev, outputType, 'medium');
2061
+ }
2062
+ }
2063
+ });
2064
+ }
2065
+ const valueUpdateTimeouts = {};
2066
+ this.dss.on(dev.dSUID, data => {
2067
+ this.adapter.log.debug(`DEVICE event ${JSON.stringify(data)}`);
2068
+ if (data.name !== 'callScene' && data.name !== 'undoScene') {
2069
+ return;
2070
+ }
2071
+ // The preset stands in for a position that used to be unknowable while the
2072
+ // blind travelled. With the sync the real one arrives about two seconds
2073
+ // later and follows the movement, so the preset would only add a jump -
2074
+ // and it carries the value of the GROUP scene, which is not always the one
2075
+ // this device travels to (measured: preset 50 while the device went to 60,
2076
+ // and the state stood wrong for 21 seconds until the real value arrived).
2077
+ if (this.adapter.config.usePresetValues && !this.smartHomeSync) {
2078
+ let shadePos = dssConstants.shadeSceneValueMap[data.properties.sceneID];
2079
+ if (shadePos !== null && shadePos !== undefined) {
2080
+ shadePos = Math.round((shadePos * 100) / 65535);
2081
+ positionName && this.setStateSafe(dev.outputChannelList[positionName], shadePos);
2082
+ if ((shadePos === 0 || shadePos === 100) && angleName && dev.outputChannelList[angleName]) {
2083
+ if (!this.dssObjects[dev.outputChannelList[angleName]]) {
2084
+ this.adapter.log.warn(`Can not set unknown state ${dev.outputChannelList[angleName]}`);
2085
+ }
2086
+ else {
2087
+ this.setStateSafe(dev.outputChannelList[angleName], shadePos);
2088
+ this.initialObjectValues[dev.outputChannelList[angleName]] = shadePos;
2089
+ }
2090
+ }
2091
+ }
2092
+ }
2093
+ // Re-reading the real output values after a scene is a read as well, so it follows
2094
+ // the same option. Without it the states are still updated from the preset map
2095
+ // above (usePresetValues), the adapter just does not query the DSS.
2096
+ if (dev.outputChannelList && this.adapter.config.initializeOutputValues) {
2097
+ // One debounced status request of the new API replaces the per-channel
2098
+ // reads, including the follow-up reads while the blind is still moving
2099
+ if (this.smartHomeSync && this.smartHomeSync.requestDeviceSync(dev)) {
2100
+ // Classic re-read timers armed while the sync was in its failure
2101
+ // backoff would now read a second time - the status covers them
2102
+ Object.keys(valueUpdateTimeouts).forEach(outputType => {
2103
+ if (valueUpdateTimeouts[outputType]) {
2104
+ clearTimeout(valueUpdateTimeouts[outputType]);
2105
+ this.pendingTimeouts.delete(valueUpdateTimeouts[outputType]);
2106
+ valueUpdateTimeouts[outputType] = null;
2107
+ }
2108
+ });
2109
+ return;
2110
+ }
2111
+ Object.keys(dev.outputChannelList).forEach(outputType => {
2112
+ if (valueUpdateTimeouts[outputType]) {
2113
+ clearTimeout(valueUpdateTimeouts[outputType]);
2114
+ this.pendingTimeouts.delete(valueUpdateTimeouts[outputType]);
2115
+ valueUpdateTimeouts[outputType] = null;
2116
+ }
2117
+ valueUpdateTimeouts[outputType] = this.setClearableTimeout(() => {
2118
+ valueUpdateTimeouts[outputType] = null;
2119
+ this.queueClassicOutputRead(dev, outputType, 'medium');
2120
+ }, 2000);
2121
+ });
2122
+ }
2123
+ });
2124
+ callback && setImmediate(() => callback());
2125
+ }
2126
+ /**
2127
+ * Reports a failed output value read.
2128
+ *
2129
+ * Not every device answers for every channel it declares - a blind without tilt
2130
+ * answers the angle parameter with HTTP 500. That is a property of the device, not a
2131
+ * fault, and the value is re-read after every scene. So it is reported once per device
2132
+ * and channel and only at debug afterwards.
2133
+ *
2134
+ * @param dev device as reported by the DSS
2135
+ * @param outputType e.g. "shadeOpeningAngleOutside"
2136
+ */
2137
+ logOutputReadError(dev, outputType, err) {
2138
+ const key = `${dev.dSUID}.${outputType}`;
2139
+ const message = `Could not read ${outputType} of ${dev.name || dev.dSUID}: ${(err && err.message) || err}`;
2140
+ if (dssQueue_1.DSSQueue.isExpectedQueueError(err)) {
2141
+ // Cancelled by the adapter stop - not a property of the device, so it must
2142
+ // neither be reported nor block the "reported once" bookkeeping.
2143
+ this.adapter.log.debug(message);
2144
+ return;
2145
+ }
2146
+ if (this.reportedOutputReadErrors.has(key)) {
2147
+ this.adapter.log.debug(message);
2148
+ return;
2149
+ }
2150
+ this.reportedOutputReadErrors.add(key);
2151
+ this.adapter.log.info(`${message}. The device does not deliver this value - the state stays empty. This is only reported once.`);
2152
+ }
2153
+ /**
2154
+ * Single entry point for reporting a failed queued request.
2155
+ *
2156
+ * Expected cancellations are classified centrally by DSSQueue.isExpectedQueueError():
2157
+ * - a queued but not yet sent value that was replaced by a newer one (SupersededError)
2158
+ * is normal last-write-wins coalescing, not a DSS error
2159
+ * - a request cancelled by the adapter stop is expected as well
2160
+ *
2161
+ * Everything else (network errors, DSS error responses, invalid answers) stays a warning.
2162
+ */
2163
+ logQueueError(message, err) {
2164
+ if (dssQueue_1.DSSQueue.isExpectedQueueError(err)) {
2165
+ this.adapter.log.debug(message);
2166
+ return;
2167
+ }
2168
+ this.adapter.log.warn(message);
2169
+ }
2170
+ /**
2171
+ * Remembers what the dSS reports for an apartment user state. Only then can a
2172
+ * write of the same value be skipped safely: a state someone changed in the dSS
2173
+ * must not look unchanged to us.
2174
+ *
2175
+ * @param id ioBroker state id
2176
+ */
2177
+ noteUserStateValue(id, value) {
2178
+ const tracked = this.userStates.get(id);
2179
+ if (tracked) {
2180
+ tracked.value = value;
2181
+ }
2182
+ }
2183
+ /**
2184
+ * Sets a state value. Values delivered by the request queue can arrive before
2185
+ * processObjectQueue() has created the objects - such a value is parked as an initial
2186
+ * value instead of being written to an object that does not exist yet.
2187
+ *
2188
+ * @param id ioBroker state id
2189
+ * @param value the value to write
2190
+ * @param [options] write options
2191
+ * @param [options.skipUnchanged] drops a write that would
2192
+ * publish the value that is already there. ONLY for polling and reconciling paths -
2193
+ * see this.publishedValues.
2194
+ * @returns true when the value really went out, so a caller that counts its
2195
+ * writes counts writes and not attempts
2196
+ */
2197
+ setStateSafe(id, value, options) {
2198
+ if (value === undefined) {
2199
+ return false;
2200
+ }
2201
+ if (!this.objectsReady) {
2202
+ this.initialObjectValues[id] = value;
2203
+ return false;
2204
+ }
2205
+ if (options && options.skipUnchanged && this.publishedValues.get(id) === value) {
2206
+ return false;
2207
+ }
2208
+ this.adapter.setDssState(id, value);
2209
+ return true;
2210
+ }
2211
+ /**
2212
+ * Remembers what is currently in a state. Fed from setDssState() for everything this
2213
+ * adapter writes, and from the acknowledged echo in onStateChange() for everything
2214
+ * someone else wrote - without the second half a state overwritten by another adapter
2215
+ * could never be corrected by the next reconciliation.
2216
+ */
2217
+ notePublishedValue(id, value) {
2218
+ this.publishedValues.set(id, value);
2219
+ }
2220
+ /**
2221
+ * The value a state property carries at startup.
2222
+ *
2223
+ * Most states of the property dump describe themselves with a word: {"name":"presence",
2224
+ * "state":"present","value":"present"}. A few carry only the raw value and no word at
2225
+ * all - measured against a dSS20 1.19.13: {"name":"daylight","value":true,"script_id":
2226
+ * "solar_computer"} and {"name":"holiday","value":"off",...}. Reading only .state left
2227
+ * those five apartment states without any value from the first start to the next event
2228
+ * that happened to mention them, and for daylight and its siblings that event never
2229
+ * came. Both forms end up in coerceScalarValue(), which knows what to do with a boolean
2230
+ * as well as with "off".
2231
+ *
2232
+ * @param state one entry of the property dump -
2233
+ * the callers walk a list the dSS delivered, so an unusable entry is a normal case
2234
+ * @returns the value to park as the initial one, undefined when there is none
2235
+ */
2236
+ static initialStateValue(state) {
2237
+ if (!state) {
2238
+ return undefined;
2239
+ }
2240
+ return state.state !== undefined ? state.state : state.value;
2241
+ }
2242
+ /**
2243
+ * Converts a written state value into a boolean. Plain !!value would turn the
2244
+ * strings "false" and "0" into true.
2245
+ */
2246
+ static toBoolean(value) {
2247
+ if (typeof value === 'string') {
2248
+ const normalized = value.trim().toLowerCase();
2249
+ // The DSS uses different words for the "off" state depending on the state type
2250
+ if (DSSStructure.FALSY_STATE_WORDS.includes(normalized)) {
2251
+ return false;
2252
+ }
2253
+ return true;
2254
+ }
2255
+ return !!value;
2256
+ }
2257
+ /**
2258
+ * Resolves the state id suffix of a scene. Apartment and zone/group scenes live in
2259
+ * two disjoint maps, so both have to be considered for every level.
2260
+ *
2261
+ * A scene id the DSS did not send at all is a normal case for the callers, and the
2262
+ * map lookup answers it with null like any unknown scene - so undefined belongs in
2263
+ * the type instead of being an unwritten assumption.
2264
+ *
2265
+ * @returns converted scene name or null when the scene is unknown
2266
+ */
2267
+ resolveSceneStateName(sceneId) {
2268
+ // A string or a missing id indexes the maps the same way it always did
2269
+ const name = dssConstants.apartmentScenes[sceneId] || dssConstants.zoneSceneCommands[sceneId];
2270
+ if (!name) {
2271
+ return null;
2272
+ }
2273
+ return this.convertSceneName(name);
2274
+ }
2275
+ /**
2276
+ * Resolves the ioBroker state of a scene exactly like the event handling does.
2277
+ *
2278
+ * Special groups use their own scene names for the same scene numbers: temperature
2279
+ * control (group 48) calls scene 0 "Heating Off" and the ventilation groups (10/64)
2280
+ * call it "Off", while the generic map calls it "Preset 0". All of them are registered
2281
+ * in the state map under the same DSS key, so the state map is the only authority.
2282
+ * Resolving the name generically here would mark the generic state as active while
2283
+ * every later event toggles the special one - both would permanently disagree.
2284
+ *
2285
+ * @param dssSceneKey state map key, e.g. "5.48.scenes.0"
2286
+ * @param sceneId scene number reported by the DSS
2287
+ * @param baseId object path that holds the "scenes" channel
2288
+ * @returns state id or null when the scene has no state
2289
+ */
2290
+ resolveSceneStateId(dssSceneKey, sceneId, baseId) {
2291
+ const mapped = this.stateMap[dssSceneKey];
2292
+ if (mapped) {
2293
+ return mapped;
2294
+ }
2295
+ // Fallback for scenes that exist as an object but were never registered in the
2296
+ // state map (keeps the previous behaviour for those)
2297
+ const sceneName = this.resolveSceneStateName(sceneId);
2298
+ return sceneName ? `${baseId}.scenes.${sceneName}` : null;
2299
+ }
2300
+ /**
2301
+ * Logs a failed output write. A superseded request is normal for fast slider
2302
+ * movements and therefore only logged at debug level.
2303
+ *
2304
+ * @param dev the device the value was meant for
2305
+ * @param err whatever the queue rejected with - the DSS layer hands over an
2306
+ * Error, a response message or a bare status code, which is why the callers read it
2307
+ * as `(err && err.message) || err`
2308
+ */
2309
+ logOutputWriteError(dev, err) {
2310
+ if (dssQueue_1.DSSQueue.isExpectedQueueError(err)) {
2311
+ this.adapter.log.debug(`Output value for ${dev.dSUID} was not sent: ${(err && err.message) || err} (expected, no error)`);
2312
+ return;
2313
+ }
2314
+ this.adapter.log.warn(`Error when setting output value for ${dev.dSUID}: ${(err && err.message) || err}`);
2315
+ }
2316
+ convertSceneName(name) {
2317
+ if (!name) {
2318
+ return name;
2319
+ }
2320
+ const brackets = name.indexOf(' (');
2321
+ if (brackets !== -1) {
2322
+ name = name.substr(0, brackets);
2323
+ }
2324
+ name = name.replace(/ /g, '');
2325
+ return name;
2326
+ }
2327
+ createUserActions() {
2328
+ if (!this.userActions || !this.userActions.length) {
2329
+ return;
2330
+ }
2331
+ this.addFolderObject('userActions', 'User Actions', 'channel');
2332
+ this.userActions.forEach(action => {
2333
+ this.addStateObject(`userActions.${action.id}`, {
2334
+ name: `User Action ${action.name}`,
2335
+ type: 'boolean',
2336
+ role: 'button',
2337
+ }, value => {
2338
+ if (!value) {
2339
+ return;
2340
+ }
2341
+ this.dssQueue.pushQueryQueue(`event-${action.id}`, {
2342
+ dssClass: 'event',
2343
+ dssFunction: 'raise',
2344
+ params: {
2345
+ name: 'highlevelevent',
2346
+ parameter: `id=${action.id}`,
2347
+ },
2348
+ }, 'high', (err, res) => {
2349
+ if (err || (res && !res.ok)) {
2350
+ this.logQueueError(`Error while raise event for apartment: ${err || JSON.stringify(res)}`, err);
2351
+ }
2352
+ });
2353
+ });
2354
+ this.initialObjectValues[`userActions.${action.id}`] = false;
2355
+ });
2356
+ }
2357
+ /**
2358
+ * The user defined states of the apartment - writable, and each write goes to the
2359
+ * dSS. Kept in its own method so the write path can be tested without building a
2360
+ * whole apartment.
2361
+ */
2362
+ createApartmentUserStates() {
2363
+ if (this.propertyUserStates && this.propertyUserStates.length) {
2364
+ this.addFolderObject('apartment.userStates', 'Apartment User States', 'channel');
2365
+ this.propertyUserStates.forEach(state => {
2366
+ const stateId = `apartment.userStates.${state.name.replace(/\./g, '-')}`;
2367
+ const stateValue = state.state;
2368
+ const stateObj = {
2369
+ name: state.displayName,
2370
+ role: 'indicator',
2371
+ type: 'string',
2372
+ };
2373
+ this.userStates.set(stateId, { name: state.name, value: stateValue });
2374
+ this.addStateObject(stateId, state.name, stateObj, stateValue, value => {
2375
+ const tracked = this.userStates.get(stateId);
2376
+ if (tracked && tracked.value === value) {
2377
+ // The dSS already holds this value: setting it again changes
2378
+ // nothing there and emits no event, it only costs a request.
2379
+ // Scripts that re-assert their states every few minutes made
2380
+ // this the biggest remaining load on the classic interface.
2381
+ this.adapter.log.debug(`User state ${state.name} already is ${value}, not sent again`);
2382
+ this.setStateSafe(stateId, value);
2383
+ return;
2384
+ }
2385
+ if (tracked) {
2386
+ tracked.value = value;
2387
+ }
2388
+ this.dssQueue.pushQueryQueue('apartment-user', {
2389
+ dssClass: 'state',
2390
+ dssFunction: 'set',
2391
+ params: {
2392
+ addon: 'system-addon-user-defined-states',
2393
+ name: state.name,
2394
+ value: value,
2395
+ },
2396
+ }, 'high', (err, res) => {
2397
+ if (err || (res && !res.ok)) {
2398
+ // What the dSS holds is unknown again - the next write
2399
+ // has to go out, even with the same value
2400
+ if (tracked) {
2401
+ tracked.value = undefined;
2402
+ }
2403
+ this.logQueueError(`Error while set State for apartment-user: ${err || JSON.stringify(res)}`, err);
2404
+ }
2405
+ });
2406
+ });
2407
+ this.initialObjectValues[stateId] = stateValue;
2408
+ });
2409
+ }
2410
+ }
2411
+ /**
2412
+ * Creates the outdoor sensors of the apartment from the last getSensorValues answer.
2413
+ *
2414
+ * The DSS leaves a value out of that answer once it has gone stale - an outdoor
2415
+ * brightness sensor stops sending in the dark, and the value is missing from then on.
2416
+ * Creating only what the answer carries made the state disappear on every restart at
2417
+ * night, together with its history and its custom settings. A sensor ioBroker already
2418
+ * knows therefore keeps its object; only its value is not refreshed. A sensor that was
2419
+ * really removed from the installation keeps its object too - deleting it stays a
2420
+ * deliberate step of the user.
2421
+ */
2422
+ createOutdoorSensors() {
2423
+ const outdoor = (this.sensorValues && this.sensorValues.outdoor) || {};
2424
+ const existingStates = (this.adapter.objectHelper && this.adapter.objectHelper.existingStates) || {};
2425
+ const knownWithoutValue = Object.keys(dssConstants.sensorValuesRoleMapOutdoor).filter(sensorName => !outdoor[sensorName] && existingStates[`apartment.sensors.outdoor.${sensorName}`]);
2426
+ if (!Object.keys(outdoor).length && !knownWithoutValue.length) {
2427
+ return;
2428
+ }
2429
+ this.addFolderObject('apartment.sensors.outdoor', 'Apartment Outdoor Sensors', 'channel');
2430
+ const addSensor = (sensorName) => this.addStateObject(`apartment.sensors.outdoor.${sensorName}`, `0.sensors.${dssConstants.sensorValuesRoleMapOutdoor[sensorName].native.sensorType}`, dssConstants.sensorValuesRoleMapOutdoor[sensorName]);
2431
+ Object.keys(outdoor).forEach(sensorName => {
2432
+ if (!dssConstants.sensorValuesRoleMapOutdoor[sensorName]) {
2433
+ this.adapter.log.warn(`INVALID Sensor Type! ${sensorName}`);
2434
+ return;
2435
+ }
2436
+ addSensor(sensorName);
2437
+ this.initialObjectValues[`apartment.sensors.outdoor.${sensorName}`] = {
2438
+ val: outdoor[sensorName].value,
2439
+ ts: typeof outdoor[sensorName].time === 'number'
2440
+ ? outdoor[sensorName].time
2441
+ : new Date(outdoor[sensorName].time).getTime(),
2442
+ };
2443
+ });
2444
+ knownWithoutValue.forEach(sensorName => {
2445
+ this.adapter.log.debug(`The DSS reports no value for apartment.sensors.outdoor.${sensorName}, the known state keeps its last one`);
2446
+ addSensor(sensorName);
2447
+ // deliberately no entry in initialObjectValues - the old value stays untouched
2448
+ });
2449
+ }
2450
+ createApartment(apartment, reachableZoneGroups, callback) {
2451
+ this.addFolderObject('apartment', 'Apartment');
2452
+ let callbackCounter = 0;
2453
+ // zones that are assigned to a floor, see the check below
2454
+ const zonesOnAFloor = new Set();
2455
+ // Create Floors and Zones and Groups inside
2456
+ Object.keys(apartment.floors).forEach(floorId => {
2457
+ const floor = apartment.floors[floorId];
2458
+ this.addFolderObject(`apartment.${floorId}`, floor.name || `Floor ${floorId}`);
2459
+ floor.zones.forEach((zoneId) => {
2460
+ zonesOnAFloor.add(String(zoneId));
2461
+ callbackCounter++;
2462
+ const zoneReachableGroups = (reachableZoneGroups[zoneId] && reachableZoneGroups[zoneId].groups) || [];
2463
+ setImmediate(() => this.processZone(`apartment.${floorId}`, apartment.zones[zoneId], zoneReachableGroups, this.sensorValues.zones[zoneId], this.temperatureControlStatus.zones[zoneId], () => {
2464
+ !--callbackCounter && callback && callback(null);
2465
+ }));
2466
+ });
2467
+ });
2468
+ // Check if we have available Zones that were not assigned to any floor (should not happen).
2469
+ // Deliberately NOT via processedZones: the zones above are handed to processZone() through
2470
+ // setImmediate, so that map is still empty here and every regular zone would be reported.
2471
+ // isValid/isPresent are only evaluated when the DSS really reports them - not every
2472
+ // firmware sends isValid for a zone, and a plain truthiness check would silence the
2473
+ // whole check on those installations.
2474
+ Object.keys(apartment.zones).forEach(zoneId => {
2475
+ const zone = apartment.zones[zoneId];
2476
+ if (zone.isValid === false || zone.isPresent === false) {
2477
+ // processZone() never runs for it, so none of its states gets an object
2478
+ this.skippedStatePrefixes.add(`zone.${zoneId}.`);
2479
+ return;
2480
+ }
2481
+ if (zonesOnAFloor.has(String(zoneId))) {
2482
+ return;
2483
+ }
2484
+ this.adapter.log.warn(`EXTRANOUS ZONE found ${zoneId}`);
2485
+ });
2486
+ this.addFolderObject('apartment.scenes', 'Apartment Scenes', 'channel');
2487
+ const sceneList = {};
2488
+ Object.keys(dssConstants.apartmentScenes).forEach(sceneId => {
2489
+ // Object.keys() delivers strings - compare as numbers instead of relying on
2490
+ // the implicit coercion of the relational operators
2491
+ if (Number(sceneId) >= 67 && Number(sceneId) <= 70) {
2492
+ return;
2493
+ } // ignore Zone Scenes?
2494
+ const sceneStateId = `apartment.scenes.${this.convertSceneName(dssConstants.apartmentScenes[Number(sceneId)])}`;
2495
+ sceneList[sceneId] = dssConstants.apartmentScenes[Number(sceneId)];
2496
+ this.addStateObject(sceneStateId, `0.0.scenes.${sceneId}`, {
2497
+ name: `Apartment ${dssConstants.apartmentScenes[Number(sceneId)]}`,
2498
+ type: 'boolean',
2499
+ role: 'switch',
2500
+ }, value => {
2501
+ value = DSSStructure.toBoolean(value);
2502
+ this.dssQueue.pushQueryQueue('apartment', {
2503
+ dssClass: 'apartment',
2504
+ dssFunction: value ? 'callScene' : 'undoScene',
2505
+ params: {
2506
+ sceneNumber: sceneId,
2507
+ },
2508
+ }, 'high', (err, res) => {
2509
+ if (err || (res && !res.ok)) {
2510
+ this.logQueueError(`Error while ${value ? 'callScene' : 'undoScene'} for apartment: ${err || JSON.stringify(res)}`, err);
2511
+ }
2512
+ });
2513
+ });
2514
+ this.initialObjectValues[sceneStateId] = false;
2515
+ });
2516
+ if (Object.keys(sceneList).length) {
2517
+ this.addStateObject('apartment.scenes.sceneId', {
2518
+ name: 'Scene ID',
2519
+ type: 'number',
2520
+ role: 'state',
2521
+ states: sceneList,
2522
+ }, value => {
2523
+ if (!sceneList[value]) {
2524
+ this.adapter.log.warn(`Invalid Scene ID ${value} for apartment.scenes.sceneId`);
2525
+ return;
2526
+ }
2527
+ this.dssQueue.pushQueryQueue('apartment', {
2528
+ dssClass: 'apartment',
2529
+ dssFunction: 'callScene',
2530
+ params: {
2531
+ sceneNumber: value,
2532
+ },
2533
+ }, 'high', (err, res) => {
2534
+ if (err || (res && !res.ok)) {
2535
+ this.logQueueError(`Error while callScene for apartment: ${err || JSON.stringify(res)}`, err);
2536
+ }
2537
+ });
2538
+ });
2539
+ callbackCounter++;
2540
+ this.dssQueue.pushQueryQueue('apartment', {
2541
+ dssClass: 'zone',
2542
+ dssFunction: 'getLastCalledScene',
2543
+ params: {
2544
+ id: 0,
2545
+ },
2546
+ }, 'high', (err, res) => {
2547
+ if (err || (res && !res.ok) || !res.result || res.result.scene === undefined) {
2548
+ this.logQueueError(`Error while getLastCalledScene for apartment: ${err || JSON.stringify(res)}`, err);
2549
+ }
2550
+ else {
2551
+ this.initialObjectValues['apartment.scenes.sceneId'] = res.result.scene;
2552
+ this.initialScenes['0.0'] = res.result.scene;
2553
+ const sceneStateId = this.resolveSceneStateId(`0.0.scenes.${res.result.scene}`, res.result.scene, 'apartment');
2554
+ if (sceneStateId && this.dssObjects[sceneStateId]) {
2555
+ this.initialObjectValues[sceneStateId] = true;
2556
+ }
2557
+ }
2558
+ !--callbackCounter && callback && callback(null);
2559
+ });
2560
+ }
2561
+ const aptStates = this.findStates('^([^.]*)$');
2562
+ if (aptStates && aptStates.length) {
2563
+ this.addFolderObject('apartment.states', 'Apartment States', 'channel');
2564
+ aptStates.forEach(state => {
2565
+ if (!state.matchedName) {
2566
+ return;
2567
+ }
2568
+ const stateId = `apartment.states.${state.matchedName}`;
2569
+ const stateName = state.matchedName;
2570
+ let roleMap = dssConstants.apartmentStateRoleMap[stateName];
2571
+ if (!roleMap) {
2572
+ roleMap = {
2573
+ name: stateName,
2574
+ role: 'indicator',
2575
+ type: 'boolean',
2576
+ read: true,
2577
+ write: false,
2578
+ native: {
2579
+ valueTrue: 'active',
2580
+ valueFalse: 'inactive',
2581
+ },
2582
+ };
2583
+ }
2584
+ this.addStateObject(stateId, state.name, roleMap, value => {
2585
+ if (!this.dssObjects[stateId] || !this.dssObjects[stateId].native) {
2586
+ return;
2587
+ }
2588
+ const { valueTrue, valueFalse } = this.dssObjects[stateId].native;
2589
+ if (valueTrue === undefined && valueFalse === undefined) {
2590
+ // A state that carries the wording of the DSS (heating_water_system
2591
+ // answers "hot water") has no active/inactive pair to send, and a
2592
+ // guessed one would write nonsense into the installation
2593
+ this.adapter.log.warn(`Cannot write ${stateId}: this DSS state carries text, not a flag`);
2594
+ return;
2595
+ }
2596
+ this.dssQueue.pushQueryQueue('apartment', {
2597
+ dssClass: 'state',
2598
+ dssFunction: 'set',
2599
+ params: {
2600
+ name: state.name,
2601
+ value: DSSStructure.toBoolean(value) ? valueTrue : valueFalse,
2602
+ },
2603
+ }, 'high', (err, res) => {
2604
+ if (err || (res && !res.ok)) {
2605
+ this.logQueueError(`Error while set State for apartment: ${err || JSON.stringify(res)}`, err);
2606
+ }
2607
+ });
2608
+ });
2609
+ // Converted to the declared type of the object when written
2610
+ this.initialObjectValues[stateId] = DSSStructure.initialStateValue(state);
2611
+ });
2612
+ }
2613
+ this.createApartmentUserStates();
2614
+ this.addFolderObject('apartment.sensors', 'Apartment Sensors');
2615
+ // Ignore weather for now!
2616
+ this.createOutdoorSensors();
2617
+ // Sensor 60 is not a flag but a status code (0 = OK, 2 = Malfunction, 4 = Service,
2618
+ // 6 = Malfunction+Service). A boolean state would collapse every code != 0 to true
2619
+ // and lose the distinction, so the declared numeric type incl. its states map is used.
2620
+ this.addStateObject('apartment.sensors.VentilationStatusValue', '0.sensors.60', {
2621
+ ...dssConstants.sensorUnitRoleMap[60],
2622
+ name: 'Ventilation Status',
2623
+ read: true,
2624
+ write: false,
2625
+ });
2626
+ // Create Apartment groups, as soon as at least one device is present
2627
+ this.addFolderObject('apartment.groups', 'Apartment Groups');
2628
+ apartment.zone0.groups.forEach((group) => {
2629
+ if (!group.devices || !group.devices.length) {
2630
+ this.skippedStatePrefixes.add(`zone.0.group.${group.id}.`);
2631
+ return;
2632
+ }
2633
+ callbackCounter++;
2634
+ setImmediate(() => this.processGroup(`apartment.groups.${group.id}`, 0, group, () => {
2635
+ !--callbackCounter && callback && callback(null);
2636
+ }));
2637
+ // setApartmentScene: '/apartment/callScene?sceneNumber=%s&force=true',
2638
+ // setZoneScene: '/zone/callScene?id=%s&sceneNumber=%s&force=true',
2639
+ // setGroupScene: '/zone/callScene?id=%s&groupID=%s&sceneNumber=%s&force=true',
2640
+ // undoScene
2641
+ });
2642
+ !callbackCounter && callback && setImmediate(() => callback(null));
2643
+ }
2644
+ processZone(baseId, zone, reachableGroups, sensorValues, temperatureControlStatus, callback) {
2645
+ if (!zone) {
2646
+ this.adapter.log.debug('INVALID ZONE (not contained in apartment structure)');
2647
+ return void (callback && setImmediate(callback, null));
2648
+ }
2649
+ if (!zone.isPresent) {
2650
+ this.adapter.log.debug(`Ignore not present zone ${zone.id}`);
2651
+ this.skippedStatePrefixes.add(`zone.${zone.id}.`);
2652
+ return void (callback && setImmediate(callback, null));
2653
+ }
2654
+ if (this.processedZones[zone.id]) {
2655
+ this.adapter.log.debug(`Zone ${zone.id} already processec`);
2656
+ return void (callback && setImmediate(callback, null));
2657
+ }
2658
+ const zoneBaseId = `${baseId}.${zone.id}`;
2659
+ this.addFolderObject(zoneBaseId, zone.name || `Zone ${zone.id}`);
2660
+ const zoneStates = this.findStates(`^zone\\.${zone.id}\\.([^.]*)$`);
2661
+ if (zoneStates && zoneStates.length) {
2662
+ this.addFolderObject(`${zoneBaseId}.states`, 'Zone States', 'channel');
2663
+ zoneStates.forEach(state => {
2664
+ if (!state.matchedName) {
2665
+ return;
2666
+ }
2667
+ const stateId = `${zoneBaseId}.states.${state.matchedName}`;
2668
+ const stateName = state.matchedName;
2669
+ if (!dssConstants.zoneStateRoleMap[stateName]) {
2670
+ this.adapter.log.info(`INVALID Zone State ${state.matchedName}: ${JSON.stringify(state)}`);
2671
+ return;
2672
+ }
2673
+ this.addStateObject(stateId, state.name, dssConstants.zoneStateRoleMap[stateName], state.state, value => {
2674
+ value = DSSStructure.toBoolean(value);
2675
+ if (!this.dssObjects[stateId] || !this.dssObjects[stateId].native) {
2676
+ return;
2677
+ }
2678
+ this.dssQueue.pushQueryQueue('zone', {
2679
+ dssClass: 'state',
2680
+ dssFunction: 'set',
2681
+ params: {
2682
+ name: state.name,
2683
+ value: value
2684
+ ? this.dssObjects[stateId].native.valueTrue
2685
+ : this.dssObjects[stateId].native.valueFalse,
2686
+ },
2687
+ }, 'high', (err, res) => {
2688
+ if (err || (res && !res.ok)) {
2689
+ this.logQueueError(`Error while set State for zone: ${err || JSON.stringify(res)}`, err);
2690
+ }
2691
+ });
2692
+ });
2693
+ // Converted to the declared type of the object when written
2694
+ this.initialObjectValues[stateId] = DSSStructure.initialStateValue(state);
2695
+ });
2696
+ }
2697
+ this.createZoneSensorStates(zoneBaseId, zone);
2698
+ let groupCounter = 0;
2699
+ zone.groups.forEach((group) => {
2700
+ if (!reachableGroups.includes(group.id)) {
2701
+ this.skippedStatePrefixes.add(`zone.${zone.id}.group.${group.id}.`);
2702
+ return;
2703
+ }
2704
+ groupCounter++;
2705
+ setImmediate(() => this.processGroup(`${zoneBaseId}.${group.id}`, zone.id, group, () => {
2706
+ !--groupCounter && callback && callback(null);
2707
+ }));
2708
+ });
2709
+ this.processedZones[zone.id] = true;
2710
+ this.addFolderObject(`${zoneBaseId}.scenes`, `${zone.name || `Zone ${zone.id}`} Scenes`, 'channel');
2711
+ const sceneList = {};
2712
+ this.basicRoomScenes.forEach(sceneId => {
2713
+ const sceneStateId = `${zoneBaseId}.scenes.${this.convertSceneName(dssConstants.zoneSceneCommands[sceneId])}`;
2714
+ sceneList[sceneId] = dssConstants.zoneSceneCommands[sceneId];
2715
+ this.addStateObject(sceneStateId, `${zone.id}.0.scenes.${sceneId}`, {
2716
+ name: `Zone ${zone.id} ${dssConstants.zoneSceneCommands[sceneId]}`,
2717
+ type: 'boolean',
2718
+ role: 'switch',
2719
+ }, value => {
2720
+ value = DSSStructure.toBoolean(value);
2721
+ this.dssQueue.pushQueryQueue('zone', {
2722
+ dssClass: 'zone',
2723
+ dssFunction: value ? 'callScene' : 'undoScene',
2724
+ params: {
2725
+ id: zone.id,
2726
+ sceneNumber: sceneId,
2727
+ },
2728
+ }, 'high', (err, res) => {
2729
+ if (err || (res && !res.ok)) {
2730
+ this.logQueueError(`Error while ${value ? 'callScene' : 'undoScene'} for zone ${zone.id}: ${err || JSON.stringify(res)}`, err);
2731
+ }
2732
+ });
2733
+ });
2734
+ this.initialObjectValues[sceneStateId] = false;
2735
+ });
2736
+ for (let sceneId = 67; sceneId <= 70; sceneId++) {
2737
+ const sceneStateId = `${zoneBaseId}.scenes.${this.convertSceneName(dssConstants.apartmentScenes[sceneId])}`;
2738
+ sceneList[sceneId] = dssConstants.apartmentScenes[sceneId];
2739
+ this.addStateObject(sceneStateId, `${zone.id}.0.scenes.${sceneId}`, {
2740
+ name: `Zone ${zone.id} ${dssConstants.apartmentScenes[sceneId]}`,
2741
+ type: 'boolean',
2742
+ role: 'switch',
2743
+ }, value => {
2744
+ value = DSSStructure.toBoolean(value);
2745
+ this.dssQueue.pushQueryQueue('zone', {
2746
+ dssClass: 'zone',
2747
+ dssFunction: value ? 'callScene' : 'undoScene',
2748
+ params: {
2749
+ id: zone.id,
2750
+ sceneNumber: sceneId,
2751
+ },
2752
+ }, 'high', (err, res) => {
2753
+ if (err || (res && !res.ok)) {
2754
+ this.logQueueError(`Error while ${value ? 'callScene' : 'undoScene'} for zone ${zone.id}: ${err || JSON.stringify(res)}`, err);
2755
+ }
2756
+ });
2757
+ });
2758
+ this.initialObjectValues[sceneStateId] = false;
2759
+ }
2760
+ if (Object.keys(sceneList).length) {
2761
+ this.addStateObject(`${zoneBaseId}.scenes.sceneId`, {
2762
+ name: 'Scene ID',
2763
+ type: 'number',
2764
+ role: 'value',
2765
+ states: sceneList,
2766
+ }, value => {
2767
+ if (!sceneList[value]) {
2768
+ this.adapter.log.warn(`Invalid Scene ID ${value} for Zone ${zone.id}.scenes.sceneId`);
2769
+ return;
2770
+ }
2771
+ this.dssQueue.pushQueryQueue('zone', {
2772
+ dssClass: 'zone',
2773
+ dssFunction: 'callScene',
2774
+ params: {
2775
+ id: zone.id,
2776
+ sceneNumber: value,
2777
+ },
2778
+ }, 'high', (err, res) => {
2779
+ if (err || (res && !res.ok)) {
2780
+ this.logQueueError(`Error while ${value ? 'callScene' : 'undoScene'} for Zone ${zone.id}: ${err || JSON.stringify(res)}`, err);
2781
+ }
2782
+ });
2783
+ });
2784
+ groupCounter++;
2785
+ this.dssQueue.pushQueryQueue('zone', {
2786
+ dssClass: 'zone',
2787
+ dssFunction: 'getLastCalledScene',
2788
+ params: {
2789
+ id: zone.id,
2790
+ },
2791
+ }, 'high', (err, res) => {
2792
+ if (err || (res && !res.ok) || !res.result || res.result.scene === undefined) {
2793
+ this.logQueueError(`Error while getLastCalledScene for zone ${zone.id}: ${err || JSON.stringify(res)}`, err);
2794
+ }
2795
+ else {
2796
+ this.initialObjectValues[`${zoneBaseId}.scenes.sceneId`] = res.result.scene;
2797
+ this.initialScenes[`${zone.id}.0`] = res.result.scene;
2798
+ const sceneStateId = this.resolveSceneStateId(`${zone.id}.0.scenes.${res.result.scene}`, res.result.scene, zoneBaseId);
2799
+ if (sceneStateId && this.dssObjects[sceneStateId]) {
2800
+ this.initialObjectValues[sceneStateId] = true;
2801
+ }
2802
+ }
2803
+ !--groupCounter && callback && callback(null);
2804
+ });
2805
+ }
2806
+ this.addFolderObject(`${zoneBaseId}.sensors`, `${zone.name || `Zone ${zone.id}`} Sensors`, 'channel');
2807
+ // Merken, wo die Sensor-States dieser Zone liegen - der Status der neuen API
2808
+ // adressiert Zonen ueber ihre Id (als String)
2809
+ this.zoneSensorBaseIds[String(zone.id)] = `${zoneBaseId}.sensors`;
2810
+ sensorValues = sensorValues || {};
2811
+ sensorValues.values = sensorValues.values || [];
2812
+ if (temperatureControlStatus) {
2813
+ sensorValues.values.push(temperatureControlStatus);
2814
+ }
2815
+ Object.keys(dssConstants.sensorValuesRoleMapZone).forEach(sensorValueName => {
2816
+ const sensor = sensorValues.values.find((val) => val && val[sensorValueName] !== undefined) || {};
2817
+ this.addStateObject(`${zoneBaseId}.sensors.${sensorValueName}`, `${zone.id}.sensors.${dssConstants.sensorValuesRoleMapZone[sensorValueName].native.sensorType}`, dssConstants.sensorValuesRoleMapZone[sensorValueName], value => {
2818
+ this.dssQueue.pushQueryQueue('zone', {
2819
+ dssClass: 'zone',
2820
+ dssFunction: 'pushSensorValue',
2821
+ params: {
2822
+ id: zone.id,
2823
+ groupID: 0,
2824
+ sensorType: dssConstants.sensorValuesRoleMapZone[sensorValueName].native.sensorType,
2825
+ sensorValue: value,
2826
+ },
2827
+ }, 'high', (err, res) => {
2828
+ if (err || (res && !res.ok)) {
2829
+ this.logQueueError(`Error while pushSensorValue for zone: ${err || JSON.stringify(res)}`, err);
2830
+ }
2831
+ });
2832
+ });
2833
+ if (sensor[sensorValueName] !== undefined) {
2834
+ this.initialObjectValues[`${zoneBaseId}.sensors.${sensorValueName}`] = sensor[sensorValueName];
2835
+ }
2836
+ });
2837
+ if (this.hasTemperatureControl(temperatureControlStatus)) {
2838
+ groupCounter++;
2839
+ this.createTemperatureControl(zoneBaseId, zone, temperatureControlStatus, () => {
2840
+ !--groupCounter && callback && callback(null);
2841
+ });
2842
+ }
2843
+ !groupCounter && callback && setImmediate(() => callback(null));
2844
+ }
2845
+ /**
2846
+ * Creates the room sensor states of dSS apps next to the zone states, for example
2847
+ * passiveCooling of the climate control.
2848
+ *
2849
+ * Only group 0 belongs to the room itself; a sensor state of another group is named
2850
+ * by reportUnmappedStates(). Read-only and without a write handler, the dSS computes
2851
+ * the value from the room sensor. A sensor state knows nothing but active, inactive
2852
+ * and unknown (dss-mainline src/model/state.cpp State::toString, a StateSensor has no
2853
+ * value list of its own), so an identifier without an entry in zoneSensorStateRoleMap
2854
+ * still gets a boolean. Unknown leaves it empty, like every other boolean state.
2855
+ *
2856
+ * @param zoneBaseId object path of the zone
2857
+ * @param zone zone as reported by the DSS
2858
+ */
2859
+ createZoneSensorStates(zoneBaseId, zone) {
2860
+ const states = this.addonSensorStates.filter(state => state.zoneId === zone.id && state.groupId === 0);
2861
+ // A failed read says nothing about the room. The objects of the last start keep their
2862
+ // mapping and their last value, the way createOutdoorSensors() keeps a sensor the dSS
2863
+ // left out - otherwise they would be listed as unknown ("Delete unknown objects"
2864
+ // removes them with their history), and each change would ask for a GitHub issue.
2865
+ const known = this.addonSensorStatesRead ? [] : this.knownZoneSensorStates(zoneBaseId, zone);
2866
+ if (!states.length && !known.length) {
2867
+ return;
2868
+ }
2869
+ if (!this.dssObjects[`${zoneBaseId}.states`]) {
2870
+ this.addFolderObject(`${zoneBaseId}.states`, 'Zone States', 'channel');
2871
+ }
2872
+ states.forEach(state => {
2873
+ let stateId = `${zoneBaseId}.states.${state.identifier.replace(FORBIDDEN_ID_CHARS, '_')}`;
2874
+ if (this.dssObjects[stateId]) {
2875
+ // A zone state or another sensor type already has this name. The dSS
2876
+ // keeps both apart by the sensor type, so the object id does as well.
2877
+ stateId = `${stateId}_type${state.sensorType}`;
2878
+ }
2879
+ // The dSS name stays the key of stateMap, whatever the object id became
2880
+ this.addStateObject(stateId, state.name, DSSStructure.zoneSensorStateDefinition(state), state.state);
2881
+ // Converted to the declared type of the object when written
2882
+ this.initialObjectValues[stateId] = DSSStructure.initialStateValue(state);
2883
+ this.matchedPropertyStates.add(state.name);
2884
+ });
2885
+ known.forEach(({ id, state }) => {
2886
+ this.adapter.log.debug(`The sensor states of dSS apps could not be read, ${id} keeps its last value`);
2887
+ // deliberately no entry in initialObjectValues - the old value stays untouched
2888
+ this.addStateObject(id, state.name, DSSStructure.zoneSensorStateDefinition(state));
2889
+ });
2890
+ }
2891
+ /**
2892
+ * The room sensor state objects a previous start created for this zone, recognised by
2893
+ * the dSS name kept in native.dssStateName. Their stored id is kept as it is, with a
2894
+ * _type<n> suffix or cleaned characters.
2895
+ *
2896
+ * @param zoneBaseId object path of the zone
2897
+ * @param zone zone as reported by the DSS
2898
+ */
2899
+ knownZoneSensorStates(zoneBaseId, zone) {
2900
+ const existingStates = (this.adapter.objectHelper && this.adapter.objectHelper.existingStates) || {};
2901
+ const prefix = `${zoneBaseId}.states.`;
2902
+ const result = [];
2903
+ Object.keys(existingStates).forEach(id => {
2904
+ const obj = existingStates[id];
2905
+ const name = id.startsWith(prefix) && obj && obj.native ? obj.native.dssStateName : undefined;
2906
+ const match = typeof name === 'string' ? ZONE_SENSOR_STATE.exec(name) : null;
2907
+ if (match && parseInt(match[1], 10) === zone.id && parseInt(match[2], 10) === 0 && !this.dssObjects[id]) {
2908
+ result.push({ id, state: { name, identifier: match[4] } });
2909
+ }
2910
+ });
2911
+ return result;
2912
+ }
2913
+ /**
2914
+ * The object definition of a room sensor state of a dSS app, see createZoneSensorStates().
2915
+ */
2916
+ static zoneSensorStateDefinition(state) {
2917
+ const definition = dssConstants.zoneSensorStateRoleMap[state.identifier] || {
2918
+ name: state.identifier,
2919
+ role: 'indicator',
2920
+ type: 'boolean',
2921
+ read: true,
2922
+ write: false,
2923
+ native: {
2924
+ valueTrue: 'active',
2925
+ valueFalse: 'inactive',
2926
+ },
2927
+ };
2928
+ // The dSS name, by which a start whose read failed finds the object again
2929
+ return { ...definition, native: { ...definition.native, dssStateName: state.name } };
2930
+ }
2931
+ /**
2932
+ * True when the DSS really regulates the temperature of this zone.
2933
+ *
2934
+ * apartment/getTemperatureControlStatus answers for EVERY zone, but a zone without a
2935
+ * controller only carries `ControlMode: 0` and no values at all. Creating the control
2936
+ * objects for those would only produce states that stay empty forever.
2937
+ *
2938
+ * @param [status] per zone entry of apartment/getTemperatureControlStatus
2939
+ */
2940
+ hasTemperatureControl(status) {
2941
+ return !!status && typeof status.ControlMode === 'number' && status.ControlMode > 0;
2942
+ }
2943
+ /**
2944
+ * Creates the room temperature control of one zone.
2945
+ *
2946
+ * The operation mode itself is switched through the scenes of group 48, which already
2947
+ * exist. What was missing so far is the state of the controller (which zones are
2948
+ * regulated at all, who owns the set point) and the configured set point per mode.
2949
+ *
2950
+ * The set points are read with zone/getTemperatureControlValues. Not every DSS
2951
+ * firmware knows that endpoint, so the states are only created when the DSS really
2952
+ * answered - an unsupported firmware simply gets no set point objects instead of a
2953
+ * folder full of dead states.
2954
+ *
2955
+ * @param zoneBaseId object path of the zone
2956
+ * @param zone zone as reported by the DSS
2957
+ * @param status per zone entry of apartment/getTemperatureControlStatus
2958
+ */
2959
+ createTemperatureControl(zoneBaseId, zone, status, callback) {
2960
+ const baseId = `${zoneBaseId}.temperatureControl`;
2961
+ this.addFolderObject(baseId, `${zone.name || `Zone ${zone.id}`} Temperature Control`, 'channel');
2962
+ this.addStateObject(`${baseId}.ControlMode`, {
2963
+ name: 'Temperature Control Mode',
2964
+ type: 'number',
2965
+ role: 'value',
2966
+ states: dssConstants.temperatureControlModes,
2967
+ read: true,
2968
+ write: false,
2969
+ });
2970
+ this.initialObjectValues[`${baseId}.ControlMode`] = status.ControlMode;
2971
+ this.addStateObject(`${baseId}.ControlState`, {
2972
+ name: 'Temperature Control State',
2973
+ type: 'number',
2974
+ role: 'value',
2975
+ states: dssConstants.temperatureControlStates,
2976
+ read: true,
2977
+ write: false,
2978
+ });
2979
+ if (status.ControlState !== undefined) {
2980
+ this.initialObjectValues[`${baseId}.ControlState`] = status.ControlState;
2981
+ }
2982
+ // Mirrors the scenes of group 48 under a name that is findable. Registered in the
2983
+ // state map so the event handling keeps it in sync with every scene call.
2984
+ this.addStateObject(`${baseId}.OperationMode`, `${zone.id}.48.operationMode`, {
2985
+ name: 'Temperature Operation Mode',
2986
+ type: 'number',
2987
+ role: 'level',
2988
+ states: dssConstants.temperatureControlScenes,
2989
+ read: true,
2990
+ write: true,
2991
+ }, value => {
2992
+ if (dssConstants.temperatureControlScenes[value] === undefined) {
2993
+ this.adapter.log.warn(`Invalid operation mode ${value} for ${baseId}.OperationMode`);
2994
+ return;
2995
+ }
2996
+ this.dssQueue.pushQueryQueue('zone', {
2997
+ dssClass: 'zone',
2998
+ dssFunction: 'callScene',
2999
+ params: { id: zone.id, groupID: 48, sceneNumber: value },
3000
+ }, 'high', (err, res) => {
3001
+ if (err || (res && !res.ok)) {
3002
+ this.logQueueError(`Error while setting the operation mode of zone ${zone.id}: ${err || JSON.stringify(res)}`, err);
3003
+ }
3004
+ });
3005
+ });
3006
+ if (status.OperationMode !== undefined) {
3007
+ this.initialObjectValues[`${baseId}.OperationMode`] = status.OperationMode;
3008
+ }
3009
+ this.dssQueue.pushQueryQueue('zone', {
3010
+ dssClass: 'zone',
3011
+ dssFunction: 'getTemperatureControlValues',
3012
+ params: { id: zone.id },
3013
+ },
3014
+ // Every other read of the structure build-up runs 'high'. This one sat on
3015
+ // 'medium' and therefore on the 10s grid: measured on a real installation the
3016
+ // five zone reads took 50.6s of the 149.7s in which the adapter is deaf to
3017
+ // events, each of them answered in 110ms on an otherwise empty queue.
3018
+ 'high', (err, res) => {
3019
+ const values = !err && res && res.ok && res.result ? res.result : null;
3020
+ if (!values) {
3021
+ this.adapter.log.debug(`No temperature set points for zone ${zone.id}: ${err || JSON.stringify(res)}`);
3022
+ return void (callback && callback());
3023
+ }
3024
+ // The field names are the operation modes of the DSS (Off, Comfort, Economy,
3025
+ // ...). They are taken as they come instead of being hard coded, so a
3026
+ // firmware with different or additional modes works as well.
3027
+ const modes = Object.keys(values).filter(name => typeof values[name] === 'number');
3028
+ if (modes.length) {
3029
+ this.addFolderObject(`${baseId}.setpoints`, 'Temperature Set Points', 'channel');
3030
+ }
3031
+ modes.forEach(mode => {
3032
+ const stateId = `${baseId}.setpoints.${mode}`;
3033
+ this.addStateObject(stateId, {
3034
+ name: `Set Point ${mode}`,
3035
+ type: 'number',
3036
+ role: 'level.temperature',
3037
+ unit: '°C',
3038
+ read: true,
3039
+ write: true,
3040
+ }, value => {
3041
+ this.dssQueue.pushQueryQueue('zone', {
3042
+ dssClass: 'zone',
3043
+ dssFunction: 'setTemperatureControlValues',
3044
+ params: { id: zone.id, [mode]: value },
3045
+ }, 'high', (setErr, setRes) => {
3046
+ if (setErr || (setRes && !setRes.ok)) {
3047
+ this.logQueueError(`Error while setting the ${mode} set point of zone ${zone.id}: ${setErr || JSON.stringify(setRes)}`, setErr);
3048
+ }
3049
+ });
3050
+ });
3051
+ this.initialObjectValues[stateId] = values[mode];
3052
+ });
3053
+ callback && callback();
3054
+ });
3055
+ }
3056
+ processGroup(groupBaseId, zoneId, group, callback) {
3057
+ if (!group.isPresent || !group.isValid) {
3058
+ return void (callback && setImmediate(callback, null));
3059
+ }
3060
+ // Request via the queue to not flood the DSS with a request burst on startup
3061
+ this.dssQueue.pushQueryQueue('zone', {
3062
+ dssClass: 'zone',
3063
+ dssFunction: 'getReachableScenes',
3064
+ params: { id: zoneId, groupID: group.id },
3065
+ }, 'high', (err, reachableScenes) => {
3066
+ if (err) {
3067
+ // Do not fail the whole initialization because of one broken group - just skip it
3068
+ this.logQueueError(`Err getReachableScenes for zone ${zoneId} group ${group.id} - skip group: ${err.message || JSON.stringify(err)}`, err);
3069
+ return void (callback && callback(null));
3070
+ }
3071
+ this.adapter.log.debug(`getReachableScenes ${zoneId}-${group.id}: ${JSON.stringify(reachableScenes)}`);
3072
+ this.addFolderObject(groupBaseId, group.name || `Group ${group.id}`);
3073
+ this.addFolderObject(`${groupBaseId}.scenes`, `${group.name || `Group ${group.id}`} Scenes`, 'channel');
3074
+ const sceneList = {};
3075
+ const reachableResult = (reachableScenes && reachableScenes.result) || {};
3076
+ const scenesToProcess = reachableResult.reachableScenes || [];
3077
+ this.basicRoomScenes.forEach(sceneId => scenesToProcess.push(sceneId)); // enhance
3078
+ if (scenesToProcess.length) {
3079
+ const userNames = this.convertObject(reachableResult.userSceneNames, 'sceneNr');
3080
+ if (scenesToProcess.includes(0)) {
3081
+ scenesToProcess.push(40); // Add Auto-Off if we support off
3082
+ }
3083
+ scenesToProcess.forEach((sceneId) => {
3084
+ let sceneStateId;
3085
+ let sceneName;
3086
+ if (zoneId === 0) {
3087
+ if (!dssConstants.apartmentScenes[sceneId] && !dssConstants.zoneSceneCommands[sceneId]) {
3088
+ this.adapter.log.warn(`IGNORE INVALID SCENEID ${sceneId}`);
3089
+ return;
3090
+ }
3091
+ sceneStateId = `${groupBaseId}.scenes.${this.convertSceneName(dssConstants.apartmentScenes[sceneId] || dssConstants.zoneSceneCommands[sceneId])}`;
3092
+ sceneName =
3093
+ dssConstants.apartmentScenes[sceneId] || dssConstants.zoneSceneCommands[sceneId];
3094
+ }
3095
+ else {
3096
+ if (!dssConstants.zoneSceneCommands[sceneId]) {
3097
+ this.adapter.log.warn(`IGNORE INVALID SCENEID ${sceneId}`);
3098
+ return;
3099
+ }
3100
+ sceneStateId = `${groupBaseId}.scenes.${this.convertSceneName(dssConstants.zoneSceneCommands[sceneId])}`;
3101
+ sceneName =
3102
+ (userNames[sceneId] && userNames[sceneId].sceneName) ||
3103
+ // Die neue API kennt auch Namen, die die klassische
3104
+ // getReachableScenes-Antwort nicht liefert
3105
+ this.scenarioNames[`${zoneId}.${group.id}.${sceneId}`] ||
3106
+ dssConstants.zoneSceneCommands[sceneId];
3107
+ }
3108
+ sceneList[sceneId] = sceneName;
3109
+ this.addStateObject(sceneStateId, `${zoneId}.${group.id}.scenes.${sceneId}`, {
3110
+ name: `Group ${group.id} ${sceneName}`,
3111
+ type: 'boolean',
3112
+ role: 'switch',
3113
+ }, value => {
3114
+ value = DSSStructure.toBoolean(value);
3115
+ this.dssQueue.pushQueryQueue('zone', {
3116
+ dssClass: 'zone',
3117
+ dssFunction: value ? 'callScene' : 'undoScene',
3118
+ params: {
3119
+ sceneNumber: sceneId,
3120
+ groupID: group.id,
3121
+ id: zoneId,
3122
+ },
3123
+ }, 'high', (err, res) => {
3124
+ if (err || (res && !res.ok)) {
3125
+ this.logQueueError(`Error while ${value ? 'callScene' : 'undoScene'} for group: ${err || JSON.stringify(res)}`, err);
3126
+ }
3127
+ });
3128
+ });
3129
+ this.initialObjectValues[sceneStateId] = false;
3130
+ });
3131
+ for (let sceneId = 67; sceneId <= 70; sceneId++) {
3132
+ const sceneStateId = `${groupBaseId}.scenes.${this.convertSceneName(dssConstants.apartmentScenes[sceneId])}`;
3133
+ sceneList[sceneId] = dssConstants.apartmentScenes[sceneId];
3134
+ this.addStateObject(sceneStateId, `${zoneId}.${group.id}.scenes.${sceneId}`, {
3135
+ name: `Group ${group.id} ${dssConstants.apartmentScenes[sceneId]}`,
3136
+ type: 'boolean',
3137
+ role: 'switch',
3138
+ }, value => {
3139
+ value = DSSStructure.toBoolean(value);
3140
+ this.dssQueue.pushQueryQueue('zone', {
3141
+ dssClass: 'zone',
3142
+ dssFunction: value ? 'callScene' : 'undoScene',
3143
+ params: {
3144
+ id: zoneId,
3145
+ groupID: group.id,
3146
+ sceneNumber: sceneId,
3147
+ },
3148
+ }, 'high', (err, res) => {
3149
+ if (err || (res && !res.ok)) {
3150
+ this.logQueueError(`Error while ${value ? 'callScene' : 'undoScene'} for group: ${err || JSON.stringify(res)}`, err);
3151
+ }
3152
+ });
3153
+ });
3154
+ this.initialObjectValues[sceneStateId] = false;
3155
+ }
3156
+ }
3157
+ if (group.id === 48 && zoneId !== 0) {
3158
+ Object.keys(dssConstants.temperatureControlScenes).forEach(sceneId => {
3159
+ const sceneStateId = `${groupBaseId}.scenes.${this.convertSceneName(dssConstants.temperatureControlScenes[Number(sceneId)])}`;
3160
+ const sceneName = dssConstants.temperatureControlScenes[Number(sceneId)];
3161
+ sceneList[sceneId] = sceneName;
3162
+ this.addStateObject(sceneStateId, `${zoneId}.${group.id}.scenes.${sceneId}`, {
3163
+ name: `Group ${group.id} ${sceneName}`,
3164
+ type: 'boolean',
3165
+ role: 'switch',
3166
+ }, value => {
3167
+ value = DSSStructure.toBoolean(value);
3168
+ this.dssQueue.pushQueryQueue('zone', {
3169
+ dssClass: 'zone',
3170
+ dssFunction: value ? 'callScene' : 'undoScene',
3171
+ params: {
3172
+ sceneNumber: sceneId,
3173
+ groupID: group.id,
3174
+ id: zoneId,
3175
+ },
3176
+ }, 'high', (err, res) => {
3177
+ if (err || (res && !res.ok)) {
3178
+ this.logQueueError(`Error while ${value ? 'callScene' : 'undoScene'} for group: ${err || JSON.stringify(res)}`, err);
3179
+ }
3180
+ });
3181
+ });
3182
+ this.initialObjectValues[sceneStateId] = false;
3183
+ });
3184
+ }
3185
+ if ((group.id === 10 || group.id === 64) && zoneId !== 0) {
3186
+ Object.keys(dssConstants.ventilationControlScenes).forEach(sceneId => {
3187
+ const sceneStateId = `${groupBaseId}.scenes.${this.convertSceneName(dssConstants.ventilationControlScenes[Number(sceneId)])}`;
3188
+ const sceneName = dssConstants.ventilationControlScenes[Number(sceneId)];
3189
+ sceneList[sceneId] = sceneName;
3190
+ this.addStateObject(sceneStateId, `${zoneId}.${group.id}.scenes.${sceneId}`, {
3191
+ name: `Group ${group.id} ${sceneName}`,
3192
+ type: 'boolean',
3193
+ role: 'switch',
3194
+ }, value => {
3195
+ value = DSSStructure.toBoolean(value);
3196
+ this.dssQueue.pushQueryQueue('zone', {
3197
+ dssClass: 'zone',
3198
+ dssFunction: value ? 'callScene' : 'undoScene',
3199
+ params: {
3200
+ sceneNumber: sceneId,
3201
+ groupID: group.id,
3202
+ id: zoneId,
3203
+ },
3204
+ }, 'high', (err, res) => {
3205
+ if (err || (res && !res.ok)) {
3206
+ this.logQueueError(`Error while ${value ? 'callScene' : 'undoScene'} for group: ${err || JSON.stringify(res)}`, err);
3207
+ }
3208
+ });
3209
+ });
3210
+ this.initialObjectValues[sceneStateId] = false;
3211
+ });
3212
+ }
3213
+ if (Object.keys(sceneList).length) {
3214
+ this.addStateObject(`${groupBaseId}.scenes.sceneId`, {
3215
+ name: 'Group Scene ID',
3216
+ type: 'number',
3217
+ role: 'value',
3218
+ states: sceneList,
3219
+ }, value => {
3220
+ if (!sceneList[value]) {
3221
+ this.adapter.log.warn(`Invalid Scene ID ${value} for ${groupBaseId}.scenes.sceneId`);
3222
+ return;
3223
+ }
3224
+ this.dssQueue.pushQueryQueue('zone', {
3225
+ dssClass: 'zone',
3226
+ dssFunction: 'callScene',
3227
+ params: {
3228
+ sceneNumber: value,
3229
+ groupID: group.id,
3230
+ id: zoneId,
3231
+ },
3232
+ }, 'high', (err, res) => {
3233
+ if (err || (res && !res.ok)) {
3234
+ this.logQueueError(`Error while callScene for ${groupBaseId}.scenes.sceneId: ${err || JSON.stringify(res)}`, err);
3235
+ }
3236
+ });
3237
+ });
3238
+ this.dssQueue.pushQueryQueue('zone', {
3239
+ dssClass: 'zone',
3240
+ dssFunction: 'getLastCalledScene',
3241
+ params: {
3242
+ id: zoneId,
3243
+ groupID: group.id,
3244
+ },
3245
+ }, 'high', (err, res) => {
3246
+ if (err || (res && !res.ok) || !res.result || res.result.scene === undefined) {
3247
+ this.logQueueError(`Error while getLastCalledScene for group ${zoneId}.${group.id}: ${err || JSON.stringify(res)}`, err);
3248
+ }
3249
+ else {
3250
+ this.initialObjectValues[`${groupBaseId}.scenes.sceneId`] = res.result.scene;
3251
+ this.initialScenes[`${zoneId}.${group.id}`] = res.result.scene;
3252
+ const sceneStateId = this.resolveSceneStateId(`${zoneId}.${group.id}.scenes.${res.result.scene}`, res.result.scene, groupBaseId);
3253
+ if (sceneStateId && this.dssObjects[sceneStateId]) {
3254
+ this.initialObjectValues[sceneStateId] = true;
3255
+ }
3256
+ }
3257
+ callback && callback(null);
3258
+ });
3259
+ }
3260
+ // Two naming schemes end up here:
3261
+ // - `zone.<zone>.group.<group>.<name>` for the groups of a room. The name may
3262
+ // contain dots itself (`status.malfunction` of the ventilation groups), so
3263
+ // everything behind the group is taken and turned into a nested state.
3264
+ // - `cluster.<id>.<name>` for the apartment wide clusters (17, 18, ...). Their
3265
+ // group folders exist, but their states used to have no object at all.
3266
+ const groupStates = this.findStates(`^zone\\.${zoneId}\\.group\\.${group.id}\\.(.+)$`).concat(zoneId === 0 ? this.findStates(`^cluster\\.${group.id}\\.(.+)$`) : []);
3267
+ if (groupStates && groupStates.length) {
3268
+ this.addFolderObject(`${groupBaseId}.states`, `${group.name || `Group ${group.id}`} Scenes`, 'channel');
3269
+ groupStates.forEach(state => {
3270
+ if (!state.matchedName) {
3271
+ return;
3272
+ }
3273
+ const stateId = `${groupBaseId}.states.${state.matchedName}`;
3274
+ // `status.malfunction` becomes a nested state - create the folder in
3275
+ // between so the object tree has no gap
3276
+ if (state.matchedName.includes('.')) {
3277
+ const parts = state.matchedName.split('.');
3278
+ parts.slice(0, -1).forEach((part, idx) => {
3279
+ const folderId = `${groupBaseId}.states.${parts.slice(0, idx + 1).join('.')}`;
3280
+ if (!this.dssObjects[folderId]) {
3281
+ this.addFolderObject(folderId, part, 'channel');
3282
+ }
3283
+ });
3284
+ }
3285
+ this.addStateObject(stateId, state.name, {
3286
+ name: state.matchedName,
3287
+ role: 'indicator',
3288
+ type: 'boolean',
3289
+ read: true,
3290
+ write: false,
3291
+ // Without a mapping the write handler below can only warn -
3292
+ // it was the ONLY branch it ever took, because nothing else
3293
+ // filled this native. The zone path (zoneStateRoleMap) is the
3294
+ // working counterpart and this mirrors it: same vocabulary,
3295
+ // same write: false, and a state the dSS computes itself
3296
+ // still gets no mapping and keeps warning.
3297
+ native: { ...(dssConstants.groupStateRoleMap[state.matchedName] || {}) },
3298
+ }, value => {
3299
+ value = DSSStructure.toBoolean(value);
3300
+ const groupNative = this.dssObjects[stateId] && this.dssObjects[stateId].native;
3301
+ // Without a value mapping the DSS would receive "undefined"
3302
+ if (!groupNative || groupNative.valueTrue === undefined) {
3303
+ this.adapter.log.warn(`Can not write ${stateId}: no value mapping known for this group state`);
3304
+ return;
3305
+ }
3306
+ this.dssQueue.pushQueryQueue('group', {
3307
+ dssClass: 'state',
3308
+ dssFunction: 'set',
3309
+ params: {
3310
+ name: state.name,
3311
+ value: value
3312
+ ? this.dssObjects[stateId].native.valueTrue
3313
+ : this.dssObjects[stateId].native.valueFalse,
3314
+ },
3315
+ }, 'high', (err, res) => {
3316
+ if (err || (res && !res.ok)) {
3317
+ this.logQueueError(`Error while set State for group: ${err || JSON.stringify(res)}`, err);
3318
+ }
3319
+ });
3320
+ });
3321
+ this.initialObjectValues[stateId] = DSSStructure.initialStateValue(state);
3322
+ });
3323
+ }
3324
+ !Object.keys(sceneList).length && callback && callback(null);
3325
+ });
3326
+ }
3327
+ addFolderObject(id, name, type) {
3328
+ const obj = {
3329
+ type: type || 'folder',
3330
+ common: {
3331
+ // Circuits, rooms and devices carry the names of the dSS. One the dSS still
3332
+ // stores with HTML codes is shown with the real characters, see
3333
+ // decodeDssEntities() - the ID is never derived from it
3334
+ name: typeof name === 'string' ? decodeDssEntities(name) : name,
3335
+ },
3336
+ };
3337
+ this.dssObjects[id] = obj;
3338
+ const idLength = id.replace(/[^.]/g, '').length;
3339
+ const spacesStr = ' ';
3340
+ this.adapter.log.debug(`${spacesStr.substr(0, idLength * 2)}CREATE ${obj.type} ${id} WITH ${JSON.stringify(obj)}`);
3341
+ }
3342
+ addStateObject(id, dssId, objData, value, onChange) {
3343
+ if (typeof dssId === 'object') {
3344
+ onChange = value;
3345
+ value = objData;
3346
+ objData = dssId;
3347
+ dssId = null;
3348
+ }
3349
+ if (typeof value === 'function') {
3350
+ onChange = value;
3351
+ value = undefined;
3352
+ }
3353
+ objData = JSON.parse(JSON.stringify(objData));
3354
+ let native = {};
3355
+ if (objData.native) {
3356
+ native = objData.native;
3357
+ delete objData.native;
3358
+ }
3359
+ // Names of user states, scenes and sensors come from the dSS as well
3360
+ if (typeof objData.name === 'string') {
3361
+ objData.name = decodeDssEntities(objData.name);
3362
+ }
3363
+ const obj = {
3364
+ type: 'state',
3365
+ common: objData,
3366
+ native,
3367
+ value,
3368
+ onChange,
3369
+ };
3370
+ this.dssObjects[id] = obj;
3371
+ if (dssId) {
3372
+ this.stateMap[dssId] = id;
3373
+ }
3374
+ const idLength = id.replace(/[^.]/g, '').length;
3375
+ const spacesStr = ' ';
3376
+ this.adapter.log.debug(`${spacesStr.substr(0, idLength * 2)}CREATE state ${id} value = ${value} WITH ${JSON.stringify(obj)}`);
3377
+ }
3378
+ static FALSY_STATE_WORDS = ['', '0', 'false', 'off', 'inactive', 'no', 'disabled', 'closed'];
3379
+ // The word the dSS uses for a state it has no information about. A state without words of
3380
+ // its own counts 1 = active, 2 = inactive, 3 = unknown; one with its own words numbers
3381
+ // those instead (a window handle: 1 = closed, 2 = open, 3 = tilted). So only the word
3382
+ // says "unknown", never the number (dss-mainline src/model/modelconst.h eState,
3383
+ // src/model/state.cpp State::toString()). Neither true nor false, see
3384
+ // Digitalstrom.coerceScalarValue().
3385
+ static UNKNOWN_STATE_WORD = 'unknown';
3386
+ static decodeDssEntities = decodeDssEntities;
3387
+ static wattSecondsToKwh = wattSecondsToKwh;
3388
+ }
3389
+ exports.DSSStructure = DSSStructure;
3390
+ //# sourceMappingURL=dssStructure.js.map