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.
- package/LICENSE +2 -1
- package/README.md +806 -35
- package/admin/assets/index.js +682 -0
- package/admin/index.html +45 -0
- package/build/lib/activityCounter.js +82 -0
- package/build/lib/activityCounter.js.map +1 -0
- package/build/lib/configUtils.js +125 -0
- package/build/lib/configUtils.js.map +1 -0
- package/build/lib/constants.js +1285 -0
- package/build/lib/constants.js.map +1 -0
- package/build/lib/dss.js +877 -0
- package/build/lib/dss.js.map +1 -0
- package/build/lib/dssQueue.js +517 -0
- package/build/lib/dssQueue.js.map +1 -0
- package/build/lib/dssSmartHome.js +769 -0
- package/build/lib/dssSmartHome.js.map +1 -0
- package/build/lib/dssSmartHomeSync.js +601 -0
- package/build/lib/dssSmartHomeSync.js.map +1 -0
- package/build/lib/dssStructure.js +3390 -0
- package/build/lib/dssStructure.js.map +1 -0
- package/build/lib/websocket.js +386 -0
- package/build/lib/websocket.js.map +1 -0
- package/build/main.js +2203 -0
- package/build/main.js.map +1 -0
- package/io-package.json +262 -266
- package/package.json +67 -36
- package/admin/admin.d.ts +0 -1
- package/admin/index_m.html +0 -201
- package/admin/style.css +0 -10
- package/admin/words.js +0 -20
- package/img/dss-apartment.png +0 -0
- package/img/dss-devices.png +0 -0
- package/lib/adapter-config.d.ts +0 -16
- package/lib/constants.js +0 -1202
- package/lib/dss.js +0 -193
- package/lib/dssQueue.js +0 -268
- package/lib/dssStructure.js +0 -1662
- package/lib/tools.js +0 -91
- package/main.js +0 -713
package/build/main.js
ADDED
|
@@ -0,0 +1,2203 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/*
|
|
3
|
+
* Digitalstrom ioBroker Adapter
|
|
4
|
+
*/
|
|
5
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
6
|
+
if (k2 === undefined) k2 = k;
|
|
7
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
8
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
9
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
10
|
+
}
|
|
11
|
+
Object.defineProperty(o, k2, desc);
|
|
12
|
+
}) : (function(o, m, k, k2) {
|
|
13
|
+
if (k2 === undefined) k2 = k;
|
|
14
|
+
o[k2] = m[k];
|
|
15
|
+
}));
|
|
16
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
17
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
18
|
+
}) : function(o, v) {
|
|
19
|
+
o["default"] = v;
|
|
20
|
+
});
|
|
21
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
22
|
+
var ownKeys = function(o) {
|
|
23
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
24
|
+
var ar = [];
|
|
25
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
26
|
+
return ar;
|
|
27
|
+
};
|
|
28
|
+
return ownKeys(o);
|
|
29
|
+
};
|
|
30
|
+
return function (mod) {
|
|
31
|
+
if (mod && mod.__esModule) return mod;
|
|
32
|
+
var result = {};
|
|
33
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
34
|
+
__setModuleDefault(result, mod);
|
|
35
|
+
return result;
|
|
36
|
+
};
|
|
37
|
+
})();
|
|
38
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
+
/*
|
|
40
|
+
Rule 5 When applications send a scene command to a set of digitalSTROM-Devices with more than one target device they have to use scene calls directed to a group, splitting into multiple calls to single devices has to be avoided due to latency and statemachine consistency issues.
|
|
41
|
+
|
|
42
|
+
Rule 8 Application processes that do automatic cyclic reads or writes of device parameters are subject to a request limit: at maximum one request per minute and circuit is allowed.
|
|
43
|
+
|
|
44
|
+
Rule 9 Application processes that do automatic cyclic reads of measured values are subject to a request limit: at maximum one request per minute and circuit is allowed.
|
|
45
|
+
|
|
46
|
+
Rule 10 The action command ”Set Output Value” must not be used for other than device configuration purposes.
|
|
47
|
+
|
|
48
|
+
Rule 13 Applications that automatically generate Call Scene action commands (see 6.1.1) must not execute the action commands at a rate faster than one request per second.
|
|
49
|
+
*/
|
|
50
|
+
const node_perf_hooks_1 = require("node:perf_hooks");
|
|
51
|
+
const utils = __importStar(require("@iobroker/adapter-core"));
|
|
52
|
+
const iobroker_tools_1 = require("@apollon/iobroker-tools"); // Get common adapter utils
|
|
53
|
+
const dss_1 = require("./lib/dss");
|
|
54
|
+
const dssQueue_1 = require("./lib/dssQueue");
|
|
55
|
+
const dssStructure_1 = require("./lib/dssStructure");
|
|
56
|
+
const dssSmartHome_1 = require("./lib/dssSmartHome");
|
|
57
|
+
const activityCounter_1 = require("./lib/activityCounter");
|
|
58
|
+
const configUtils = __importStar(require("./lib/configUtils"));
|
|
59
|
+
const dssConstants = __importStar(require("./lib/constants"));
|
|
60
|
+
// Safety valve for the events parked during the startup, not a working limit: the busiest
|
|
61
|
+
// 150 s of a three hour production log carried 88 of them, the whole run 2746. At roughly
|
|
62
|
+
// 300 bytes of payload each this caps the parking at a couple of megabytes even if a start
|
|
63
|
+
// runs all the way into the ten minute watchdog.
|
|
64
|
+
const STARTUP_EVENT_LIMIT = 2000;
|
|
65
|
+
// A momentary scene is released again after this pause. Not on the next turn: a wall
|
|
66
|
+
// switch repeats its Stop, measured three times within 481 ms on one blind while the
|
|
67
|
+
// position never moved. Releasing immediately would turn that ONE press into three
|
|
68
|
+
// rising edges for every rule listening on it. Re-armed on each repeat, so a burst
|
|
69
|
+
// stays a single true -> false, exactly as many edges as the user caused.
|
|
70
|
+
const MOMENTARY_SCENE_RELEASE = 500;
|
|
71
|
+
// A dSS that did not answer at startup is asked again after this pause - the same five
|
|
72
|
+
// minutes the process restart used to wait. Such a dSS is rebooting, being updated or
|
|
73
|
+
// switched off, and asking more often would buy nothing but log lines.
|
|
74
|
+
const DSS_RETRY_DELAY = 5 * 60 * 1000;
|
|
75
|
+
// The objectHelper of `@apollon/iobroker-tools`. The package ships no types, so the part
|
|
76
|
+
// of it this adapter actually uses is written down in lib/apollon-iobroker-tools.d.ts.
|
|
77
|
+
// DSS rules 8/9 (see above) allow at most one cyclic read per minute and circuit.
|
|
78
|
+
// One cycle issues TWO reads per circuit (getConsumption + getEnergyMeterValue), and the
|
|
79
|
+
// timer for the next cycle only starts once they are answered - measured against a real
|
|
80
|
+
// DSS a cycle therefore takes about 20s longer than the configured interval:
|
|
81
|
+
// interval 60s -> cycle ~80s -> 1.53 requests per minute and circuit
|
|
82
|
+
// interval 100s -> cycle ~120s -> 1.00 requests per minute and circuit
|
|
83
|
+
// 100s is the first value that really stays within the rule, so it is the default.
|
|
84
|
+
const DEFAULT_POLL_INTERVAL = 100000;
|
|
85
|
+
// Smaller values stay possible on purpose - they exceed the guideline, which is documented
|
|
86
|
+
// in the README and in the admin dialog. 0 still disables polling completely.
|
|
87
|
+
const MIN_POLL_INTERVAL_SECONDS = 60;
|
|
88
|
+
const MAX_POLL_INTERVAL_SECONDS = 24 * 60 * 60;
|
|
89
|
+
class Digitalstrom extends utils.Adapter {
|
|
90
|
+
/** True when js-controller started this instance in compact mode */
|
|
91
|
+
compactMode;
|
|
92
|
+
objectHelper;
|
|
93
|
+
dss;
|
|
94
|
+
/** Client der neuen API, nur wenn eingeschaltet */
|
|
95
|
+
smartHome;
|
|
96
|
+
dssQueue;
|
|
97
|
+
dssStruct;
|
|
98
|
+
/** Last called scene by "<zone>.<group>" or by dSUID */
|
|
99
|
+
lastScenes;
|
|
100
|
+
unmappedBooleanStates;
|
|
101
|
+
unhandledStateNames;
|
|
102
|
+
unmappedSceneCalls;
|
|
103
|
+
sceneGroupCache;
|
|
104
|
+
momentaryReleases;
|
|
105
|
+
momentaryReleaseDelay;
|
|
106
|
+
pendingEvents;
|
|
107
|
+
pendingEventsDropped;
|
|
108
|
+
pendingModelReady;
|
|
109
|
+
startupEventLimit;
|
|
110
|
+
eventSubscriptionStarted;
|
|
111
|
+
/** undefined while the early subscribe is in flight */
|
|
112
|
+
eventSubscriptionResult;
|
|
113
|
+
eventSubscriptionWaiters;
|
|
114
|
+
dataPollInterval;
|
|
115
|
+
dataPollTimeout;
|
|
116
|
+
restartTimeout;
|
|
117
|
+
startupTimeout;
|
|
118
|
+
dssRetryTimeout;
|
|
119
|
+
dssRetryDelay;
|
|
120
|
+
dssOutage;
|
|
121
|
+
stopping;
|
|
122
|
+
stopped;
|
|
123
|
+
stopCallbacks;
|
|
124
|
+
stopGuardTimeout;
|
|
125
|
+
tokenConnections;
|
|
126
|
+
smartHomeKeyControllers;
|
|
127
|
+
eventHandlersRegistered;
|
|
128
|
+
/** Counts per path what really runs, see countClassicActivity() */
|
|
129
|
+
apiActivity;
|
|
130
|
+
apiActivityTimer;
|
|
131
|
+
lastApiActivityPayload;
|
|
132
|
+
/**
|
|
133
|
+
* Returns an objectHelper that belongs to this adapter instance only.
|
|
134
|
+
*
|
|
135
|
+
* The helper of `@apollon/iobroker-tools` keeps its adapter reference, the object queue,
|
|
136
|
+
* the known objects and the state change callbacks in module scope. In compact mode two
|
|
137
|
+
* instances of this adapter share one process, so the instance initialized last would
|
|
138
|
+
* receive the object and state writes of the other one (verified, see testObjectHelper).
|
|
139
|
+
* Loading a private copy of the module per instance keeps them isolated without
|
|
140
|
+
* reimplementing the helper.
|
|
141
|
+
*
|
|
142
|
+
* @param [logger] adapter logger, used only if the private copy is not possible
|
|
143
|
+
* @returns objectHelper instance
|
|
144
|
+
*/
|
|
145
|
+
static createObjectHelper(logger) {
|
|
146
|
+
try {
|
|
147
|
+
const modulePath = require.resolve('@apollon/iobroker-tools/lib/objectHelper');
|
|
148
|
+
const cached = require.cache[modulePath];
|
|
149
|
+
delete require.cache[modulePath];
|
|
150
|
+
try {
|
|
151
|
+
return require('@apollon/iobroker-tools/lib/objectHelper');
|
|
152
|
+
}
|
|
153
|
+
finally {
|
|
154
|
+
// Restore the module cache so other consumers keep their own copy
|
|
155
|
+
if (cached) {
|
|
156
|
+
require.cache[modulePath] = cached;
|
|
157
|
+
}
|
|
158
|
+
else {
|
|
159
|
+
delete require.cache[modulePath];
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
catch (err) {
|
|
164
|
+
// Should not happen, but a shared helper is still better than no adapter at all
|
|
165
|
+
logger &&
|
|
166
|
+
logger.warn &&
|
|
167
|
+
logger.warn(`Could not create a private objectHelper (${configUtils.errorMessage(err)}). Running a second instance of this adapter in the same compact process is not safe.`);
|
|
168
|
+
return iobroker_tools_1.objectHelper;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* @param [options] options of js-controller, {compact: true} for a compact instance
|
|
173
|
+
*/
|
|
174
|
+
constructor(options) {
|
|
175
|
+
super({
|
|
176
|
+
...options,
|
|
177
|
+
name: 'digitalstrom',
|
|
178
|
+
});
|
|
179
|
+
// The host starts a compact instance with {compact: true}. js-controller keeps its
|
|
180
|
+
// own flag for that private, and restartAdapter() has to know it: in compact mode
|
|
181
|
+
// the host logs the reason of a stop as a warning.
|
|
182
|
+
this.compactMode = !!(options && options.compact);
|
|
183
|
+
this.on('ready', this.onReady.bind(this));
|
|
184
|
+
this.on('objectChange', this.onObjectChange.bind(this));
|
|
185
|
+
this.on('stateChange', this.onStateChange.bind(this));
|
|
186
|
+
this.on('message', this.onMessage.bind(this));
|
|
187
|
+
this.on('unload', this.onUnload.bind(this));
|
|
188
|
+
this.objectHelper = Digitalstrom.createObjectHelper(this.log);
|
|
189
|
+
this.objectHelper.init(this);
|
|
190
|
+
// undefined (not null) so the type matches the connected flag of the base class.
|
|
191
|
+
// The first setConnected() call writes the state in either case.
|
|
192
|
+
this.connected = undefined;
|
|
193
|
+
this.dss = null;
|
|
194
|
+
// Client der neuen API, nur wenn eingeschaltet
|
|
195
|
+
this.smartHome = null;
|
|
196
|
+
this.dssQueue = null;
|
|
197
|
+
this.dssStruct = null;
|
|
198
|
+
this.lastScenes = {};
|
|
199
|
+
// Boolean states whose declared valueTrue/valueFalse did not match what the dSS
|
|
200
|
+
// sent. Each one is reported once per run, see coerceScalarValue().
|
|
201
|
+
this.unmappedBooleanStates = new Set();
|
|
202
|
+
// dSS state names that have no object here. Each one is named once per run at info,
|
|
203
|
+
// see handleStateChange in registerEventHandlers().
|
|
204
|
+
this.unhandledStateNames = new Set();
|
|
205
|
+
// Scene calls that found no scene state. Each one is named once per run at info,
|
|
206
|
+
// see logUnmappedSceneCall().
|
|
207
|
+
this.unmappedSceneCalls = new Set();
|
|
208
|
+
// "<zone>.<group>" of every group that has scene states, see logUnmappedSceneCall()
|
|
209
|
+
this.sceneGroupCache = null;
|
|
210
|
+
// Scene states waiting to be released again, by state id - see handleScene()
|
|
211
|
+
this.momentaryReleases = new Map();
|
|
212
|
+
// Overridable in tests so a release does not cost half a second there
|
|
213
|
+
this.momentaryReleaseDelay = MOMENTARY_SCENE_RELEASE;
|
|
214
|
+
// Events that arrived before the objects existed, in arrival order. null means the
|
|
215
|
+
// live path, an array means the startup is still building - see replayStartupEvents()
|
|
216
|
+
this.pendingEvents = null;
|
|
217
|
+
this.pendingEventsDropped = 0;
|
|
218
|
+
// A model_ready that arrived while the objects were being created - acted on once
|
|
219
|
+
// the startup is through, see replayStartupEvents()
|
|
220
|
+
this.pendingModelReady = false;
|
|
221
|
+
// Overridable in tests so an overflow does not need thousands of events
|
|
222
|
+
this.startupEventLimit = STARTUP_EVENT_LIMIT;
|
|
223
|
+
// Set SYNCHRONOUSLY when the subscribe goes out, not when it comes back: the second
|
|
224
|
+
// attempt is decided while the first is still in flight
|
|
225
|
+
this.eventSubscriptionStarted = false;
|
|
226
|
+
// undefined while the early subscribe is in flight
|
|
227
|
+
this.eventSubscriptionResult = undefined;
|
|
228
|
+
this.eventSubscriptionWaiters = [];
|
|
229
|
+
this.dataPollInterval = 60000;
|
|
230
|
+
this.dataPollTimeout = null;
|
|
231
|
+
this.restartTimeout = null;
|
|
232
|
+
this.startupTimeout = null;
|
|
233
|
+
// Next check of a dSS that did not answer at startup, see waitForDss()
|
|
234
|
+
this.dssRetryTimeout = null;
|
|
235
|
+
// Overridable in tests so a retry does not take five minutes
|
|
236
|
+
this.dssRetryDelay = DSS_RETRY_DELAY;
|
|
237
|
+
// The outage waitForDss() is riding out: since when (performance.now(), a clock NTP
|
|
238
|
+
// does not set), how many checks failed and which errors were already reported. null
|
|
239
|
+
// as long as the dSS answers.
|
|
240
|
+
this.dssOutage = null;
|
|
241
|
+
this.stopping = false;
|
|
242
|
+
this.stopped = false;
|
|
243
|
+
this.stopCallbacks = [];
|
|
244
|
+
// Overridable in tests so the unsubscribe guard does not take four seconds
|
|
245
|
+
this.stopGuardTimeout = undefined;
|
|
246
|
+
// DSS clients created by the App-Token dialog. They are not part of the normal
|
|
247
|
+
// adapter lifecycle, so they have to be tracked to be closable on unload.
|
|
248
|
+
this.tokenConnections = new Set();
|
|
249
|
+
// Smart Home key creation also lives outside the normal client lifecycle. Abort every
|
|
250
|
+
// in-flight flow on unload so it cannot create a late key or answer a closed dialog.
|
|
251
|
+
this.smartHomeKeyControllers = new Set();
|
|
252
|
+
// Guards against registering the event handlers more than once
|
|
253
|
+
this.eventHandlersRegistered = false;
|
|
254
|
+
}
|
|
255
|
+
/**
|
|
256
|
+
* True as soon as the unload has started.
|
|
257
|
+
*
|
|
258
|
+
* Every asynchronous startup callback has to check this before it creates timers,
|
|
259
|
+
* requests, subscriptions or state subscriptions. Otherwise an answer that arrives
|
|
260
|
+
* during or after the unload would revive an already stopped adapter.
|
|
261
|
+
*
|
|
262
|
+
* @returns true if the adapter is stopping or already stopped
|
|
263
|
+
*/
|
|
264
|
+
isStopping() {
|
|
265
|
+
return this.stopping || this.stopped;
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Is called when databases are connected and adapter received configuration.
|
|
269
|
+
*/
|
|
270
|
+
async onReady() {
|
|
271
|
+
await this.migratePlainTextSecrets();
|
|
272
|
+
this.main();
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Up to 2.3.0 the App-Token was stored in plain text, because io-package.json did not list
|
|
276
|
+
* it in `encryptedNative`. Now it does, so js-controller "decrypts" such a plain value on
|
|
277
|
+
* start and hands over garbage - every installation updated from 2.3.0 would lose its login.
|
|
278
|
+
*
|
|
279
|
+
* If the value from js-controller is no token but the raw stored value is one, the raw
|
|
280
|
+
* value is the plain text token of an older version: it is used for this run and written
|
|
281
|
+
* back encrypted. An encrypted value never looks like a hex string, so a correctly stored
|
|
282
|
+
* token is never touched. Writing the instance object makes js-controller restart the
|
|
283
|
+
* instance, which then reads the encrypted value.
|
|
284
|
+
*
|
|
285
|
+
* @returns true if a value was migrated
|
|
286
|
+
*/
|
|
287
|
+
async migratePlainTextSecrets() {
|
|
288
|
+
const fields = ['appToken', 'smartHomeApiKey'].filter(name => this.config[name] && !Digitalstrom.looksLikeAppToken(this.config[name]));
|
|
289
|
+
if (!fields.length) {
|
|
290
|
+
return false;
|
|
291
|
+
}
|
|
292
|
+
const id = `system.adapter.${this.namespace}`;
|
|
293
|
+
try {
|
|
294
|
+
const obj = await this.getForeignObjectAsync(id);
|
|
295
|
+
const native = {};
|
|
296
|
+
fields.forEach(name => {
|
|
297
|
+
const raw = obj && obj.native ? obj.native[name] : undefined;
|
|
298
|
+
if (typeof raw === 'string' && Digitalstrom.looksLikeAppToken(raw)) {
|
|
299
|
+
this.config[name] = raw.trim();
|
|
300
|
+
native[name] = this.encrypt(raw.trim());
|
|
301
|
+
}
|
|
302
|
+
});
|
|
303
|
+
const migrated = Object.keys(native);
|
|
304
|
+
if (!migrated.length) {
|
|
305
|
+
return false;
|
|
306
|
+
}
|
|
307
|
+
this.log.info(`Storing the ${migrated.join(' and ')} of an older adapter version encrypted now. ` +
|
|
308
|
+
'The instance restarts once for that.');
|
|
309
|
+
await this.extendForeignObjectAsync(id, { native });
|
|
310
|
+
return true;
|
|
311
|
+
}
|
|
312
|
+
catch (err) {
|
|
313
|
+
this.log.warn(`Could not migrate the stored credentials to encrypted storage: ${configUtils.errorMessage(err)}`);
|
|
314
|
+
return false;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Is called when adapter shuts down - callback has to be called under any circumstances!
|
|
319
|
+
*
|
|
320
|
+
* @param callback tells js-controller that the unload is done
|
|
321
|
+
*/
|
|
322
|
+
onUnload(callback) {
|
|
323
|
+
try {
|
|
324
|
+
this.stopAdapter(callback);
|
|
325
|
+
}
|
|
326
|
+
catch {
|
|
327
|
+
callback();
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* Is called if a subscribed object changes
|
|
332
|
+
*
|
|
333
|
+
* @param id ID of the object
|
|
334
|
+
* @param obj the object, null or undefined if it was deleted
|
|
335
|
+
*/
|
|
336
|
+
onObjectChange(id, obj) {
|
|
337
|
+
if (obj) {
|
|
338
|
+
// The object was changed
|
|
339
|
+
this.log.debug(`object ${id} changed: ${JSON.stringify(obj)}`);
|
|
340
|
+
}
|
|
341
|
+
else {
|
|
342
|
+
// The object was deleted
|
|
343
|
+
this.log.debug(`object ${id} deleted`);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
/**
|
|
347
|
+
* Is called if a subscribed state changes
|
|
348
|
+
*
|
|
349
|
+
* @param id ID of the state
|
|
350
|
+
* @param state the state, null or undefined if it was deleted
|
|
351
|
+
*/
|
|
352
|
+
onStateChange(id, state) {
|
|
353
|
+
if (this.isStopping()) {
|
|
354
|
+
// A control command during the unload would push a new queue entry after the
|
|
355
|
+
// queues were already cleared and the DSS client is about to be closed
|
|
356
|
+
this.log.debug(`Ignoring state change for ${id} - the adapter is stopping`);
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
if (state) {
|
|
360
|
+
// The state was changed. A command (ack = false) is logged at debug. The
|
|
361
|
+
// confirmations are mostly this adapter's own writes - half of a debug log, one
|
|
362
|
+
// line per sensor value and every 30 s for info.apiActivity - and go to silly.
|
|
363
|
+
if (state.ack) {
|
|
364
|
+
this.log.silly(`state ${id} changed: ${state.val} (ack = true)`);
|
|
365
|
+
}
|
|
366
|
+
else {
|
|
367
|
+
this.log.debug(`state ${id} changed: ${state.val} (ack = false)`);
|
|
368
|
+
}
|
|
369
|
+
if (this.dssStruct && typeof this.dssStruct.notePublishedValue === 'function') {
|
|
370
|
+
// What is in the state now, no matter who wrote it and whether it was
|
|
371
|
+
// acknowledged. Tracking foreign writes here is what keeps the
|
|
372
|
+
// reconciliation able to correct a value another adapter put there -
|
|
373
|
+
// without it the skipped re-assert would leave it standing forever.
|
|
374
|
+
// Deliberately NOT limited to acknowledged writes: an unacknowledged one
|
|
375
|
+
// on a read-only state is a value nobody will confirm, and it is exactly
|
|
376
|
+
// the case the reconciliation has to notice.
|
|
377
|
+
// The id arrives with the namespace, the structure keeps its ids without it -
|
|
378
|
+
// under the full id the value was stored next to the tracked one and never
|
|
379
|
+
// compared, so a foreign write on a polled state was never corrected.
|
|
380
|
+
const prefix = `${this.namespace}.`;
|
|
381
|
+
const ownId = this.namespace && id.startsWith(prefix) ? id.slice(prefix.length) : id;
|
|
382
|
+
this.dssStruct.notePublishedValue(ownId, state.val);
|
|
383
|
+
}
|
|
384
|
+
if (!state.ack && state.val === null) {
|
|
385
|
+
// null is "no value" - what this adapter writes for a state the dSS reports
|
|
386
|
+
// as unknown. There is nothing to send for it, and objectHelper would turn
|
|
387
|
+
// it into false for a boolean state (!!null) and hand that to the write
|
|
388
|
+
// handler, which sends the false word of the state ("inactive", "absent",
|
|
389
|
+
// ...) to the dSS - a command nobody gave. It has to be stopped here: by
|
|
390
|
+
// the time a write handler runs, the null is already gone.
|
|
391
|
+
this.log.debug(`Ignoring null for ${id} - there is no value to send to the DSS`);
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
394
|
+
this.objectHelper.handleStateChange(id, state);
|
|
395
|
+
}
|
|
396
|
+
else {
|
|
397
|
+
// The state was deleted
|
|
398
|
+
this.log.debug(`state ${id} deleted`);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* Some message was sent to this instance over message box. Used by email, pushover, text2speech, ...
|
|
403
|
+
* Using this method requires "common.message" property to be set to true in io-package.json
|
|
404
|
+
*
|
|
405
|
+
* @param obj the message
|
|
406
|
+
*/
|
|
407
|
+
onMessage(obj) {
|
|
408
|
+
if (typeof obj === 'object' && obj.message) {
|
|
409
|
+
if (obj.command === 'createSmartHomeKey') {
|
|
410
|
+
if (!obj.callback) {
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
413
|
+
if (this.isStopping()) {
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
const messageToken = typeof obj.message.appToken === 'string' ? obj.message.appToken.trim() : '';
|
|
417
|
+
const appToken = messageToken || this.config.appToken;
|
|
418
|
+
if (!appToken) {
|
|
419
|
+
this.sendTo(obj.from, obj.command, { error: 'Please create or enter the App-Token first, the API key is derived from it.' }, obj.callback);
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
// Der vorhandene App-Token reicht: er wird zur Session und die erzeugt den
|
|
423
|
+
// Bearer-Key. Der Benutzer muss also kein Passwort erneut eingeben.
|
|
424
|
+
this.log.info(`Creating a Smart Home API key for host ${obj.message.host || this.config.host}`);
|
|
425
|
+
const controller = new AbortController();
|
|
426
|
+
this.smartHomeKeyControllers.add(controller);
|
|
427
|
+
dssSmartHome_1.DSSSmartHome.createApiKey({
|
|
428
|
+
host: obj.message.host || this.config.host,
|
|
429
|
+
appToken,
|
|
430
|
+
validateCertificate: this.config.validateCertificate,
|
|
431
|
+
name: `ioBroker.digitalstrom.${this.instance}`,
|
|
432
|
+
signal: controller.signal,
|
|
433
|
+
logger: {
|
|
434
|
+
silly: this.log.silly.bind(this),
|
|
435
|
+
debug: this.log.debug.bind(this),
|
|
436
|
+
info: this.log.info.bind(this),
|
|
437
|
+
warn: this.log.warn.bind(this),
|
|
438
|
+
error: this.log.error.bind(this),
|
|
439
|
+
},
|
|
440
|
+
})
|
|
441
|
+
.then(apiKey => {
|
|
442
|
+
if (this.isStopping() || controller.signal.aborted) {
|
|
443
|
+
return;
|
|
444
|
+
}
|
|
445
|
+
this.log.info('Smart Home API key created');
|
|
446
|
+
this.sendTo(obj.from, obj.command, { apiKey, native: { smartHomeApiKey: apiKey } }, obj.callback);
|
|
447
|
+
}, err => {
|
|
448
|
+
if (this.isStopping() || controller.signal.aborted) {
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
this.log.warn(`Could not create the Smart Home API key: ${configUtils.errorMessage(err)}`);
|
|
452
|
+
this.sendTo(obj.from, obj.command, { error: configUtils.errorMessage(err) }, obj.callback);
|
|
453
|
+
})
|
|
454
|
+
.finally(() => this.smartHomeKeyControllers.delete(controller));
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
if (obj.command === 'createAppToken') {
|
|
458
|
+
if (!obj.callback) {
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
if (this.isStopping()) {
|
|
462
|
+
// Starting a new connection during the unload would outlive the adapter
|
|
463
|
+
this.log.debug('Ignoring createAppToken request - the adapter is stopping');
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
// The username is part of the credentials and is deliberately not logged
|
|
467
|
+
this.log.info(`Try to retrieve AppToken for host ${obj.message.host}`);
|
|
468
|
+
let tokenConnection;
|
|
469
|
+
try {
|
|
470
|
+
tokenConnection = new dss_1.DSS({
|
|
471
|
+
host: obj.message.host,
|
|
472
|
+
validateCertificate: this.config.validateCertificate,
|
|
473
|
+
logger: {
|
|
474
|
+
silly: this.log.silly.bind(this),
|
|
475
|
+
debug: this.log.debug.bind(this),
|
|
476
|
+
info: this.log.info.bind(this),
|
|
477
|
+
warn: this.log.warn.bind(this),
|
|
478
|
+
error: this.log.error.bind(this),
|
|
479
|
+
},
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
catch (err) {
|
|
483
|
+
// An invalid host throws synchronously - answer the admin dialog instead
|
|
484
|
+
// of letting the exception escape the message handler
|
|
485
|
+
this.log.warn(`Can not retrieve AppToken: ${configUtils.errorMessage(err)}`);
|
|
486
|
+
this.sendTo(obj.from, obj.command, { error: configUtils.errorMessage(err) }, obj.callback);
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
// Tracked so that an unload can close a token dialog that is still running
|
|
490
|
+
this.tokenConnections.add(tokenConnection);
|
|
491
|
+
let tokenClientClosed = false;
|
|
492
|
+
const closeTokenClient = () => {
|
|
493
|
+
if (tokenClientClosed) {
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
tokenClientClosed = true;
|
|
497
|
+
this.tokenConnections.delete(tokenConnection);
|
|
498
|
+
tokenConnection.stop();
|
|
499
|
+
};
|
|
500
|
+
tokenConnection.createAppTokenAsync(obj.message.username, obj.message.password).then(appToken => {
|
|
501
|
+
closeTokenClient();
|
|
502
|
+
if (this.isStopping()) {
|
|
503
|
+
// The admin dialog is gone with the adapter - no late answer, no log line
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
this.log.info(`Successfully retrieved AppToken for host ${obj.message.host}`);
|
|
507
|
+
// "native" is used by the jsonConfig sendTo component (useNative) to fill the config field
|
|
508
|
+
this.sendTo(obj.from, obj.command, { appToken, native: { appToken } }, obj.callback);
|
|
509
|
+
}, error => {
|
|
510
|
+
closeTokenClient();
|
|
511
|
+
if (this.isStopping()) {
|
|
512
|
+
return;
|
|
513
|
+
}
|
|
514
|
+
this.log.warn(`Error while retrieving AppToken for host ${obj.message.host}: ${configUtils.errorMessage(error)}`);
|
|
515
|
+
this.sendTo(obj.from, obj.command, { error: configUtils.errorMessage(error) }, obj.callback);
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
stopAdapter(callback) {
|
|
521
|
+
// Every caller has to be answered exactly once, even if a stop is already running
|
|
522
|
+
if (this.stopping) {
|
|
523
|
+
if (this.stopped) {
|
|
524
|
+
return void (callback && callback());
|
|
525
|
+
}
|
|
526
|
+
callback && this.stopCallbacks.push(callback);
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
this.stopping = true;
|
|
530
|
+
this.stopCallbacks = callback ? [callback] : [];
|
|
531
|
+
const stopStartedAt = Date.now();
|
|
532
|
+
this.log && this.log.info(`stopping ... ${stopStartedAt}`);
|
|
533
|
+
this.setConnected(false);
|
|
534
|
+
if (this.dataPollTimeout) {
|
|
535
|
+
this.clearTimeout(this.dataPollTimeout);
|
|
536
|
+
this.dataPollTimeout = null;
|
|
537
|
+
}
|
|
538
|
+
if (this.apiActivityTimer) {
|
|
539
|
+
this.clearInterval(this.apiActivityTimer);
|
|
540
|
+
this.apiActivityTimer = null;
|
|
541
|
+
}
|
|
542
|
+
if (this.startupTimeout) {
|
|
543
|
+
this.clearTimeout(this.startupTimeout);
|
|
544
|
+
this.startupTimeout = null;
|
|
545
|
+
}
|
|
546
|
+
if (this.restartTimeout) {
|
|
547
|
+
this.clearTimeout(this.restartTimeout);
|
|
548
|
+
this.restartTimeout = null;
|
|
549
|
+
}
|
|
550
|
+
if (this.dssRetryTimeout) {
|
|
551
|
+
this.clearTimeout(this.dssRetryTimeout);
|
|
552
|
+
this.dssRetryTimeout = null;
|
|
553
|
+
}
|
|
554
|
+
// A scene state that was about to be released stays true - the adapter is going
|
|
555
|
+
// down, and writing after the stop barrier is what isStopping() exists to prevent
|
|
556
|
+
this.momentaryReleases?.forEach(timer => this.clearTimeout(timer));
|
|
557
|
+
this.momentaryReleases?.clear();
|
|
558
|
+
// Anything still parked belongs to a startup that is not going to finish. Dropped
|
|
559
|
+
// rather than carried into the next run, where it would be older than the fresh
|
|
560
|
+
// snapshot and would overwrite it.
|
|
561
|
+
this.pendingEvents = null;
|
|
562
|
+
this.pendingEventsDropped = 0;
|
|
563
|
+
this.eventSubscriptionWaiters = [];
|
|
564
|
+
// Close a still running App-Token dialog: its client lives outside the normal
|
|
565
|
+
// lifecycle and would otherwise keep sockets open after the unload
|
|
566
|
+
this.tokenConnections.forEach(connection => {
|
|
567
|
+
try {
|
|
568
|
+
connection.stop();
|
|
569
|
+
}
|
|
570
|
+
catch (err) {
|
|
571
|
+
this.log && this.log.debug(`Error while closing a token connection: ${configUtils.errorMessage(err)}`);
|
|
572
|
+
}
|
|
573
|
+
});
|
|
574
|
+
this.tokenConnections.clear();
|
|
575
|
+
this.smartHomeKeyControllers?.forEach(controller => controller.abort());
|
|
576
|
+
this.smartHomeKeyControllers?.clear();
|
|
577
|
+
this.dssStruct && this.dssStruct.clearTimeouts();
|
|
578
|
+
// Stop the queue for good: removes all entries, ends the timers and rejects
|
|
579
|
+
// anything that still arrives while the unload is running
|
|
580
|
+
this.dssQueue && this.dssQueue.stop();
|
|
581
|
+
// Central cleanup, runs exactly once no matter which path finished first
|
|
582
|
+
let unsubscribeGuard = null;
|
|
583
|
+
const finish = (time) => {
|
|
584
|
+
if (this.stopped) {
|
|
585
|
+
return;
|
|
586
|
+
}
|
|
587
|
+
this.stopped = true;
|
|
588
|
+
if (unsubscribeGuard) {
|
|
589
|
+
this.clearTimeout(unsubscribeGuard);
|
|
590
|
+
unsubscribeGuard = null;
|
|
591
|
+
}
|
|
592
|
+
// Closes the agents and aborts still running requests/long-polls
|
|
593
|
+
this.dss && this.dss.stop();
|
|
594
|
+
this.smartHome && this.smartHome.stop();
|
|
595
|
+
// This used to print the value unsubscribeAllEvents hands over, which is the
|
|
596
|
+
// deadline of the longest running long-poll - a moment in the FUTURE. Next to
|
|
597
|
+
// the timestamp of the "stopping" line it read like a duration and suggested
|
|
598
|
+
// 15 s where the unload had taken 116 ms. The elapsed time is what anybody
|
|
599
|
+
// reading these two lines wants, and the poll deadline stays available for
|
|
600
|
+
// whoever needs it.
|
|
601
|
+
this.log &&
|
|
602
|
+
this.log.info(`cleaned everything up... after ${Date.now() - stopStartedAt}ms (longest event poll ran until ${time})`);
|
|
603
|
+
const callbacks = this.stopCallbacks;
|
|
604
|
+
this.stopCallbacks = [];
|
|
605
|
+
callbacks.forEach(cb => {
|
|
606
|
+
try {
|
|
607
|
+
cb();
|
|
608
|
+
}
|
|
609
|
+
catch (err) {
|
|
610
|
+
this.log && this.log.debug(`Error in unload callback: ${configUtils.errorMessage(err)}`);
|
|
611
|
+
}
|
|
612
|
+
});
|
|
613
|
+
};
|
|
614
|
+
// unsubscribe to all events
|
|
615
|
+
if (this.dss) {
|
|
616
|
+
// A timer of adapter-core: js-controller clears its timers only after the unload
|
|
617
|
+
// callback ran, so this guard still fires while the unload is in progress
|
|
618
|
+
unsubscribeGuard = this.setTimeout(() => {
|
|
619
|
+
unsubscribeGuard = null;
|
|
620
|
+
this.log && this.log.info('unsubscribe did not finish in time, stopping anyway');
|
|
621
|
+
finish(0);
|
|
622
|
+
}, this.stopGuardTimeout || 4000);
|
|
623
|
+
this.dss.unsubscribeAllEvents(time => finish(time));
|
|
624
|
+
}
|
|
625
|
+
else {
|
|
626
|
+
finish(0);
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
/**
|
|
630
|
+
* Ends this instance so that js-controller starts it again.
|
|
631
|
+
*
|
|
632
|
+
* @param timeout ms until the restart
|
|
633
|
+
* @param reason why, completing "restarting because ..." - js-controller logs
|
|
634
|
+
* it next to the exit code
|
|
635
|
+
*/
|
|
636
|
+
restartAdapter(timeout, reason) {
|
|
637
|
+
if (this.restartTimeout || this.isStopping()) {
|
|
638
|
+
return;
|
|
639
|
+
}
|
|
640
|
+
this.restartTimeout = this.setTimeout(() => {
|
|
641
|
+
this.restartTimeout = null;
|
|
642
|
+
// START_IMMEDIATELY_AFTER_STOP is the code js-controller restarts after one second
|
|
643
|
+
// and logs at info level together with the reason. The -100 used before only
|
|
644
|
+
// became that code because a process exit code is cut to 8 bits: the instance
|
|
645
|
+
// logged "Terminated (-100): Without reason" as a warning at every restart, and in
|
|
646
|
+
// compact mode, where nothing is cut, the host logged an error and waited 30 s.
|
|
647
|
+
// Read here and not at load time: the test stubs of adapter-core do not carry it.
|
|
648
|
+
const exitCode = utils.EXIT_CODES.START_IMMEDIATELY_AFTER_STOP;
|
|
649
|
+
const text = `restarting because ${reason}`;
|
|
650
|
+
// In compact mode terminate() hands the reason to the host as the "signal" of its
|
|
651
|
+
// exit event, and the host logs any signal as a warning ("terminated due to
|
|
652
|
+
// restarting because ..."). There the reason is logged here at info and not passed
|
|
653
|
+
// on. undefined and not the bare exit code: terminate(156) would make 156 the signal.
|
|
654
|
+
const stopReason = this.compactMode ? undefined : text;
|
|
655
|
+
if (this.compactMode) {
|
|
656
|
+
this.log.info(text);
|
|
657
|
+
}
|
|
658
|
+
if (typeof this.stop === 'function') {
|
|
659
|
+
// stop(), not terminate(): only stop() runs onUnload first. terminate() skips
|
|
660
|
+
// it, and in compact mode this instance would keep polling the dSS events and
|
|
661
|
+
// keep its timers and its websocket in the shared process next to the new one.
|
|
662
|
+
// process.exit() is no option either, it would end that whole process.
|
|
663
|
+
this.stop({ exitCode, reason: stopReason }).catch(() => this.terminate(stopReason, exitCode));
|
|
664
|
+
}
|
|
665
|
+
else {
|
|
666
|
+
this.terminate(stopReason, exitCode);
|
|
667
|
+
}
|
|
668
|
+
}, timeout || 1000);
|
|
669
|
+
}
|
|
670
|
+
/**
|
|
671
|
+
* @param isConnected the new value of info.connection
|
|
672
|
+
*/
|
|
673
|
+
setConnected(isConnected) {
|
|
674
|
+
if (isConnected && this.isStopping()) {
|
|
675
|
+
// A late startup callback must never mark an already stopped adapter as connected
|
|
676
|
+
this.log && this.log.debug('Ignoring connected = true, the adapter is stopping');
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
679
|
+
if (this.connected !== isConnected) {
|
|
680
|
+
this.connected = isConnected;
|
|
681
|
+
void this.setState('info.connection', isConnected, true);
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
/**
|
|
685
|
+
* Brings the boolean options into a defined state.
|
|
686
|
+
*
|
|
687
|
+
* The instance object can be written by hand, by a script or by a restored backup, so
|
|
688
|
+
* a value can arrive as the string "false". Plain truthiness would read that as true -
|
|
689
|
+
* for deleteUnknownObjects that would silently enable deleting objects including their
|
|
690
|
+
* custom settings (history, influxdb, ...).
|
|
691
|
+
*/
|
|
692
|
+
normalizeConfig() {
|
|
693
|
+
// option name -> safe default, matching "native" in io-package.json
|
|
694
|
+
const booleanDefaults = {
|
|
695
|
+
usePresetValues: true,
|
|
696
|
+
initializeOutputValues: true,
|
|
697
|
+
deleteUnknownObjects: false,
|
|
698
|
+
validateCertificate: false,
|
|
699
|
+
};
|
|
700
|
+
Object.keys(booleanDefaults).forEach(name => {
|
|
701
|
+
const raw = this.config[name];
|
|
702
|
+
const normalized = configUtils.normalizeBoolean(raw, booleanDefaults[name]);
|
|
703
|
+
if (raw !== undefined && !configUtils.isInterpretableBoolean(raw)) {
|
|
704
|
+
// Never fail silently - especially not for the certificate check
|
|
705
|
+
this.log.warn(`Configuration value "${name}" is not a valid boolean (${JSON.stringify(raw)}), using the default ${normalized}. Please check the adapter settings.`);
|
|
706
|
+
}
|
|
707
|
+
this.config[name] = normalized;
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
main() {
|
|
711
|
+
// Reset the connection indicator during startup
|
|
712
|
+
this.setConnected(false);
|
|
713
|
+
this.normalizeConfig();
|
|
714
|
+
if (!this.config.host || !this.config.appToken) {
|
|
715
|
+
this.log.warn('Please open Admin page for this adapter to set the host and create an App Token.');
|
|
716
|
+
return;
|
|
717
|
+
}
|
|
718
|
+
if (!Digitalstrom.looksLikeAppToken(this.config.appToken)) {
|
|
719
|
+
this.log.error('The stored App-Token does not look like a valid digitalSTROM token (expected a long hex ' +
|
|
720
|
+
'string). Please open the adapter configuration, enter the App-Token again or create a new ' +
|
|
721
|
+
'one with your DSS login, and save. The adapter tries to log in anyway.');
|
|
722
|
+
}
|
|
723
|
+
// Zaehlt je Weg, was wirklich laeuft - der Status-Tab zeigt daraus
|
|
724
|
+
// "x empfangen / y gesendet in den letzten 10 Minuten"
|
|
725
|
+
this.apiActivity = new activityCounter_1.ActivityCounter();
|
|
726
|
+
let dss;
|
|
727
|
+
try {
|
|
728
|
+
dss = new dss_1.DSS({
|
|
729
|
+
host: this.config.host,
|
|
730
|
+
appToken: this.config.appToken,
|
|
731
|
+
validateCertificate: this.config.validateCertificate,
|
|
732
|
+
onActivity: (kind, detail) => this.countClassicActivity(kind, detail),
|
|
733
|
+
logger: {
|
|
734
|
+
silly: this.log.silly.bind(this),
|
|
735
|
+
debug: this.log.debug.bind(this),
|
|
736
|
+
info: this.log.info.bind(this),
|
|
737
|
+
warn: this.log.warn.bind(this),
|
|
738
|
+
error: this.log.error.bind(this),
|
|
739
|
+
},
|
|
740
|
+
});
|
|
741
|
+
}
|
|
742
|
+
catch (err) {
|
|
743
|
+
// An invalid host is a configuration error - restarting would only loop.
|
|
744
|
+
// The adapter stays idle until the configuration is corrected (which restarts it).
|
|
745
|
+
this.dss = null;
|
|
746
|
+
this.log.error(`${configUtils.errorMessage(err)}. Please correct the host in the adapter configuration - the adapter stays inactive until then.`);
|
|
747
|
+
return;
|
|
748
|
+
}
|
|
749
|
+
this.dss = dss;
|
|
750
|
+
this.smartHome = this.createSmartHomeClient();
|
|
751
|
+
// 30 s Takt reicht: der Status-Tab zeigt ein 10-Minuten-Fenster
|
|
752
|
+
this.apiActivityTimer = this.setInterval(() => this.publishApiActivity(), 30000);
|
|
753
|
+
const dssQueue = new dssQueue_1.DSSQueue({
|
|
754
|
+
logger: {
|
|
755
|
+
silly: this.log.silly.bind(this),
|
|
756
|
+
debug: this.log.debug.bind(this),
|
|
757
|
+
info: this.log.info.bind(this),
|
|
758
|
+
warn: this.log.warn.bind(this),
|
|
759
|
+
error: this.log.error.bind(this),
|
|
760
|
+
},
|
|
761
|
+
dss,
|
|
762
|
+
});
|
|
763
|
+
this.dssQueue = dssQueue;
|
|
764
|
+
const dssStruct = new dssStructure_1.DSSStructure({
|
|
765
|
+
dss,
|
|
766
|
+
dssQueue,
|
|
767
|
+
adapter: this,
|
|
768
|
+
smartHome: this.smartHome,
|
|
769
|
+
});
|
|
770
|
+
this.dssStruct = dssStruct;
|
|
771
|
+
this.dataPollInterval = Digitalstrom.normalizePollInterval(this.config.dataPollInterval);
|
|
772
|
+
this.waitForDss(dssName => {
|
|
773
|
+
// Every step checks the stop barrier: an answer that arrives during the
|
|
774
|
+
// unload must not create new objects, timers or subscriptions any more.
|
|
775
|
+
if (this.isStopping()) {
|
|
776
|
+
return;
|
|
777
|
+
}
|
|
778
|
+
this.log.debug(`getName: ${JSON.stringify(dssName)}`);
|
|
779
|
+
// Watchdog: if initialization does not finish in time (e.g. a stuck request
|
|
780
|
+
// or a DSS that stops responding mid-init), restart the adapter. Armed only
|
|
781
|
+
// now that the dSS answered - waitForDss() may wait for hours, and that is
|
|
782
|
+
// not an initialization that got stuck.
|
|
783
|
+
this.startupTimeout = this.setTimeout(() => {
|
|
784
|
+
this.startupTimeout = null;
|
|
785
|
+
this.log.warn('Initialization did not finish within 10 minutes, restarting adapter');
|
|
786
|
+
this.restartAdapter(1000, 'the initialization did not finish within 10 minutes');
|
|
787
|
+
}, 600000);
|
|
788
|
+
// getName has proven host, login and reachability, so the events can be
|
|
789
|
+
// subscribed NOW. Measured on a real installation: the adapter was deaf for
|
|
790
|
+
// 149.7 s, and the classic structure read was done after 2.6 s of it - all
|
|
791
|
+
// the rest is parsing and creating 5231 objects. Nothing is applied yet:
|
|
792
|
+
// the level handlers park their events until replayStartupEvents() runs.
|
|
793
|
+
this.pendingEvents = [];
|
|
794
|
+
this.startEarlyEventSubscription();
|
|
795
|
+
this.objectHelper.loadExistingObjects(() => {
|
|
796
|
+
if (this.isStopping()) {
|
|
797
|
+
return;
|
|
798
|
+
}
|
|
799
|
+
this.initializeDSSData(err => {
|
|
800
|
+
if (this.isStopping()) {
|
|
801
|
+
return;
|
|
802
|
+
}
|
|
803
|
+
if (err) {
|
|
804
|
+
this.log.warn(`Error while initializing Data: ${String(err)}`);
|
|
805
|
+
this.restartAdapter(60000, 'reading the DSS structure failed');
|
|
806
|
+
return;
|
|
807
|
+
}
|
|
808
|
+
this.registerObjects();
|
|
809
|
+
this.objectHelper.processObjectQueue(() => {
|
|
810
|
+
if (this.isStopping()) {
|
|
811
|
+
return;
|
|
812
|
+
}
|
|
813
|
+
// From here on all objects exist, so values may be written directly
|
|
814
|
+
dssStruct.objectsReady = true;
|
|
815
|
+
this.setInitialValues(() => {
|
|
816
|
+
if (this.isStopping()) {
|
|
817
|
+
return;
|
|
818
|
+
}
|
|
819
|
+
this.lastScenes = dssStruct.initialScenes;
|
|
820
|
+
// Subscribe right away: every millisecond between the initial
|
|
821
|
+
// snapshot and the active subscription is a window in which
|
|
822
|
+
// scene calls are lost for good. Usually the early
|
|
823
|
+
// subscription already covers it, see ensureEventSubscription().
|
|
824
|
+
this.ensureEventSubscription(subscriptionErr => {
|
|
825
|
+
if (this.isStopping()) {
|
|
826
|
+
return;
|
|
827
|
+
}
|
|
828
|
+
if (subscriptionErr) {
|
|
829
|
+
// Without events the adapter would silently miss every
|
|
830
|
+
// change, so this must not be treated as a running adapter
|
|
831
|
+
this.log.error(`Could not subscribe to the DSS events: ${subscriptionErr.message}`);
|
|
832
|
+
this.setConnected(false);
|
|
833
|
+
if (this.startupTimeout) {
|
|
834
|
+
this.clearTimeout(this.startupTimeout);
|
|
835
|
+
this.startupTimeout = null;
|
|
836
|
+
}
|
|
837
|
+
// Drop the partially created subscriptions before restarting
|
|
838
|
+
dss.unsubscribeAllEvents(() => this.restartAdapter(30000, 'the DSS events could not be subscribed'));
|
|
839
|
+
return;
|
|
840
|
+
}
|
|
841
|
+
this.subscribeStates('*');
|
|
842
|
+
this.setConnected(true);
|
|
843
|
+
if (this.startupTimeout) {
|
|
844
|
+
this.clearTimeout(this.startupTimeout);
|
|
845
|
+
this.startupTimeout = null;
|
|
846
|
+
}
|
|
847
|
+
this.log.info('Subscribed to states ...');
|
|
848
|
+
// Everything the dSS reported while the objects were
|
|
849
|
+
// being created, in arrival order, ON TOP of the initial
|
|
850
|
+
// snapshot that was just written - never before it
|
|
851
|
+
this.replayStartupEvents();
|
|
852
|
+
this.startDataPolling();
|
|
853
|
+
// Catches scene calls that happened while the structure
|
|
854
|
+
// was being built, see resyncSceneStates()
|
|
855
|
+
this.resyncSceneStates();
|
|
856
|
+
this.clearAdditionalObjects();
|
|
857
|
+
this.startNotificationChannel();
|
|
858
|
+
});
|
|
859
|
+
});
|
|
860
|
+
});
|
|
861
|
+
});
|
|
862
|
+
});
|
|
863
|
+
});
|
|
864
|
+
}
|
|
865
|
+
/**
|
|
866
|
+
* Calls back with the answer of apartment/getName as soon as the dSS answers.
|
|
867
|
+
*
|
|
868
|
+
* A dSS that refuses connections is rebooting, being updated or switched off. Ending the
|
|
869
|
+
* process for that turned one night without a dSS into 102 restarts, each with two error
|
|
870
|
+
* lines and a warning from js-controller. The process stays now and only this check is
|
|
871
|
+
* repeated: nothing else of the startup exists yet, so there is nothing to tear down or
|
|
872
|
+
* to create twice. Never calls back after a stop - the unload clears the retry timer and
|
|
873
|
+
* aborts a check that is still running.
|
|
874
|
+
*
|
|
875
|
+
* @param callback receives the answer of apartment/getName
|
|
876
|
+
*/
|
|
877
|
+
waitForDss(callback) {
|
|
878
|
+
const dss = this.dss;
|
|
879
|
+
if (!dss || dss.stopped || this.isStopping()) {
|
|
880
|
+
return;
|
|
881
|
+
}
|
|
882
|
+
dss.requestAsync('apartment', 'getName').then(dssName => {
|
|
883
|
+
if (this.isStopping()) {
|
|
884
|
+
return;
|
|
885
|
+
}
|
|
886
|
+
this.noteDssReachable();
|
|
887
|
+
callback(dssName);
|
|
888
|
+
}, err => {
|
|
889
|
+
// A stopped client refuses every request - that is a shutdown, not an
|
|
890
|
+
// outage, and asking it again would only loop
|
|
891
|
+
if (this.isStopping() || dss.stopped) {
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
this.noteDssUnreachable(err);
|
|
895
|
+
this.dssRetryTimeout = this.setTimeout(() => {
|
|
896
|
+
this.dssRetryTimeout = null;
|
|
897
|
+
this.waitForDss(callback);
|
|
898
|
+
}, this.dssRetryDelay || DSS_RETRY_DELAY);
|
|
899
|
+
});
|
|
900
|
+
}
|
|
901
|
+
/**
|
|
902
|
+
* Reports a failed connection check - loudly once, then quietly.
|
|
903
|
+
*
|
|
904
|
+
* The first failure is an error with the hint what to check. Every further failure with
|
|
905
|
+
* an error already reported goes to debug: nothing has changed, info.connection stays
|
|
906
|
+
* false, and a line every five minutes for hours helps nobody. A failure with a NEW error
|
|
907
|
+
* is reported again - a dSS that accepts the connection but refuses the login needs
|
|
908
|
+
* somebody to act, even in the middle of an outage.
|
|
909
|
+
*
|
|
910
|
+
* A refused login is named as such. The dSS was reached then, and a line that starts
|
|
911
|
+
* with "Cannot reach" sends the user to the network, while a revoked App-Token never
|
|
912
|
+
* comes back by itself.
|
|
913
|
+
*
|
|
914
|
+
* @param err why the check failed
|
|
915
|
+
*/
|
|
916
|
+
noteDssUnreachable(err) {
|
|
917
|
+
const message = configUtils.errorMessage(err);
|
|
918
|
+
const retryIn = Digitalstrom.formatDuration(this.dssRetryDelay || DSS_RETRY_DELAY);
|
|
919
|
+
// loginApplication answered without a session token (see DSS.getSessionToken()).
|
|
920
|
+
// dSS 1.19 answers a revoked App-Token and a full session table the same way.
|
|
921
|
+
const loginRefused = /^Login failed:/.test(message);
|
|
922
|
+
const tokenHint = 'Please check that the App-Token is still enabled on the DSS, or create a new one in the adapter settings';
|
|
923
|
+
const outage = this.dssOutage;
|
|
924
|
+
if (!outage) {
|
|
925
|
+
this.dssOutage = { since: node_perf_hooks_1.performance.now(), failures: 1, reported: new Set([message]) };
|
|
926
|
+
// The line for the answer is info: somebody running at warn must not wait for it
|
|
927
|
+
const howItGoesOn = `The adapter asks again every ${retryIn}, reports a different error once more and logs at ` +
|
|
928
|
+
`info level when the DSS ${loginRefused ? 'accepts the login' : 'answers'} again`;
|
|
929
|
+
this.log.error(loginRefused
|
|
930
|
+
? `The DSS at ${this.config.host} refused the login with the App-Token (getName): ${message}. ` +
|
|
931
|
+
`${tokenHint}. ${howItGoesOn}`
|
|
932
|
+
: `Cannot reach the DSS at ${this.config.host} (getName): ${message}. Please check the host, ` +
|
|
933
|
+
`the network and the App-Token in the adapter settings. ${howItGoesOn}`);
|
|
934
|
+
return;
|
|
935
|
+
}
|
|
936
|
+
outage.failures++;
|
|
937
|
+
if (!outage.reported.has(message)) {
|
|
938
|
+
outage.reported.add(message);
|
|
939
|
+
// A refused login is an answer of the dSS, so neither line claims it is silent
|
|
940
|
+
this.log.error(loginRefused
|
|
941
|
+
? `The DSS at ${this.config.host} answers, but refuses the login with the App-Token - a ` +
|
|
942
|
+
`different error: ${message}. ${tokenHint}`
|
|
943
|
+
: `The connection check of the DSS at ${this.config.host} still fails, now with a different ` +
|
|
944
|
+
`error: ${message}`);
|
|
945
|
+
return;
|
|
946
|
+
}
|
|
947
|
+
this.log.debug(`DSS connection check still fails (${outage.failures} failed checks in ${Digitalstrom.formatDuration(node_perf_hooks_1.performance.now() - outage.since)}): ${message} - asking again in ${retryIn}`);
|
|
948
|
+
}
|
|
949
|
+
/**
|
|
950
|
+
* Closes an outage noted by noteDssUnreachable() with one line saying how long it took.
|
|
951
|
+
*/
|
|
952
|
+
noteDssReachable() {
|
|
953
|
+
const outage = this.dssOutage;
|
|
954
|
+
if (!outage) {
|
|
955
|
+
return;
|
|
956
|
+
}
|
|
957
|
+
this.dssOutage = null;
|
|
958
|
+
this.log.info(`The DSS answers again after ${Digitalstrom.formatDuration(node_perf_hooks_1.performance.now() - outage.since)} (${outage.failures} failed check${outage.failures === 1 ? '' : 's'}) - continuing the start`);
|
|
959
|
+
}
|
|
960
|
+
/**
|
|
961
|
+
* Formats a duration for a log line: "45 s", "5 min", "4 min 12 s", "8 h 37 min".
|
|
962
|
+
*
|
|
963
|
+
* @param ms duration in milliseconds
|
|
964
|
+
* @returns readable duration, rounded to seconds
|
|
965
|
+
*/
|
|
966
|
+
static formatDuration(ms) {
|
|
967
|
+
const total = Math.max(0, Math.round(ms / 1000));
|
|
968
|
+
const hours = Math.floor(total / 3600);
|
|
969
|
+
const minutes = Math.floor((total % 3600) / 60);
|
|
970
|
+
const seconds = total % 60;
|
|
971
|
+
if (hours) {
|
|
972
|
+
return minutes ? `${hours} h ${minutes} min` : `${hours} h`;
|
|
973
|
+
}
|
|
974
|
+
if (minutes) {
|
|
975
|
+
return seconds ? `${minutes} min ${seconds} s` : `${minutes} min`;
|
|
976
|
+
}
|
|
977
|
+
return `${seconds} s`;
|
|
978
|
+
}
|
|
979
|
+
/**
|
|
980
|
+
* Re-reads the last called scene of every known zone group once the event
|
|
981
|
+
* subscription is active.
|
|
982
|
+
*
|
|
983
|
+
* The initial scene snapshot is taken while the structure is being read, which can
|
|
984
|
+
* take minutes on large installations. A scene called between that snapshot and the
|
|
985
|
+
* active subscription appears neither in the snapshot nor in an event, so the states
|
|
986
|
+
* would stay wrong until the next scene call. The re-read uses the lowest priority so
|
|
987
|
+
* it never delays a user command, and only a really changed scene is applied - through
|
|
988
|
+
* the normal event path, so all follow up handling stays identical.
|
|
989
|
+
*
|
|
990
|
+
* @param [callback] called when every zone group was checked
|
|
991
|
+
*/
|
|
992
|
+
resyncSceneStates(callback) {
|
|
993
|
+
// Group keys look like "<zoneId>.<groupId>", device keys are dSUIDs without a dot
|
|
994
|
+
const groupKeys = Object.keys(this.lastScenes || {}).filter(key => /^\d+\.\d+$/.test(key));
|
|
995
|
+
const dss = this.dss;
|
|
996
|
+
const dssQueue = this.dssQueue;
|
|
997
|
+
if (!groupKeys.length || this.isStopping() || !dssQueue || !dss) {
|
|
998
|
+
return void (callback && callback());
|
|
999
|
+
}
|
|
1000
|
+
this.log.debug(`Checking the scenes of ${groupKeys.length} zone groups for changes during the startup`);
|
|
1001
|
+
let open = groupKeys.length;
|
|
1002
|
+
const done = () => {
|
|
1003
|
+
if (!--open) {
|
|
1004
|
+
callback && callback();
|
|
1005
|
+
}
|
|
1006
|
+
};
|
|
1007
|
+
groupKeys.forEach(key => {
|
|
1008
|
+
const [zoneId, groupId] = key.split('.');
|
|
1009
|
+
dssQueue.pushQueryQueue('zone', {
|
|
1010
|
+
dssClass: 'zone',
|
|
1011
|
+
dssFunction: 'getLastCalledScene',
|
|
1012
|
+
params: {
|
|
1013
|
+
id: zoneId,
|
|
1014
|
+
groupID: groupId,
|
|
1015
|
+
},
|
|
1016
|
+
}, 'low', (err, res) => {
|
|
1017
|
+
if (this.isStopping()) {
|
|
1018
|
+
return void done();
|
|
1019
|
+
}
|
|
1020
|
+
if (err || !res || !res.ok || !res.result || res.result.scene === undefined) {
|
|
1021
|
+
this.log.debug(`Could not check the scene of zone group ${key}: ${(err && err.message) || JSON.stringify(res)}`);
|
|
1022
|
+
return void done();
|
|
1023
|
+
}
|
|
1024
|
+
if (String(res.result.scene) === String(this.lastScenes[key])) {
|
|
1025
|
+
return void done();
|
|
1026
|
+
}
|
|
1027
|
+
this.log.info(`Scene of zone group ${key} changed to ${res.result.scene} while the adapter was starting - applying it now`);
|
|
1028
|
+
dss.emit('callScene', {
|
|
1029
|
+
name: 'callScene',
|
|
1030
|
+
source: { isDevice: false, isGroup: true, isApartment: false },
|
|
1031
|
+
properties: {
|
|
1032
|
+
zoneID: String(zoneId),
|
|
1033
|
+
groupID: String(groupId),
|
|
1034
|
+
sceneID: String(res.result.scene),
|
|
1035
|
+
callOrigin: '-1',
|
|
1036
|
+
},
|
|
1037
|
+
});
|
|
1038
|
+
done();
|
|
1039
|
+
});
|
|
1040
|
+
});
|
|
1041
|
+
}
|
|
1042
|
+
/**
|
|
1043
|
+
* True when the value looks like a digitalSTROM application token.
|
|
1044
|
+
*
|
|
1045
|
+
* The DSS issues a long hex string. A stored value that does not look like one usually
|
|
1046
|
+
* means js-controller could not decrypt it, and the login would fail with nothing but
|
|
1047
|
+
* "Login failed" - which gives the user no clue what to do.
|
|
1048
|
+
*
|
|
1049
|
+
* Deliberately only a plausibility check - it never blocks the login, it only produces a
|
|
1050
|
+
* helpful message.
|
|
1051
|
+
*
|
|
1052
|
+
* @param token configured app token
|
|
1053
|
+
* @returns true if the value can be a valid token
|
|
1054
|
+
*/
|
|
1055
|
+
static looksLikeAppToken(token) {
|
|
1056
|
+
return typeof token === 'string' && /^[0-9a-f]{32,}$/i.test(token.trim());
|
|
1057
|
+
}
|
|
1058
|
+
/**
|
|
1059
|
+
* True for a scene that commands a change instead of selecting a preset.
|
|
1060
|
+
*
|
|
1061
|
+
* The group is checked FIRST and not afterwards: group 48 reads scene 10 as "Cooling
|
|
1062
|
+
* Night" and 11 as "Cooling Holiday", the ventilation groups read their own numbers
|
|
1063
|
+
* too. Those are lasting modes, and releasing one would clear the operation mode of a
|
|
1064
|
+
* room half a second after it was set.
|
|
1065
|
+
*
|
|
1066
|
+
* @param sceneId scene number of the event
|
|
1067
|
+
* @param groupId group of the event, undefined for a device
|
|
1068
|
+
* @returns true if the scene leaves no state behind
|
|
1069
|
+
*/
|
|
1070
|
+
static isMomentaryScene(sceneId, groupId) {
|
|
1071
|
+
if (groupId !== undefined && dssConstants.ownSceneNumberGroups.includes(Number(groupId))) {
|
|
1072
|
+
return false;
|
|
1073
|
+
}
|
|
1074
|
+
return !!dssConstants.momentaryScenes[Number(sceneId)];
|
|
1075
|
+
}
|
|
1076
|
+
/**
|
|
1077
|
+
* True for the internal helper states of dSS addons, which have no object on purpose.
|
|
1078
|
+
*
|
|
1079
|
+
* Measured on a dSS20 1.19.13: the window-states addon keeps "<dsuid>_open-tilded" per
|
|
1080
|
+
* window handle, the climate control "queue-active" while it works through its queue.
|
|
1081
|
+
* Neither is anything a user would read.
|
|
1082
|
+
*
|
|
1083
|
+
* @param statename name of the state in the dSS
|
|
1084
|
+
* @returns true if the state is logged at debug only
|
|
1085
|
+
*/
|
|
1086
|
+
static isAddonHelperState(statename) {
|
|
1087
|
+
return statename === 'queue-active' || /_open-tilded$/.test(statename);
|
|
1088
|
+
}
|
|
1089
|
+
/**
|
|
1090
|
+
* Logs a scene call that found no scene state, with zone, group and scene.
|
|
1091
|
+
*
|
|
1092
|
+
* Two kinds are expected and go to debug: a room or group that has no scene objects at
|
|
1093
|
+
* all - the climate control calls the scenes of group 48 in every room at its switch
|
|
1094
|
+
* times, also in rooms without heating - and a command such as Stop on group level,
|
|
1095
|
+
* which only exists as a device scene state. Anything else is named once per run at
|
|
1096
|
+
* info, then at debug.
|
|
1097
|
+
*
|
|
1098
|
+
* @param data the callScene or undoScene event
|
|
1099
|
+
*/
|
|
1100
|
+
logUnmappedSceneCall(data) {
|
|
1101
|
+
const props = data.properties || {};
|
|
1102
|
+
const source = data.source || {};
|
|
1103
|
+
const stateMap = (this.dssStruct && this.dssStruct.stateMap) || {};
|
|
1104
|
+
let key;
|
|
1105
|
+
let what;
|
|
1106
|
+
let expected = false;
|
|
1107
|
+
if (source.isDevice) {
|
|
1108
|
+
key = `device ${source.dSUID}.${props.sceneID}`;
|
|
1109
|
+
what = `device ${source.dSUID}, scene ${props.sceneID}`;
|
|
1110
|
+
}
|
|
1111
|
+
else {
|
|
1112
|
+
const zone = source.isApartment ? '0' : props.zoneID;
|
|
1113
|
+
const group = source.isApartment ? '0' : props.groupID;
|
|
1114
|
+
key = `${zone}.${group}.${props.sceneID}`;
|
|
1115
|
+
what = `zone ${zone}, group ${group}, scene ${props.sceneID}`;
|
|
1116
|
+
if (!this.sceneGroupCache || this.sceneGroupCache.stateMap !== stateMap) {
|
|
1117
|
+
// Built once per structure, not per call: the climate control alone calls
|
|
1118
|
+
// group 48 in every room at each of its switch times
|
|
1119
|
+
const groups = new Set();
|
|
1120
|
+
Object.keys(stateMap).forEach(id => {
|
|
1121
|
+
const match = /^(\d+)\.(\d+)\.scenes\./.exec(id);
|
|
1122
|
+
match && groups.add(`${match[1]}.${match[2]}`);
|
|
1123
|
+
});
|
|
1124
|
+
this.sceneGroupCache = { stateMap, groups };
|
|
1125
|
+
}
|
|
1126
|
+
if (!this.sceneGroupCache.groups.has(`${zone}.${group}`)) {
|
|
1127
|
+
what += ' - this room has no scene objects for that group';
|
|
1128
|
+
expected = true;
|
|
1129
|
+
}
|
|
1130
|
+
else if (Digitalstrom.isMomentaryScene(props.sceneID, group)) {
|
|
1131
|
+
what += ' - a command scene, only devices have a state for it';
|
|
1132
|
+
expected = true;
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
if (!this.unmappedSceneCalls) {
|
|
1136
|
+
this.unmappedSceneCalls = new Set();
|
|
1137
|
+
}
|
|
1138
|
+
if (expected || this.unmappedSceneCalls.has(key)) {
|
|
1139
|
+
this.log.debug(`${data.name || 'Scene call'} without scene state: ${what}`);
|
|
1140
|
+
return;
|
|
1141
|
+
}
|
|
1142
|
+
this.unmappedSceneCalls.add(key);
|
|
1143
|
+
this.log.info(`${data.name || 'Scene call'} without scene state: ${what}. The scene is not mapped to an object here; further calls of it are logged at debug level.`);
|
|
1144
|
+
}
|
|
1145
|
+
/**
|
|
1146
|
+
* Wraps an event handler so that it parks its event while the objects are being built.
|
|
1147
|
+
*
|
|
1148
|
+
* ONLY for handlers whose event carries a LEVEL - a sensor reading, a state, a binary
|
|
1149
|
+
* input. For those, applying them late is the same as applying them on time: the newest
|
|
1150
|
+
* value wins either way, and the initial snapshot underneath is older than all of them.
|
|
1151
|
+
*
|
|
1152
|
+
* Deliberately NOT for callScene, undoScene and buttonClick. Those are actions, and a
|
|
1153
|
+
* button press replayed two minutes after it happened would make every rule listening
|
|
1154
|
+
* on it act two minutes late - lights on, blinds up, long after the person left the
|
|
1155
|
+
* room. Losing it is the lesser evil, and it is what happened before the subscription
|
|
1156
|
+
* moved forward - only for 150 s instead of the 95 s the objects now take.
|
|
1157
|
+
*
|
|
1158
|
+
* The repair afterwards is partial, and the comment used to claim more than it does:
|
|
1159
|
+
* resyncSceneStates() re-reads the last called scene of every ZONE GROUP, so a group
|
|
1160
|
+
* scene missed here is corrected. A scene the dSS reported for a single device is not
|
|
1161
|
+
* - initialScenes only ever holds group keys - and on an installation whose wall
|
|
1162
|
+
* switches report per device that is the common case. Such a scene state stays as it
|
|
1163
|
+
* was until the next call reaches it.
|
|
1164
|
+
*
|
|
1165
|
+
* @param handler the live handler
|
|
1166
|
+
* @returns the handler with the parking in front of it
|
|
1167
|
+
*/
|
|
1168
|
+
parkable(handler) {
|
|
1169
|
+
return (...args) => {
|
|
1170
|
+
if (!this.pendingEvents) {
|
|
1171
|
+
return handler(...args);
|
|
1172
|
+
}
|
|
1173
|
+
if (this.pendingEvents.length >= this.startupEventLimit) {
|
|
1174
|
+
// The newest value is the one that counts, so the oldest goes. Reported once
|
|
1175
|
+
// at the replay rather than per event.
|
|
1176
|
+
this.pendingEvents.shift();
|
|
1177
|
+
this.pendingEventsDropped++;
|
|
1178
|
+
}
|
|
1179
|
+
this.pendingEvents.push({ apply: () => handler(...args), at: Date.now() });
|
|
1180
|
+
};
|
|
1181
|
+
}
|
|
1182
|
+
/**
|
|
1183
|
+
* Wraps an event handler that must NOT run while the objects are being built and must
|
|
1184
|
+
* not be caught up afterwards either.
|
|
1185
|
+
*
|
|
1186
|
+
* These are the actions - a scene call, a button press. Replaying one late would make
|
|
1187
|
+
* every rule listening on it act minutes after the fact, and running it live would let
|
|
1188
|
+
* it reach into a half built tree: handleScene() walks dssStruct.apartmentStructure,
|
|
1189
|
+
* which is still null until the structure is parsed. Dropping it is exactly what
|
|
1190
|
+
* happened before the subscription was moved forward, and the scenes are re-read by
|
|
1191
|
+
* resyncSceneStates() at the end of the start anyway.
|
|
1192
|
+
*
|
|
1193
|
+
* @param handler the live handler
|
|
1194
|
+
* @returns the handler, silent until the objects are there
|
|
1195
|
+
*/
|
|
1196
|
+
liveOnly(handler) {
|
|
1197
|
+
return (...args) => {
|
|
1198
|
+
if (this.pendingEvents) {
|
|
1199
|
+
// Named, because this is the only trace such an event ever leaves - and
|
|
1200
|
+
// nothing catches a device scene up afterwards, see the note above
|
|
1201
|
+
const name = (args[0] && args[0].name) || 'event';
|
|
1202
|
+
this.log.debug(`${name} ignored - the objects are still being created`);
|
|
1203
|
+
return;
|
|
1204
|
+
}
|
|
1205
|
+
handler(...args);
|
|
1206
|
+
};
|
|
1207
|
+
}
|
|
1208
|
+
/**
|
|
1209
|
+
* Applies everything that arrived while the objects did not exist yet, in arrival order.
|
|
1210
|
+
*
|
|
1211
|
+
* Must run AFTER setInitialValues() and never before it. The initial snapshot is the
|
|
1212
|
+
* older picture - it was read while the structure was being parsed - so replaying first
|
|
1213
|
+
* would let the snapshot overwrite the newer value and leave exactly the stale state
|
|
1214
|
+
* this is meant to prevent.
|
|
1215
|
+
*/
|
|
1216
|
+
replayStartupEvents() {
|
|
1217
|
+
const parked = this.pendingEvents;
|
|
1218
|
+
this.pendingEvents = null;
|
|
1219
|
+
if (!parked || !parked.length) {
|
|
1220
|
+
this.pendingEventsDropped = 0;
|
|
1221
|
+
this.settlePendingModelReady();
|
|
1222
|
+
return;
|
|
1223
|
+
}
|
|
1224
|
+
const oldest = Math.round((Date.now() - parked[0].at) / 1000);
|
|
1225
|
+
this.log.info(`Applying ${parked.length} event(s) that arrived while the objects were being created, the oldest ${oldest}s ago`);
|
|
1226
|
+
if (this.pendingEventsDropped) {
|
|
1227
|
+
this.log.warn(`${this.pendingEventsDropped} further event(s) were dropped during the startup - the newest value of a state survived, an intermediate one may not have`);
|
|
1228
|
+
this.pendingEventsDropped = 0;
|
|
1229
|
+
}
|
|
1230
|
+
parked.forEach(entry => {
|
|
1231
|
+
try {
|
|
1232
|
+
entry.apply();
|
|
1233
|
+
}
|
|
1234
|
+
catch (err) {
|
|
1235
|
+
// One unusable event must not cost the remaining ones
|
|
1236
|
+
this.log.debug(`Parked event could not be applied: ${configUtils.errorMessage(err)}`);
|
|
1237
|
+
}
|
|
1238
|
+
});
|
|
1239
|
+
this.settlePendingModelReady();
|
|
1240
|
+
}
|
|
1241
|
+
/**
|
|
1242
|
+
* Acts on a model_ready that arrived while the objects were being created. Called at
|
|
1243
|
+
* the end of the startup, whether or not anything was parked.
|
|
1244
|
+
*/
|
|
1245
|
+
settlePendingModelReady() {
|
|
1246
|
+
if (!this.pendingModelReady) {
|
|
1247
|
+
return;
|
|
1248
|
+
}
|
|
1249
|
+
this.pendingModelReady = false;
|
|
1250
|
+
this.log.info('The dSS re-initialized its model during the startup - restarting now that it is through');
|
|
1251
|
+
this.restartAdapter(10000, 'the dSS re-initialized its apartment model during the startup');
|
|
1252
|
+
}
|
|
1253
|
+
/**
|
|
1254
|
+
* Lets a state that stands for a moment fall back to false after
|
|
1255
|
+
* MOMENTARY_SCENE_RELEASE - a momentary scene, or a button the dSS reports as pressed.
|
|
1256
|
+
*
|
|
1257
|
+
* @param stateId state that was just set to true
|
|
1258
|
+
*/
|
|
1259
|
+
releaseMomentaryState(stateId) {
|
|
1260
|
+
const pending = this.momentaryReleases.get(stateId);
|
|
1261
|
+
// A repeat re-arms instead of adding a second release, so a wall switch that sends
|
|
1262
|
+
// its Stop three times still produces one true and one false
|
|
1263
|
+
pending && this.clearTimeout(pending);
|
|
1264
|
+
this.momentaryReleases.set(stateId, this.setTimeout(() => {
|
|
1265
|
+
this.momentaryReleases.delete(stateId);
|
|
1266
|
+
if (this.isStopping()) {
|
|
1267
|
+
return;
|
|
1268
|
+
}
|
|
1269
|
+
this.setDssState(stateId, false);
|
|
1270
|
+
// Never setTimeout(fn, undefined): that fires on the next tick and would
|
|
1271
|
+
// turn the pulse into no pulse at all
|
|
1272
|
+
}, this.momentaryReleaseDelay || MOMENTARY_SCENE_RELEASE));
|
|
1273
|
+
}
|
|
1274
|
+
/**
|
|
1275
|
+
* Sorts classic API activity into the counters of the status tab.
|
|
1276
|
+
*
|
|
1277
|
+
* @param kind 'request' | 'eventPoll' | 'event'
|
|
1278
|
+
* @param detail request path or event name
|
|
1279
|
+
*/
|
|
1280
|
+
countClassicActivity(kind, detail) {
|
|
1281
|
+
if (!this.apiActivity) {
|
|
1282
|
+
return;
|
|
1283
|
+
}
|
|
1284
|
+
if (kind === 'event') {
|
|
1285
|
+
return void this.apiActivity.count('classic.events');
|
|
1286
|
+
}
|
|
1287
|
+
if (kind === 'eventPoll') {
|
|
1288
|
+
// Der permanente Long-Poll ist Zuhoeren, kein Arbeitsauftrag - er wuerde
|
|
1289
|
+
// die Request-Zahl nur kuenstlich aufblasen
|
|
1290
|
+
return;
|
|
1291
|
+
}
|
|
1292
|
+
this.apiActivity.count('classic.requests');
|
|
1293
|
+
if (detail.includes('/json/metering/')) {
|
|
1294
|
+
this.apiActivity.count('classic.meterReads');
|
|
1295
|
+
}
|
|
1296
|
+
else if (detail.includes('getOutputValue') ||
|
|
1297
|
+
// covers the named channel read of vDC devices in both spellings,
|
|
1298
|
+
// getOutputChannelValue and getOutputChannelValue2
|
|
1299
|
+
detail.includes('getOutputChannelValue') ||
|
|
1300
|
+
detail.includes('getConfig')) {
|
|
1301
|
+
this.apiActivity.count('classic.outputReads');
|
|
1302
|
+
}
|
|
1303
|
+
else if (/callScene|undoScene|setValue|setOutputValue|\/state\/set|pushSensorValue|setTemperatureControlValues|\/event\/raise/.test(detail)) {
|
|
1304
|
+
// Geschriebene Befehle - die zweite Richtung der Ereignisse-und-Steuerung-Zeile
|
|
1305
|
+
this.apiActivity.count('classic.commands');
|
|
1306
|
+
}
|
|
1307
|
+
}
|
|
1308
|
+
/**
|
|
1309
|
+
* @param kind currently always 'request'
|
|
1310
|
+
* @param apiPath path of the request
|
|
1311
|
+
*/
|
|
1312
|
+
countSmartHomeActivity(kind, apiPath) {
|
|
1313
|
+
if (!this.apiActivity || kind !== 'request') {
|
|
1314
|
+
return;
|
|
1315
|
+
}
|
|
1316
|
+
this.apiActivity.count('smarthome.requests');
|
|
1317
|
+
if (apiPath.includes('/meterings/values')) {
|
|
1318
|
+
this.apiActivity.count('smarthome.meterReads');
|
|
1319
|
+
}
|
|
1320
|
+
else if (apiPath.includes('/apartment/status')) {
|
|
1321
|
+
this.apiActivity.count('smarthome.statusReads');
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
/**
|
|
1325
|
+
* Writes the rolling 10 minute activity into info.apiActivity, at most every
|
|
1326
|
+
* 30 seconds. The status tab of the settings renders it live - that is the
|
|
1327
|
+
* proof that a path really works, not just that it is configured.
|
|
1328
|
+
*/
|
|
1329
|
+
publishApiActivity() {
|
|
1330
|
+
if (this.isStopping() || !this.apiActivity) {
|
|
1331
|
+
return;
|
|
1332
|
+
}
|
|
1333
|
+
const counts = this.apiActivity.snapshot();
|
|
1334
|
+
const payload = JSON.stringify({
|
|
1335
|
+
windowMinutes: 10,
|
|
1336
|
+
classic: {
|
|
1337
|
+
requests: counts['classic.requests'] || 0,
|
|
1338
|
+
events: counts['classic.events'] || 0,
|
|
1339
|
+
commands: counts['classic.commands'] || 0,
|
|
1340
|
+
meterReads: counts['classic.meterReads'] || 0,
|
|
1341
|
+
outputReads: counts['classic.outputReads'] || 0,
|
|
1342
|
+
},
|
|
1343
|
+
smarthome: {
|
|
1344
|
+
requests: counts['smarthome.requests'] || 0,
|
|
1345
|
+
meterReads: counts['smarthome.meterReads'] || 0,
|
|
1346
|
+
statusReads: counts['smarthome.statusReads'] || 0,
|
|
1347
|
+
notifications: counts['smarthome.notifications'] || 0,
|
|
1348
|
+
},
|
|
1349
|
+
});
|
|
1350
|
+
if (payload === this.lastApiActivityPayload) {
|
|
1351
|
+
return;
|
|
1352
|
+
}
|
|
1353
|
+
this.lastApiActivityPayload = payload;
|
|
1354
|
+
void this.setState('info.apiActivity', payload, true);
|
|
1355
|
+
}
|
|
1356
|
+
/**
|
|
1357
|
+
* Opens the notification websocket of the Smart Home API as a safety net.
|
|
1358
|
+
*
|
|
1359
|
+
* The notifications carry no payload - they only say THAT something changed, and
|
|
1360
|
+
* they fire for every meter tick. Everything driven by buttons and scenes is
|
|
1361
|
+
* already reported precisely by the classic events, so the reaction here is a
|
|
1362
|
+
* hard rate-limited reconciliation (see DSSStructure.reconcileOutputValues): it
|
|
1363
|
+
* catches changes made past ioBroker, e.g. a third-party app writing an output
|
|
1364
|
+
* directly. The client reconnects on its own; a dSS without the websocket just
|
|
1365
|
+
* leaves the adapter running like before.
|
|
1366
|
+
*/
|
|
1367
|
+
startNotificationChannel() {
|
|
1368
|
+
if (!this.smartHome || !this.dssStruct) {
|
|
1369
|
+
return;
|
|
1370
|
+
}
|
|
1371
|
+
this.smartHome.on('statusChanged', () => {
|
|
1372
|
+
if (this.isStopping() || !this.dssStruct) {
|
|
1373
|
+
return;
|
|
1374
|
+
}
|
|
1375
|
+
if (this.dssStruct.reconcileOutputValues()) {
|
|
1376
|
+
this.log.debug('Smart Home notification: reconciling the output values');
|
|
1377
|
+
}
|
|
1378
|
+
});
|
|
1379
|
+
this.smartHome.on('structureChanged', () => {
|
|
1380
|
+
// The classic model_ready event reports the same and restarts the adapter
|
|
1381
|
+
this.log.debug('The dSS reports a structure change');
|
|
1382
|
+
});
|
|
1383
|
+
this.smartHome.on('notificationConnected', () => this.log.debug('Smart Home notification channel connected'));
|
|
1384
|
+
this.smartHome.on('notification', () => this.apiActivity && this.apiActivity.count('smarthome.notifications'));
|
|
1385
|
+
this.smartHome.startNotifications().then(() =>
|
|
1386
|
+
// A start that had nothing to do (stopping, or another start still
|
|
1387
|
+
// running) resolves without a socket - that is not an open channel
|
|
1388
|
+
this.smartHome && this.smartHome.websocket
|
|
1389
|
+
? this.log.info('Smart Home notification channel is active - changes made outside of ioBroker are reconciled automatically')
|
|
1390
|
+
: this.log.debug('Smart Home notification channel was not started'), err => this.log.info(`Smart Home notification channel is not available (${configUtils.errorMessage(err)}) - the adapter works without it and keeps retrying in the background`));
|
|
1391
|
+
}
|
|
1392
|
+
/**
|
|
1393
|
+
* Creates the client for the new Smart Home API, if it is switched on and configured.
|
|
1394
|
+
*
|
|
1395
|
+
* Returns null in every other case. The adapter then behaves exactly as before: the
|
|
1396
|
+
* classic API stays the fallback for everything, so a missing key or an unreachable
|
|
1397
|
+
* host must never keep the adapter from starting.
|
|
1398
|
+
*
|
|
1399
|
+
* @returns the client, or null when the classic API is used alone
|
|
1400
|
+
*/
|
|
1401
|
+
createSmartHomeClient() {
|
|
1402
|
+
if (!configUtils.normalizeBoolean(this.config.useSmartHomeApi, false)) {
|
|
1403
|
+
return null;
|
|
1404
|
+
}
|
|
1405
|
+
if (!this.config.smartHomeApiKey && !this.dss) {
|
|
1406
|
+
this.log.warn('The Smart Home API is switched on but there is neither an API key nor a connection to the ' +
|
|
1407
|
+
'classic interface - falling back to the classic API');
|
|
1408
|
+
return null;
|
|
1409
|
+
}
|
|
1410
|
+
if (!this.config.smartHomeApiKey) {
|
|
1411
|
+
// The new API also accepts the login of the classic interface (measured for
|
|
1412
|
+
// every endpoint this adapter reads and for the notification websocket), so
|
|
1413
|
+
// a key is a convenience, not a requirement
|
|
1414
|
+
this.log.info('No Smart Home API key configured - using the login of the classic interface for the new API');
|
|
1415
|
+
}
|
|
1416
|
+
// Same reasoning as for the app token: a value that is not a hex string usually
|
|
1417
|
+
// means js-controller could not decrypt it (e.g. after restoring a backup on
|
|
1418
|
+
// another host), and the dSS would only answer with an anonymous 401
|
|
1419
|
+
if (this.config.smartHomeApiKey && !Digitalstrom.looksLikeAppToken(this.config.smartHomeApiKey)) {
|
|
1420
|
+
this.log.error('The stored Smart Home API key does not look like a valid key (expected a long hex string). ' +
|
|
1421
|
+
'Please open the adapter configuration, create the API key again and save. ' +
|
|
1422
|
+
'The adapter tries to use it anyway.');
|
|
1423
|
+
}
|
|
1424
|
+
try {
|
|
1425
|
+
const client = new dssSmartHome_1.DSSSmartHome({
|
|
1426
|
+
host: this.config.host,
|
|
1427
|
+
apiKey: this.config.smartHomeApiKey,
|
|
1428
|
+
// The session of the classic client, renewed by it: serves without a
|
|
1429
|
+
// key, and catches a key the dSS revoked without taking the path down
|
|
1430
|
+
getSessionToken: this.dss
|
|
1431
|
+
? (forceRenew) => {
|
|
1432
|
+
const dss = this.dss;
|
|
1433
|
+
forceRenew && dss.invalidateSession();
|
|
1434
|
+
return dss.getSessionToken();
|
|
1435
|
+
}
|
|
1436
|
+
: undefined,
|
|
1437
|
+
validateCertificate: this.config.validateCertificate,
|
|
1438
|
+
onActivity: (kind, apiPath) => this.countSmartHomeActivity(kind, apiPath),
|
|
1439
|
+
logger: {
|
|
1440
|
+
silly: this.log.silly.bind(this),
|
|
1441
|
+
debug: this.log.debug.bind(this),
|
|
1442
|
+
info: this.log.info.bind(this),
|
|
1443
|
+
warn: this.log.warn.bind(this),
|
|
1444
|
+
error: this.log.error.bind(this),
|
|
1445
|
+
},
|
|
1446
|
+
});
|
|
1447
|
+
this.log.info('Smart Home API is active: meter values are read with one request instead of two per ' +
|
|
1448
|
+
'circuit, and device output values with one status request instead of one read per channel');
|
|
1449
|
+
return client;
|
|
1450
|
+
}
|
|
1451
|
+
catch (err) {
|
|
1452
|
+
this.log.warn(`Could not create the Smart Home API client (${configUtils.errorMessage(err)}) - falling back to the classic API`);
|
|
1453
|
+
return null;
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
/**
|
|
1457
|
+
* Validates the configured polling interval independently of the admin UI.
|
|
1458
|
+
* Invalid values must never produce an aggressive timer.
|
|
1459
|
+
*
|
|
1460
|
+
* @param configuredSeconds raw value from the instance config
|
|
1461
|
+
* @returns interval in ms, 0 means polling is disabled
|
|
1462
|
+
*/
|
|
1463
|
+
static normalizePollInterval(configuredSeconds) {
|
|
1464
|
+
if (configuredSeconds === undefined || configuredSeconds === null || configuredSeconds === '') {
|
|
1465
|
+
return DEFAULT_POLL_INTERVAL;
|
|
1466
|
+
}
|
|
1467
|
+
const seconds = Number(configuredSeconds);
|
|
1468
|
+
if (!Number.isFinite(seconds)) {
|
|
1469
|
+
return DEFAULT_POLL_INTERVAL;
|
|
1470
|
+
}
|
|
1471
|
+
if (seconds <= 0) {
|
|
1472
|
+
return 0; // explicitly disabled
|
|
1473
|
+
}
|
|
1474
|
+
return Math.min(Math.max(Math.round(seconds), MIN_POLL_INTERVAL_SECONDS), MAX_POLL_INTERVAL_SECONDS) * 1000;
|
|
1475
|
+
}
|
|
1476
|
+
initializeDSSData(callback) {
|
|
1477
|
+
const dss = this.dss;
|
|
1478
|
+
const dssStruct = this.dssStruct;
|
|
1479
|
+
if (!dss || !dssStruct) {
|
|
1480
|
+
return void (callback && callback('No DSS connection available'));
|
|
1481
|
+
}
|
|
1482
|
+
dss.requestAsync('system', 'version').then(dssVersion => {
|
|
1483
|
+
this.log.debug(`version: ${JSON.stringify(dssVersion)}`);
|
|
1484
|
+
dssStruct.init(err => {
|
|
1485
|
+
if (err) {
|
|
1486
|
+
return void (callback && callback(err));
|
|
1487
|
+
}
|
|
1488
|
+
callback && callback(null);
|
|
1489
|
+
});
|
|
1490
|
+
}, err => {
|
|
1491
|
+
this.log.error(`Error getVersion:${(err && err.message) || JSON.stringify(err)}`);
|
|
1492
|
+
callback && callback(err);
|
|
1493
|
+
});
|
|
1494
|
+
}
|
|
1495
|
+
startDataPolling(fromTimeout) {
|
|
1496
|
+
if (this.dataPollTimeout) {
|
|
1497
|
+
!fromTimeout && this.clearTimeout(this.dataPollTimeout);
|
|
1498
|
+
this.dataPollTimeout = null;
|
|
1499
|
+
}
|
|
1500
|
+
if (this.isStopping()) {
|
|
1501
|
+
return;
|
|
1502
|
+
}
|
|
1503
|
+
if (this.dataPollInterval === 0) {
|
|
1504
|
+
this.log.info('Data polling deactivated.');
|
|
1505
|
+
return;
|
|
1506
|
+
}
|
|
1507
|
+
const dssStruct = this.dssStruct;
|
|
1508
|
+
if (!dssStruct) {
|
|
1509
|
+
return;
|
|
1510
|
+
}
|
|
1511
|
+
dssStruct.updateMeterData((failed, total) => {
|
|
1512
|
+
if (this.isStopping()) {
|
|
1513
|
+
return;
|
|
1514
|
+
}
|
|
1515
|
+
// If every single meter request failed the DSS is most likely unreachable
|
|
1516
|
+
if (total > 0) {
|
|
1517
|
+
this.setConnected(failed < total);
|
|
1518
|
+
}
|
|
1519
|
+
this.dataPollTimeout = this.setTimeout(() => this.startDataPolling(true), this.dataPollInterval);
|
|
1520
|
+
});
|
|
1521
|
+
}
|
|
1522
|
+
/**
|
|
1523
|
+
* Makes sure the events are subscribed exactly once, and answers when they are.
|
|
1524
|
+
*
|
|
1525
|
+
* The subscription is started early, before the objects exist, so almost nothing is
|
|
1526
|
+
* lost while they are built. This is the authoritative attempt afterwards: if the
|
|
1527
|
+
* early one is still in flight it waits for it - firing nine more subscribes into a
|
|
1528
|
+
* running one buys nothing - and if the early one failed it tries again, because
|
|
1529
|
+
* failing the whole start on a transient early error would be a regression.
|
|
1530
|
+
*
|
|
1531
|
+
* @param callback receives null as soon as the events are subscribed, else the error
|
|
1532
|
+
*/
|
|
1533
|
+
ensureEventSubscription(callback) {
|
|
1534
|
+
if (!this.eventSubscriptionStarted) {
|
|
1535
|
+
return void this.initializeSubscriptions(callback);
|
|
1536
|
+
}
|
|
1537
|
+
const useResult = (err) => {
|
|
1538
|
+
if (err) {
|
|
1539
|
+
this.eventSubscriptionStarted = false;
|
|
1540
|
+
return void this.initializeSubscriptions(callback);
|
|
1541
|
+
}
|
|
1542
|
+
callback(null);
|
|
1543
|
+
};
|
|
1544
|
+
if (this.eventSubscriptionResult !== undefined) {
|
|
1545
|
+
return void useResult(this.eventSubscriptionResult);
|
|
1546
|
+
}
|
|
1547
|
+
this.eventSubscriptionWaiters.push(useResult);
|
|
1548
|
+
}
|
|
1549
|
+
/**
|
|
1550
|
+
* Starts the subscription before the objects exist. Errors are not fatal here - see
|
|
1551
|
+
* ensureEventSubscription(), which decides the start.
|
|
1552
|
+
*/
|
|
1553
|
+
startEarlyEventSubscription() {
|
|
1554
|
+
this.eventSubscriptionStarted = true;
|
|
1555
|
+
this.eventSubscriptionResult = undefined;
|
|
1556
|
+
this.initializeSubscriptions(err => {
|
|
1557
|
+
this.eventSubscriptionResult = err || null;
|
|
1558
|
+
const waiting = this.eventSubscriptionWaiters;
|
|
1559
|
+
this.eventSubscriptionWaiters = [];
|
|
1560
|
+
waiting.forEach(cb => cb(err || null));
|
|
1561
|
+
});
|
|
1562
|
+
}
|
|
1563
|
+
/**
|
|
1564
|
+
* Lets the early subscription count as failed, so the authoritative attempt subscribes
|
|
1565
|
+
* again instead of trusting a channel that is not delivering.
|
|
1566
|
+
*
|
|
1567
|
+
* @param err what the event channel reported, may be nothing usable
|
|
1568
|
+
*/
|
|
1569
|
+
failEarlyEventSubscription(err) {
|
|
1570
|
+
this.eventSubscriptionStarted = false;
|
|
1571
|
+
this.eventSubscriptionResult = undefined;
|
|
1572
|
+
const waiting = this.eventSubscriptionWaiters;
|
|
1573
|
+
this.eventSubscriptionWaiters = [];
|
|
1574
|
+
waiting.forEach(cb => cb(err));
|
|
1575
|
+
}
|
|
1576
|
+
initializeSubscriptions(callback) {
|
|
1577
|
+
const eventNames = Object.keys(dssConstants.availableEvents).filter(name => dssConstants.availableEvents[name]);
|
|
1578
|
+
if (!this.dss) {
|
|
1579
|
+
return void (callback && callback(new Error('No DSS connection available')));
|
|
1580
|
+
}
|
|
1581
|
+
// Handlers first, subscriptions second - see registerEventHandlers()
|
|
1582
|
+
this.registerEventHandlers(eventNames);
|
|
1583
|
+
this.dss.subscribeEvents(eventNames, errs => {
|
|
1584
|
+
let subscriptionError = null;
|
|
1585
|
+
if (errs && Array.isArray(errs) && errs.length) {
|
|
1586
|
+
this.log.warn(`Error to subscribe to ${errs.length} events. See the following log lines.`);
|
|
1587
|
+
errs.forEach((err, idx) => this.log.warn(`${idx}: ${(err && err.message) || err}`));
|
|
1588
|
+
subscriptionError = new Error(`${errs.length} of ${eventNames.length} event subscriptions failed: ${errs
|
|
1589
|
+
.map(err => (err && err.message) || err)
|
|
1590
|
+
.join('; ')}`);
|
|
1591
|
+
}
|
|
1592
|
+
else {
|
|
1593
|
+
this.log.debug(`Successfully subscribed to ${eventNames.length} Events`);
|
|
1594
|
+
}
|
|
1595
|
+
callback && callback(subscriptionError);
|
|
1596
|
+
});
|
|
1597
|
+
}
|
|
1598
|
+
/**
|
|
1599
|
+
* Registers all event handlers on the DSS client.
|
|
1600
|
+
*
|
|
1601
|
+
* This must happen BEFORE subscribeEvents() is called: all events share one
|
|
1602
|
+
* subscription id, and its long-poll starts as soon as the last subscription
|
|
1603
|
+
* succeeded - before subscribeEvents() answers its own callback. Registering the
|
|
1604
|
+
* handlers only in that callback would silently drop the events of the first poll,
|
|
1605
|
+
* and those events are consumed on the DSS and lost for good.
|
|
1606
|
+
*
|
|
1607
|
+
* Idempotent: a second call must not add a second set of listeners.
|
|
1608
|
+
*
|
|
1609
|
+
* @param eventNames all subscribed event names
|
|
1610
|
+
*/
|
|
1611
|
+
registerEventHandlers(eventNames) {
|
|
1612
|
+
if (this.eventHandlersRegistered || !this.dss || !this.dssStruct) {
|
|
1613
|
+
return;
|
|
1614
|
+
}
|
|
1615
|
+
this.eventHandlersRegistered = true;
|
|
1616
|
+
// Captured once: both are created together in main() and are never replaced
|
|
1617
|
+
// afterwards. The local constants also keep the handlers free of repeated null checks.
|
|
1618
|
+
const dss = this.dss;
|
|
1619
|
+
const dssStruct = this.dssStruct;
|
|
1620
|
+
dss.on('deviceSensorValue', this.parkable((data) => {
|
|
1621
|
+
this.eventLog(data.name, data, true);
|
|
1622
|
+
if (!data.source || !data.source.isDevice || data.properties.sensorValueFloat === undefined) {
|
|
1623
|
+
this.log.info(`--INVALID ${JSON.stringify(data)}`);
|
|
1624
|
+
return;
|
|
1625
|
+
}
|
|
1626
|
+
const sourceDeviceId = dssStruct.stateMap[`${data.source.dSUID}.sensors.${data.properties.sensorIndex}`];
|
|
1627
|
+
if (!sourceDeviceId) {
|
|
1628
|
+
this.log.info('INVALID Device Sensor update');
|
|
1629
|
+
return;
|
|
1630
|
+
}
|
|
1631
|
+
this.setDssState(sourceDeviceId, data.properties.sensorValueFloat);
|
|
1632
|
+
}));
|
|
1633
|
+
dss.on('deviceBinaryInputEvent', this.parkable((data) => {
|
|
1634
|
+
this.eventLog(data.name, data, true);
|
|
1635
|
+
if (!data.source || !data.source.isDevice || data.properties.inputType === undefined) {
|
|
1636
|
+
this.log.info(`--INVALID ${JSON.stringify(data)}`);
|
|
1637
|
+
return;
|
|
1638
|
+
}
|
|
1639
|
+
const sourceDeviceId = dssStruct.stateMap[`${data.source.dSUID}.binaryInputs.${data.properties.inputIndex}`];
|
|
1640
|
+
if (!sourceDeviceId) {
|
|
1641
|
+
this.log.info('INVALID Device Binary input event');
|
|
1642
|
+
return;
|
|
1643
|
+
}
|
|
1644
|
+
this.setDssState(sourceDeviceId, parseInt(data.properties.inputState, 10) + 1);
|
|
1645
|
+
}));
|
|
1646
|
+
const handleStateChange = (data) => {
|
|
1647
|
+
this.eventLog(data.name, data, true);
|
|
1648
|
+
if (!data.properties || !data.properties.statename) {
|
|
1649
|
+
this.log.info(`--INVALID ${JSON.stringify(data)}`);
|
|
1650
|
+
return;
|
|
1651
|
+
}
|
|
1652
|
+
const statename = data.properties.statename;
|
|
1653
|
+
const sourceDeviceId = dssStruct.stateMap[statename];
|
|
1654
|
+
if (!sourceDeviceId) {
|
|
1655
|
+
// Helper states of dSS addons (e.g. "<dsuid>_open-tilded" of the
|
|
1656
|
+
// window-states addon, "queue-active" of the climate control) have no
|
|
1657
|
+
// ioBroker object by design - the window state itself arrives via binary
|
|
1658
|
+
// input and device state. Any other state is named once per run, an addon
|
|
1659
|
+
// state as well - "operationmode.3.NotUsed" of the climate control used to
|
|
1660
|
+
// stay at debug although nothing maps it: the first line says what is
|
|
1661
|
+
// missing, every repeat is noise. A room crossing its passive cooling
|
|
1662
|
+
// threshold repeated the same line four times in five hours. stateMap is
|
|
1663
|
+
// built at startup, so a state the dSS added since then (a new user state,
|
|
1664
|
+
// a room put under regulation) only needs a restart, not an issue.
|
|
1665
|
+
if (Digitalstrom.isAddonHelperState(statename) || this.unhandledStateNames.has(statename)) {
|
|
1666
|
+
this.log.debug(`Unhandled State Change: ${statename}`);
|
|
1667
|
+
}
|
|
1668
|
+
else {
|
|
1669
|
+
this.unhandledStateNames.add(statename);
|
|
1670
|
+
this.log.info(`Unhandled State Change: ${statename} - the DSS reports a state this adapter has no object for. A state added in the DSS after the adapter started gets its object at the next start of the adapter; if the name is still reported after a restart, please report it in a GitHub issue so it can be mapped. Further changes of it are logged at debug level.`);
|
|
1671
|
+
}
|
|
1672
|
+
return;
|
|
1673
|
+
}
|
|
1674
|
+
// The valueTrue/valueFalse mapping of the state is applied by setDssState()
|
|
1675
|
+
this.setDssState(sourceDeviceId, data.properties.state);
|
|
1676
|
+
};
|
|
1677
|
+
// One wrapper for both names, so the two share a single parked identity
|
|
1678
|
+
const parkedStateChange = this.parkable(handleStateChange);
|
|
1679
|
+
dss.on('stateChange', parkedStateChange);
|
|
1680
|
+
dss.on('addonStateChange', parkedStateChange);
|
|
1681
|
+
dss.on('buttonClick', this.liveOnly((data) => {
|
|
1682
|
+
this.eventLog(data.name, data, true);
|
|
1683
|
+
if (!data.source || !data.source.isDevice) {
|
|
1684
|
+
this.log.info(`--INVALID ${JSON.stringify(data)}`);
|
|
1685
|
+
return;
|
|
1686
|
+
}
|
|
1687
|
+
const buttonIndex = data.properties.buttonIndex ? data.properties.buttonIndex - 1 : 0;
|
|
1688
|
+
if (!dssStruct.stateMap[`${data.source.dSUID}.${buttonIndex}.button`]) {
|
|
1689
|
+
this.log.info('INVALID Button click');
|
|
1690
|
+
return;
|
|
1691
|
+
}
|
|
1692
|
+
void this.setState(dssStruct.stateMap[`${data.source.dSUID}.${buttonIndex}.button`], true, true);
|
|
1693
|
+
this.releaseMomentaryState(dssStruct.stateMap[`${data.source.dSUID}.${buttonIndex}.button`]);
|
|
1694
|
+
// setDssState, not setState: the DSS delivers the click type and the hold count as
|
|
1695
|
+
// strings while both objects are declared as numbers. The ids can be missing on
|
|
1696
|
+
// devices that only have the plain button state.
|
|
1697
|
+
const clickTypeId = dssStruct.stateMap[`${data.source.dSUID}.${buttonIndex}.buttonClickType`];
|
|
1698
|
+
clickTypeId && this.setDssState(clickTypeId, data.properties.clickType ?? -1);
|
|
1699
|
+
const holdCountId = dssStruct.stateMap[`${data.source.dSUID}.${buttonIndex}.buttonHoldCount`];
|
|
1700
|
+
holdCountId && this.setDssState(holdCountId, data.properties.holdCount ?? 0);
|
|
1701
|
+
}));
|
|
1702
|
+
dss.on('zoneSensorValue', this.parkable((data) => {
|
|
1703
|
+
this.eventLog(data.name, data, true);
|
|
1704
|
+
if (!data.source ||
|
|
1705
|
+
!data.properties ||
|
|
1706
|
+
!data.properties.sensorType ||
|
|
1707
|
+
data.properties.sensorValueFloat === undefined) {
|
|
1708
|
+
this.log.info(`--INVALID ${JSON.stringify(data)}`);
|
|
1709
|
+
return;
|
|
1710
|
+
}
|
|
1711
|
+
let sourceDeviceId = dssStruct.stateMap[`${data.source.zoneID}.sensors.${data.properties.sensorType}`];
|
|
1712
|
+
if (!sourceDeviceId && data.properties.sensorType === 60) {
|
|
1713
|
+
sourceDeviceId = dssStruct.stateMap['0.sensors.60'];
|
|
1714
|
+
}
|
|
1715
|
+
if (!sourceDeviceId) {
|
|
1716
|
+
this.log.info(`INVALID Zone Sensor update: ${data.source.zoneID}.sensors.${data.properties.sensorType}`);
|
|
1717
|
+
return;
|
|
1718
|
+
}
|
|
1719
|
+
this.setDssState(sourceDeviceId, data.properties.sensorValueFloat);
|
|
1720
|
+
}));
|
|
1721
|
+
/**
|
|
1722
|
+
* Hands a scene event to the device handlers of the affected devices.
|
|
1723
|
+
*
|
|
1724
|
+
* zoneDevices is keyed by the real device groups (1, 2, 8 ...) only - the DSS never
|
|
1725
|
+
* lists a device in the broadcast group 0. A scene called for a whole room therefore
|
|
1726
|
+
* arrives with groupID "0" and has to be fanned out over every group of that room,
|
|
1727
|
+
* exactly like the apartment wide broadcast does.
|
|
1728
|
+
*
|
|
1729
|
+
* @param zoneId zone of the scene event
|
|
1730
|
+
* @param groupId group of the scene event, "0" means the whole room
|
|
1731
|
+
* @param data the scene event itself
|
|
1732
|
+
*/
|
|
1733
|
+
const emitSceneToDevices = (zoneId, groupId, data) => {
|
|
1734
|
+
const groups = dssStruct.zoneDevices[zoneId];
|
|
1735
|
+
if (!groups) {
|
|
1736
|
+
return;
|
|
1737
|
+
}
|
|
1738
|
+
if (String(groupId) !== '0') {
|
|
1739
|
+
(groups[groupId] || []).forEach(dSUID => dss.emit(dSUID, data));
|
|
1740
|
+
return;
|
|
1741
|
+
}
|
|
1742
|
+
const handledDevices = {};
|
|
1743
|
+
Object.keys(groups).forEach(group => groups[group].forEach(dSUID => {
|
|
1744
|
+
if (!handledDevices[dSUID]) {
|
|
1745
|
+
handledDevices[dSUID] = true;
|
|
1746
|
+
dss.emit(dSUID, data);
|
|
1747
|
+
}
|
|
1748
|
+
}));
|
|
1749
|
+
};
|
|
1750
|
+
const handleScene = (data, value, forwarded) => {
|
|
1751
|
+
this.eventLog(data.name + (forwarded ? ' (forwarded)' : ''), data, true);
|
|
1752
|
+
if (!data.source) {
|
|
1753
|
+
this.log.info(`--INVALID ${JSON.stringify(data)}`);
|
|
1754
|
+
return;
|
|
1755
|
+
}
|
|
1756
|
+
let sourceDeviceId;
|
|
1757
|
+
let lastSourceDeviceId;
|
|
1758
|
+
if (data.source.isDevice) {
|
|
1759
|
+
sourceDeviceId = dssStruct.stateMap[`${data.source.dSUID}.scenes.${data.properties.sceneID}`];
|
|
1760
|
+
if (this.lastScenes[data.source.dSUID] !== undefined) {
|
|
1761
|
+
lastSourceDeviceId =
|
|
1762
|
+
dssStruct.stateMap[`${data.source.dSUID}.scenes.${this.lastScenes[data.source.dSUID]}`];
|
|
1763
|
+
}
|
|
1764
|
+
if (value) {
|
|
1765
|
+
this.lastScenes[data.source.dSUID] = data.properties.sceneID;
|
|
1766
|
+
}
|
|
1767
|
+
else {
|
|
1768
|
+
this.lastScenes[data.source.dSUID] = undefined;
|
|
1769
|
+
}
|
|
1770
|
+
dss.emit(data.source.dSUID, data);
|
|
1771
|
+
}
|
|
1772
|
+
else if (data.source.isGroup && (data.properties.zoneID !== '0' || data.properties.groupID !== '0')) {
|
|
1773
|
+
sourceDeviceId =
|
|
1774
|
+
dssStruct.stateMap[`${data.properties.zoneID}.${data.properties.groupID}.scenes.${data.properties.sceneID}`];
|
|
1775
|
+
if (this.lastScenes[`${data.properties.zoneID}.${data.properties.groupID}`] !== undefined) {
|
|
1776
|
+
lastSourceDeviceId =
|
|
1777
|
+
dssStruct.stateMap[`${data.properties.zoneID}.${data.properties.groupID}.scenes.${this.lastScenes[`${data.properties.zoneID}.${data.properties.groupID}`]}`];
|
|
1778
|
+
}
|
|
1779
|
+
if (value) {
|
|
1780
|
+
this.lastScenes[`${data.properties.zoneID}.${data.properties.groupID}`] = data.properties.sceneID;
|
|
1781
|
+
}
|
|
1782
|
+
else {
|
|
1783
|
+
this.lastScenes[`${data.properties.zoneID}.${data.properties.groupID}`] = undefined;
|
|
1784
|
+
}
|
|
1785
|
+
// No initializeOutputValues check here: the device handlers also apply the
|
|
1786
|
+
// scene preset values (usePresetValues) and gate the real DSS read on that
|
|
1787
|
+
// option themselves.
|
|
1788
|
+
if (!forwarded) {
|
|
1789
|
+
emitSceneToDevices(data.properties.zoneID, data.properties.groupID, data);
|
|
1790
|
+
}
|
|
1791
|
+
}
|
|
1792
|
+
else if (data.source.isApartment ||
|
|
1793
|
+
(data.source.isGroup && data.properties.zoneID === '0' && data.properties.groupID === '0')) {
|
|
1794
|
+
sourceDeviceId = dssStruct.stateMap[`0.0.scenes.${data.properties.sceneID}`];
|
|
1795
|
+
if (this.lastScenes['0.0'] !== undefined) {
|
|
1796
|
+
lastSourceDeviceId = dssStruct.stateMap[`0.0.scenes.${this.lastScenes['0.0']}`];
|
|
1797
|
+
}
|
|
1798
|
+
if (value) {
|
|
1799
|
+
this.lastScenes['0.0'] = data.properties.sceneID;
|
|
1800
|
+
}
|
|
1801
|
+
else {
|
|
1802
|
+
this.lastScenes['0.0'] = undefined;
|
|
1803
|
+
}
|
|
1804
|
+
if (!forwarded) {
|
|
1805
|
+
const handledDevices = {};
|
|
1806
|
+
Object.keys(dssStruct.zoneDevices).forEach(zoneId => {
|
|
1807
|
+
Object.keys(dssStruct.zoneDevices[zoneId]).forEach(groupId => {
|
|
1808
|
+
dssStruct.zoneDevices[zoneId][groupId].forEach(dSUID => {
|
|
1809
|
+
if (!handledDevices[dSUID]) {
|
|
1810
|
+
dss.emit(dSUID, data);
|
|
1811
|
+
handledDevices[dSUID] = true;
|
|
1812
|
+
}
|
|
1813
|
+
});
|
|
1814
|
+
});
|
|
1815
|
+
});
|
|
1816
|
+
}
|
|
1817
|
+
}
|
|
1818
|
+
if (sourceDeviceId) {
|
|
1819
|
+
this.setDssState(sourceDeviceId, value);
|
|
1820
|
+
lastSourceDeviceId &&
|
|
1821
|
+
lastSourceDeviceId !== sourceDeviceId &&
|
|
1822
|
+
value &&
|
|
1823
|
+
this.setDssState(lastSourceDeviceId, false);
|
|
1824
|
+
const idArr = sourceDeviceId.split('.');
|
|
1825
|
+
idArr[idArr.length - 1] = 'sceneId';
|
|
1826
|
+
const sceneIdState = idArr.join('.');
|
|
1827
|
+
if (value) {
|
|
1828
|
+
this.setDssState(sceneIdState, data.properties.sceneID);
|
|
1829
|
+
}
|
|
1830
|
+
else {
|
|
1831
|
+
this.setDssState(sceneIdState, null);
|
|
1832
|
+
}
|
|
1833
|
+
// A Stop, an Increment or an Impulse is a command, not a preset, and the
|
|
1834
|
+
// dSS never sends the undoScene that would release it again - the state
|
|
1835
|
+
// would stay true from the first press to the end of the run. sceneId is
|
|
1836
|
+
// deliberately NOT released: it keeps answering "the last scene called
|
|
1837
|
+
// here was Stop", with its own timestamp.
|
|
1838
|
+
// The scene and group are read HERE, synchronously: the zone-wide and
|
|
1839
|
+
// apartment-wide expansion further down mutates data.properties, so a
|
|
1840
|
+
// callback reading them later would see the last group of that loop.
|
|
1841
|
+
if (value && Digitalstrom.isMomentaryScene(data.properties.sceneID, data.properties.groupID)) {
|
|
1842
|
+
this.releaseMomentaryState(sourceDeviceId);
|
|
1843
|
+
}
|
|
1844
|
+
// The room temperature control is switched through the scenes of group 48.
|
|
1845
|
+
// Keep the readable operation mode of that room in sync with them.
|
|
1846
|
+
if (value && String(data.properties.groupID) === '48') {
|
|
1847
|
+
const operationModeState = dssStruct.stateMap[`${data.properties.zoneID}.48.operationMode`];
|
|
1848
|
+
operationModeState && this.setDssState(operationModeState, data.properties.sceneID);
|
|
1849
|
+
}
|
|
1850
|
+
}
|
|
1851
|
+
else if (!forwarded) {
|
|
1852
|
+
this.logUnmappedSceneCall(data);
|
|
1853
|
+
}
|
|
1854
|
+
// When Scene is called on zone level we also update all groups in that zone
|
|
1855
|
+
if (data.source.isGroup && data.properties.zoneID !== '0' && data.properties.groupID === '0') {
|
|
1856
|
+
if (dssStruct.zoneDevices[data.properties.zoneID]) {
|
|
1857
|
+
Object.keys(dssStruct.zoneDevices[data.properties.zoneID]).forEach(group => {
|
|
1858
|
+
data.properties.groupID = group.toString();
|
|
1859
|
+
handleScene(data, value, true);
|
|
1860
|
+
});
|
|
1861
|
+
}
|
|
1862
|
+
}
|
|
1863
|
+
else if (data.source.isGroup && data.properties.zoneID === '0' && data.properties.groupID === '0') {
|
|
1864
|
+
dssStruct.apartmentStructure.zones.forEach((zone) => {
|
|
1865
|
+
if (!dssStruct.zoneDevices[zone.id]) {
|
|
1866
|
+
return;
|
|
1867
|
+
}
|
|
1868
|
+
data.properties.zoneID = zone.id.toString();
|
|
1869
|
+
Object.keys(dssStruct.zoneDevices[zone.id]).forEach(group => {
|
|
1870
|
+
data.properties.groupID = group.toString();
|
|
1871
|
+
handleScene(data, value, true);
|
|
1872
|
+
});
|
|
1873
|
+
});
|
|
1874
|
+
}
|
|
1875
|
+
//console.log('Check Button: ' + dssStruct.stateMap[data.properties.originDSUID + '.0.button']);
|
|
1876
|
+
// A press is a moment, not a level: the dSS reports it and never takes it back,
|
|
1877
|
+
// so the state used to stay true from the first press to the end of the run -
|
|
1878
|
+
// the same defect the momentary scenes had, on the state right next to them.
|
|
1879
|
+
if (!forwarded && data.properties.callOrigin === '9') {
|
|
1880
|
+
if (data.properties.originDSUID && dssStruct.stateMap[`${data.properties.originDSUID}.0.button`]) {
|
|
1881
|
+
void this.setState(dssStruct.stateMap[`${data.properties.originDSUID}.0.button`], true, true);
|
|
1882
|
+
this.releaseMomentaryState(dssStruct.stateMap[`${data.properties.originDSUID}.0.button`]);
|
|
1883
|
+
void (dssStruct.stateMap[`${data.properties.originDSUID}.0.buttonClickType`] &&
|
|
1884
|
+
this.setState(dssStruct.stateMap[`${data.properties.originDSUID}.0.buttonClickType`], 0, true));
|
|
1885
|
+
void (dssStruct.stateMap[`${data.properties.originDSUID}.0.buttonHoldCount`] &&
|
|
1886
|
+
this.setState(dssStruct.stateMap[`${data.properties.originDSUID}.0.buttonHoldCount`], 0, true));
|
|
1887
|
+
}
|
|
1888
|
+
else if (data.source.dSUID && dssStruct.stateMap[`${data.source.dSUID}.0.button`]) {
|
|
1889
|
+
void this.setState(dssStruct.stateMap[`${data.source.dSUID}.0.button`], true, true);
|
|
1890
|
+
this.releaseMomentaryState(dssStruct.stateMap[`${data.source.dSUID}.0.button`]);
|
|
1891
|
+
void (dssStruct.stateMap[`${data.source.dSUID}.0.buttonClickType`] &&
|
|
1892
|
+
this.setState(dssStruct.stateMap[`${data.source.dSUID}.0.buttonClickType`], 0, true));
|
|
1893
|
+
void (dssStruct.stateMap[`${data.source.dSUID}.0.buttonHoldCount`] &&
|
|
1894
|
+
this.setState(dssStruct.stateMap[`${data.source.dSUID}.0.buttonHoldCount`], 0, true));
|
|
1895
|
+
}
|
|
1896
|
+
}
|
|
1897
|
+
};
|
|
1898
|
+
dss.on('callScene', this.liveOnly((data) => handleScene(data, true)));
|
|
1899
|
+
dss.on('undoScene', this.liveOnly((data) => handleScene(data, false)));
|
|
1900
|
+
dss.on('eventError', (eventName, errorCount, err) => {
|
|
1901
|
+
if (this.pendingEvents) {
|
|
1902
|
+
// The objects do not exist yet. Restarting here would loop an adapter that
|
|
1903
|
+
// never writes a single value - before the early subscription this state
|
|
1904
|
+
// could not be reached at all. The subscription counts as failed instead,
|
|
1905
|
+
// so the authoritative attempt after the initial values tries again.
|
|
1906
|
+
this.log.warn(`Event polling errors (${eventName}) while the objects were being created: ${err} - subscribing again after the startup`);
|
|
1907
|
+
this.failEarlyEventSubscription(configUtils.asError(err));
|
|
1908
|
+
return;
|
|
1909
|
+
}
|
|
1910
|
+
this.log.warn(`Too many event polling errors (${eventName}): ${err} - restarting adapter`);
|
|
1911
|
+
this.setConnected(false);
|
|
1912
|
+
this.restartAdapter(2000, `of too many event polling errors (${eventName})`);
|
|
1913
|
+
});
|
|
1914
|
+
dss.on('model_ready', () => {
|
|
1915
|
+
// The DSS finished (re-)initializing its apartment model, e.g. after a DSS
|
|
1916
|
+
// restart or structure change - restart to resync structure and subscriptions
|
|
1917
|
+
this.log.info('DSS apartment model was (re-)initialized (model_ready event) - restarting adapter to resync the structure');
|
|
1918
|
+
if (this.pendingEvents) {
|
|
1919
|
+
// Since the subscription moved to the front this can arrive WHILE the
|
|
1920
|
+
// objects are being created, which it never could before. Restarting in
|
|
1921
|
+
// the middle of that would throw away a structure that is half built and,
|
|
1922
|
+
// if the dSS keeps re-initializing, would loop without ever writing a
|
|
1923
|
+
// value. The structure being read right now is stale either way, so the
|
|
1924
|
+
// restart is remembered and done once the startup is through.
|
|
1925
|
+
this.pendingModelReady = true;
|
|
1926
|
+
return;
|
|
1927
|
+
}
|
|
1928
|
+
this.restartAdapter(10000, 'the dSS re-initialized its apartment model (model_ready)');
|
|
1929
|
+
});
|
|
1930
|
+
// Log unhandled Events to see what happens so at all
|
|
1931
|
+
eventNames.forEach(eventName => dss.listenerCount(eventName) === 0 &&
|
|
1932
|
+
dss.on(eventName, (data) => this.eventLog(eventName, data, false)));
|
|
1933
|
+
}
|
|
1934
|
+
/**
|
|
1935
|
+
* Converts a single DSS value to the type declared for the ioBroker object.
|
|
1936
|
+
*
|
|
1937
|
+
* The DSS delivers numeric values as strings in many places, so js-controller would
|
|
1938
|
+
* otherwise complain about the type of every sensor value, scene id and state.
|
|
1939
|
+
*
|
|
1940
|
+
* @param id ID of the state
|
|
1941
|
+
* @param value value as the DSS delivered it
|
|
1942
|
+
* @returns value converted to the declared type
|
|
1943
|
+
*/
|
|
1944
|
+
coerceScalarValue(id, value) {
|
|
1945
|
+
if (value === null || value === undefined) {
|
|
1946
|
+
return null;
|
|
1947
|
+
}
|
|
1948
|
+
const obj = this.dssStruct && this.dssStruct.dssObjects && this.dssStruct.dssObjects[id];
|
|
1949
|
+
const type = obj && obj.common && obj.common.type;
|
|
1950
|
+
if (type === 'number' && typeof value !== 'number') {
|
|
1951
|
+
// Whatever the DSS delivered is read as text first, exactly like parseFloat() would
|
|
1952
|
+
// eslint-disable-next-line @typescript-eslint/no-base-to-string
|
|
1953
|
+
const numeric = parseFloat(String(value));
|
|
1954
|
+
return Number.isNaN(numeric) ? null : numeric;
|
|
1955
|
+
}
|
|
1956
|
+
if (type === 'boolean' && typeof value !== 'boolean') {
|
|
1957
|
+
// Prefer the value mapping the DSS reported for this state
|
|
1958
|
+
const native = (obj && obj.native) || {};
|
|
1959
|
+
if (native.valueTrue !== undefined && value === native.valueTrue) {
|
|
1960
|
+
return true;
|
|
1961
|
+
}
|
|
1962
|
+
if (native.valueFalse !== undefined && value === native.valueFalse) {
|
|
1963
|
+
return false;
|
|
1964
|
+
}
|
|
1965
|
+
if (value === dssStructure_1.DSSStructure.UNKNOWN_STATE_WORD) {
|
|
1966
|
+
// The dSS has no information about this state (see UNKNOWN_STATE_WORD). It
|
|
1967
|
+
// creates the room state heating as unknown, and a dSS20 1.19.13 answers
|
|
1968
|
+
// zone.<id>.heating like that in all eight rooms of a real installation,
|
|
1969
|
+
// five of them with a running temperature control. That is neither true nor
|
|
1970
|
+
// false, and no stale vocabulary either, so it is not reported: the state
|
|
1971
|
+
// gets no value, and the next "active"/"inactive" sets it again. The
|
|
1972
|
+
// toBoolean fallback made it true - "heating active" in eight rooms at
|
|
1973
|
+
// once, plus eight warnings per start. It sits behind the vocabulary
|
|
1974
|
+
// matches on purpose, so a state that declares the word itself still wins.
|
|
1975
|
+
return null;
|
|
1976
|
+
}
|
|
1977
|
+
if (native.valueTrue !== undefined || native.valueFalse !== undefined) {
|
|
1978
|
+
// This is the only signal that a declared vocabulary has gone stale, and it
|
|
1979
|
+
// sat on debug: on a real installation it fired five times at startup and
|
|
1980
|
+
// nobody ever saw it. It warns once per state now - the value itself still
|
|
1981
|
+
// comes out right through the toBoolean fallback, so this is a report worth
|
|
1982
|
+
// filing, not a failure. Once per state, because a state that keeps sending
|
|
1983
|
+
// the unknown word must not fill the log with it.
|
|
1984
|
+
if (!this.unmappedBooleanStates.has(id)) {
|
|
1985
|
+
this.unmappedBooleanStates.add(id);
|
|
1986
|
+
this.log.warn(
|
|
1987
|
+
// The raw DSS value is logged as it arrived
|
|
1988
|
+
// eslint-disable-next-line @typescript-eslint/no-base-to-string, @typescript-eslint/restrict-template-expressions
|
|
1989
|
+
`Unmapped value "${value}" for boolean state ${id} (expected "${native.valueTrue}"/"${native.valueFalse}") - the value was interpreted, please report this state and value so the mapping can be corrected`);
|
|
1990
|
+
}
|
|
1991
|
+
}
|
|
1992
|
+
return dssStructure_1.DSSStructure.toBoolean(value);
|
|
1993
|
+
}
|
|
1994
|
+
if (type === 'string' && typeof value !== 'string') {
|
|
1995
|
+
// A text state takes whatever the DSS delivered as text
|
|
1996
|
+
// eslint-disable-next-line @typescript-eslint/no-base-to-string
|
|
1997
|
+
return String(value);
|
|
1998
|
+
}
|
|
1999
|
+
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
|
2000
|
+
return value;
|
|
2001
|
+
}
|
|
2002
|
+
// Everything else (objects, arrays, functions) has no representation as a state value
|
|
2003
|
+
return null;
|
|
2004
|
+
}
|
|
2005
|
+
/**
|
|
2006
|
+
* Converts a value that came from the DSS for writing it into a state.
|
|
2007
|
+
*
|
|
2008
|
+
* Beside plain values the adapter also passes whole state objects around: the outdoor
|
|
2009
|
+
* sensors carry the timestamp of the DSS, which has to be preserved. Only the value
|
|
2010
|
+
* itself is converted in that case.
|
|
2011
|
+
*
|
|
2012
|
+
* @param id ID of the state
|
|
2013
|
+
* @param value value or whole state as the DSS delivered it
|
|
2014
|
+
* @returns converted value, undefined stays undefined
|
|
2015
|
+
*/
|
|
2016
|
+
coerceStateValue(id, value) {
|
|
2017
|
+
if (value === undefined) {
|
|
2018
|
+
// Kept as undefined on purpose: the callers use it as "no value at all"
|
|
2019
|
+
return undefined;
|
|
2020
|
+
}
|
|
2021
|
+
if (value === null) {
|
|
2022
|
+
return null;
|
|
2023
|
+
}
|
|
2024
|
+
if (typeof value === 'object' && !Array.isArray(value) && 'val' in value && value.val !== undefined) {
|
|
2025
|
+
const state = value;
|
|
2026
|
+
return { ...state, val: this.coerceScalarValue(id, state.val) };
|
|
2027
|
+
}
|
|
2028
|
+
return this.coerceScalarValue(id, value);
|
|
2029
|
+
}
|
|
2030
|
+
/**
|
|
2031
|
+
* Writes an acknowledged value that came from the DSS, converted to the declared type.
|
|
2032
|
+
*
|
|
2033
|
+
* @param id ID of the state
|
|
2034
|
+
* @param value value or whole state as the DSS delivered it
|
|
2035
|
+
*/
|
|
2036
|
+
setDssState(id, value) {
|
|
2037
|
+
if (!id) {
|
|
2038
|
+
return;
|
|
2039
|
+
}
|
|
2040
|
+
const converted = this.coerceStateValue(id, value);
|
|
2041
|
+
if (converted === undefined) {
|
|
2042
|
+
// Writing undefined would only produce a js-controller warning, same as in
|
|
2043
|
+
// DSSStructure.setStateSafe()
|
|
2044
|
+
return;
|
|
2045
|
+
}
|
|
2046
|
+
// Everything the dSS reports comes through here - that is what keeps the known
|
|
2047
|
+
// value of a user state current, see DSSStructure.noteUserStateValue()
|
|
2048
|
+
if (this.dssStruct && typeof this.dssStruct.noteUserStateValue === 'function') {
|
|
2049
|
+
this.dssStruct.noteUserStateValue(id, converted);
|
|
2050
|
+
}
|
|
2051
|
+
// What is in the state now - the polling paths compare against this before they
|
|
2052
|
+
// re-assert a value that has not moved, see DSSStructure.setStateSafe()
|
|
2053
|
+
if (this.dssStruct && typeof this.dssStruct.notePublishedValue === 'function') {
|
|
2054
|
+
this.dssStruct.notePublishedValue(id, converted);
|
|
2055
|
+
}
|
|
2056
|
+
void this.setState(id, converted, true);
|
|
2057
|
+
}
|
|
2058
|
+
eventLog(eventName, event, handled) {
|
|
2059
|
+
this.log.debug(`${handled ? '' : 'UNHANDLED '}EVENT: ${eventName}: ${JSON.stringify(event)}`);
|
|
2060
|
+
}
|
|
2061
|
+
/**
|
|
2062
|
+
* Undoes the HTML escaping that older dSS firmware applied to every name it stored, see
|
|
2063
|
+
* DSSStructure.decodeDssEntities(). The structure applies it to every name it builds,
|
|
2064
|
+
* so the names handed to registerObjects() are already decoded.
|
|
2065
|
+
*
|
|
2066
|
+
* @param text name as it was stored
|
|
2067
|
+
* @returns the name as it was typed in the dSS
|
|
2068
|
+
*/
|
|
2069
|
+
static decodeDssEntities(text) {
|
|
2070
|
+
return dssStructure_1.DSSStructure.decodeDssEntities(text);
|
|
2071
|
+
}
|
|
2072
|
+
/**
|
|
2073
|
+
* True when the stored name is nothing but the old dSS escaping of today's name.
|
|
2074
|
+
*
|
|
2075
|
+
* Nobody chose such a name, so it may be replaced. Any other difference is a rename by
|
|
2076
|
+
* the user, and that one is kept.
|
|
2077
|
+
*
|
|
2078
|
+
* @param storedName common.name of the existing object
|
|
2079
|
+
* @param wantedName name the dSS reports now
|
|
2080
|
+
* @returns true if the stored name has to be replaced once
|
|
2081
|
+
*/
|
|
2082
|
+
static isDssEscapedName(storedName, wantedName) {
|
|
2083
|
+
return (typeof storedName === 'string' &&
|
|
2084
|
+
typeof wantedName === 'string' &&
|
|
2085
|
+
storedName !== wantedName &&
|
|
2086
|
+
Digitalstrom.decodeDssEntities(storedName) === wantedName);
|
|
2087
|
+
}
|
|
2088
|
+
registerObjects() {
|
|
2089
|
+
const dssStruct = this.dssStruct;
|
|
2090
|
+
if (!dssStruct) {
|
|
2091
|
+
return;
|
|
2092
|
+
}
|
|
2093
|
+
// Read before the loop: setOrUpdateObject() removes every object it is handed from
|
|
2094
|
+
// this list, whatever is left afterwards is deleted as unknown
|
|
2095
|
+
const existing = this.objectHelper.existingStates || {};
|
|
2096
|
+
const objNames = Object.keys(dssStruct.dssObjects);
|
|
2097
|
+
this.log.info(`Create ${objNames.length} objects ...`);
|
|
2098
|
+
objNames.forEach(id => {
|
|
2099
|
+
const obj = dssStruct.dssObjects[id];
|
|
2100
|
+
// The DSS delivers e.g. state values as strings - the object is created with its
|
|
2101
|
+
// declared type right away, so the initial value has to match it.
|
|
2102
|
+
const initValue = this.coerceStateValue(id, obj.value);
|
|
2103
|
+
const onChange = obj.onChange;
|
|
2104
|
+
delete obj.value;
|
|
2105
|
+
delete obj.onChange;
|
|
2106
|
+
// common.write is mandatory for a state, and a missing one is read differently:
|
|
2107
|
+
// the admin offers to edit the state, the type detector treats it as read-only.
|
|
2108
|
+
// Writable is exactly what has a write handler. It is decided HERE because only
|
|
2109
|
+
// now is the handler final - the light, shade and single channel paths hang it
|
|
2110
|
+
// onto the generic output channel after addStateObject, and the objectHelper
|
|
2111
|
+
// keeps an explicit flag, so an earlier false could never become true again.
|
|
2112
|
+
// An explicit flag of the definition stays as it is.
|
|
2113
|
+
if (obj.type === 'state' && obj.common && typeof obj.common.write !== 'boolean') {
|
|
2114
|
+
obj.common.write = typeof onChange === 'function';
|
|
2115
|
+
}
|
|
2116
|
+
// The stored name normally wins, the user may have renamed the object. An object
|
|
2117
|
+
// created while the dSS still escaped its names kept "Schlafen & Bad" that way
|
|
2118
|
+
// forever. That name is written ONCE - from the next start on both are equal and
|
|
2119
|
+
// the stored name wins again. The dSS may still answer with the escaped name
|
|
2120
|
+
// (it keeps what old firmware stored), so the wanted name is decoded by the
|
|
2121
|
+
// structure first; otherwise both would be equal and nothing would be repaired.
|
|
2122
|
+
const storedName = existing[id] && existing[id].common ? existing[id].common.name : undefined;
|
|
2123
|
+
const repairName = Digitalstrom.isDssEscapedName(storedName, obj.common && obj.common.name);
|
|
2124
|
+
if (repairName) {
|
|
2125
|
+
this.log.info(`Name of ${id} corrected from "${storedName}" to "${obj.common.name}"`);
|
|
2126
|
+
}
|
|
2127
|
+
this.objectHelper.setOrUpdateObject(id, obj, repairName ? [] : ['name'], initValue, onChange);
|
|
2128
|
+
});
|
|
2129
|
+
}
|
|
2130
|
+
setInitialValues(callback, list) {
|
|
2131
|
+
const dssStruct = this.dssStruct;
|
|
2132
|
+
if (!dssStruct) {
|
|
2133
|
+
return void (callback && callback());
|
|
2134
|
+
}
|
|
2135
|
+
if (list === undefined) {
|
|
2136
|
+
list = Object.keys(dssStruct.initialObjectValues);
|
|
2137
|
+
}
|
|
2138
|
+
if (list && !list.length) {
|
|
2139
|
+
return callback && callback();
|
|
2140
|
+
}
|
|
2141
|
+
const id = list.shift();
|
|
2142
|
+
const value = dssStruct.initialObjectValues[id];
|
|
2143
|
+
if (value === undefined) {
|
|
2144
|
+
// undefined values would only produce js-controller warnings
|
|
2145
|
+
return void setImmediate(() => this.setInitialValues(callback, list));
|
|
2146
|
+
}
|
|
2147
|
+
const converted = this.coerceStateValue(id, value);
|
|
2148
|
+
if (converted === undefined) {
|
|
2149
|
+
return void setImmediate(() => this.setInitialValues(callback, list));
|
|
2150
|
+
}
|
|
2151
|
+
void this.setState(id, converted, true, () => this.setInitialValues(callback, list));
|
|
2152
|
+
}
|
|
2153
|
+
clearAdditionalObjects(delIds, callback) {
|
|
2154
|
+
if (typeof delIds === 'function') {
|
|
2155
|
+
callback = delIds;
|
|
2156
|
+
delIds = null;
|
|
2157
|
+
}
|
|
2158
|
+
if (!delIds && this.objectHelper.existingStates) {
|
|
2159
|
+
delIds = Object.keys(this.objectHelper.existingStates);
|
|
2160
|
+
if (delIds.length) {
|
|
2161
|
+
// Normalized again right at the destructive branch: only an unambiguously
|
|
2162
|
+
// true value may delete objects, whatever the configuration contains.
|
|
2163
|
+
if (!configUtils.normalizeBoolean(this.config.deleteUnknownObjects, false)) {
|
|
2164
|
+
// Devices that are temporarily absent (offline circuit, unreachable device)
|
|
2165
|
+
// would lose their objects including all custom settings (history, influxdb, ...).
|
|
2166
|
+
// So only report them and let the user decide via the config option.
|
|
2167
|
+
this.log.info(`The following objects are unknown to the current DSS structure and would be deleted if "Delete unknown objects" is enabled in the adapter settings: ${JSON.stringify(delIds)}`);
|
|
2168
|
+
return void (callback && callback());
|
|
2169
|
+
}
|
|
2170
|
+
this.log.info(`Deleting the following states: ${JSON.stringify(delIds)}`);
|
|
2171
|
+
}
|
|
2172
|
+
}
|
|
2173
|
+
if (!delIds || !delIds.length) {
|
|
2174
|
+
return void (callback && callback());
|
|
2175
|
+
}
|
|
2176
|
+
const remaining = delIds;
|
|
2177
|
+
const del = remaining.shift();
|
|
2178
|
+
this.delObject(del, err => {
|
|
2179
|
+
if (err) {
|
|
2180
|
+
this.log.info(` Could not delete ${del}: ${err}`);
|
|
2181
|
+
}
|
|
2182
|
+
if (this.objectHelper.existingStates) {
|
|
2183
|
+
delete this.objectHelper.existingStates[del];
|
|
2184
|
+
}
|
|
2185
|
+
setImmediate(() => this.clearAdditionalObjects(remaining, callback));
|
|
2186
|
+
});
|
|
2187
|
+
}
|
|
2188
|
+
}
|
|
2189
|
+
if (require.main !== module) {
|
|
2190
|
+
// Export the constructor in compact mode. The class rides along on the factory BEFORE
|
|
2191
|
+
// it becomes module.exports: assigning to module.exports twice is what a module with
|
|
2192
|
+
// an export assignment may not do, and the object js-controller receives is the same
|
|
2193
|
+
// either way. Additionally exposed for unit tests - js-controller only uses the
|
|
2194
|
+
// function itself.
|
|
2195
|
+
module.exports = Object.assign((options) => new Digitalstrom(options), {
|
|
2196
|
+
Digitalstrom,
|
|
2197
|
+
});
|
|
2198
|
+
}
|
|
2199
|
+
else {
|
|
2200
|
+
// otherwise start the instance directly
|
|
2201
|
+
(() => new Digitalstrom())();
|
|
2202
|
+
}
|
|
2203
|
+
//# sourceMappingURL=main.js.map
|