iobroker.digitalstrom 2.3.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,769 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.DSSSmartHome = exports.SmartHomeError = void 0;
37
+ const node_events_1 = require("node:events");
38
+ const http = __importStar(require("node:http"));
39
+ const https = __importStar(require("node:https"));
40
+ const configUtils_1 = require("./configUtils");
41
+ const dss_1 = require("./dss");
42
+ const websocket_1 = require("./websocket");
43
+ const DEFAULT_REQUEST_TIMEOUT = 30 * 1000;
44
+ const DEFAULT_NOTIFICATION_PORT = 8090;
45
+ /**
46
+ * The dSS fires several notifications per second while something is moving, and every
47
+ * flushed notification costs the consumer a ~59 KB status read. Measured against a real
48
+ * installation: with a short debounce a moving blind produced 37 status reads (2.2 MB) in
49
+ * three minutes, so the coalescing window is deliberately long - this channel is a safety
50
+ * net behind the classic event long-poll, not a realtime feed.
51
+ */
52
+ const DEFAULT_NOTIFICATION_DEBOUNCE = 5000;
53
+ /** Even a continuous stream of notifications has to reach the consumer at some point */
54
+ const DEFAULT_NOTIFICATION_MAX_DELAY = 15000;
55
+ const RECONNECT_BASE_DELAY = 2000;
56
+ const RECONNECT_MAX_DELAY = 60000;
57
+ /** SignalR terminates every message with this character */
58
+ const RECORD_SEPARATOR = String.fromCharCode(0x1e);
59
+ /** Everything the apartment resource can deliver in one request */
60
+ const APARTMENT_INCLUDES = [
61
+ 'installation',
62
+ 'dsDevices',
63
+ 'submodules',
64
+ 'functionBlocks',
65
+ 'zones',
66
+ 'clusters',
67
+ 'applications',
68
+ 'dsServer',
69
+ 'controllers',
70
+ 'apiRevision',
71
+ 'meterings',
72
+ ].join(',');
73
+ /** Everything the status resource can deliver in one request */
74
+ const STATUS_INCLUDES = ['dsDevices', 'zones', 'clusters', 'userDefinedStates'].join(',');
75
+ class SmartHomeError extends Error {
76
+ status;
77
+ /** node style error code, e.g. ETIMEDOUT */
78
+ code;
79
+ /** true when the request was cancelled by stop() */
80
+ shutdown;
81
+ /**
82
+ * @param message error text
83
+ * @param [status] HTTP status code, if the dSS answered at all
84
+ * @param [options] error options, e.g. the cause
85
+ */
86
+ constructor(message, status, options) {
87
+ super(message, options);
88
+ this.name = 'SmartHomeError';
89
+ this.status = status;
90
+ this.code = undefined;
91
+ this.shutdown = undefined;
92
+ }
93
+ }
94
+ exports.SmartHomeError = SmartHomeError;
95
+ function stoppedError(message) {
96
+ const err = new SmartHomeError(message);
97
+ err.shutdown = true;
98
+ return err;
99
+ }
100
+ class DSSSmartHome extends node_events_1.EventEmitter {
101
+ // The extras hang off the class so `require('./dssSmartHome').DSSSmartHome.SmartHomeError`
102
+ // keeps working next to the named exports of this module.
103
+ static SmartHomeError = SmartHomeError;
104
+ static APARTMENT_INCLUDES = APARTMENT_INCLUDES;
105
+ static STATUS_INCLUDES = STATUS_INCLUDES;
106
+ static RECORD_SEPARATOR = RECORD_SEPARATOR;
107
+ options;
108
+ logger;
109
+ apiKey;
110
+ getSessionToken;
111
+ apiKeyRejected;
112
+ baseUrl;
113
+ isSecure;
114
+ transport;
115
+ requestTimeout;
116
+ notificationPort;
117
+ notificationDebounce;
118
+ notificationMaxDelay;
119
+ rejectUnauthorized;
120
+ onActivity;
121
+ agent;
122
+ activeRequests;
123
+ stopped;
124
+ websocket;
125
+ reconnectTimer;
126
+ notificationsStarting;
127
+ reconnectAttempts;
128
+ pendingNotifications;
129
+ debounceTimer;
130
+ maxDelayTimer;
131
+ constructor(options) {
132
+ super();
133
+ this.options = options || {};
134
+ this.logger = this.options.logger || null;
135
+ this.apiKey = this.options.apiKey;
136
+ /**
137
+ * The new API also accepts the session of the classic interface as a cookie -
138
+ * measured against a dSS20 1.19.13 for every endpoint this client reads and
139
+ * for the notification websocket. That makes the API key optional: without one
140
+ * the adapter uses the login it has anyway, and a key the dSS rejects no longer
141
+ * takes the Smart Home path down with it.
142
+ */
143
+ this.getSessionToken = this.options.getSessionToken || null;
144
+ /** Set once the dSS rejected the key - from then on the session serves */
145
+ this.apiKeyRejected = false;
146
+ this.baseUrl = dss_1.DSS.buildBaseUrl(this.options.host);
147
+ this.isSecure = this.baseUrl.startsWith('https:');
148
+ this.transport = this.isSecure ? https : http;
149
+ this.requestTimeout = this.options.requestTimeout || DEFAULT_REQUEST_TIMEOUT;
150
+ this.notificationPort = this.options.notificationPort || DEFAULT_NOTIFICATION_PORT;
151
+ this.notificationDebounce =
152
+ this.options.notificationDebounce === undefined
153
+ ? DEFAULT_NOTIFICATION_DEBOUNCE
154
+ : this.options.notificationDebounce;
155
+ this.notificationMaxDelay =
156
+ this.options.notificationMaxDelay === undefined
157
+ ? DEFAULT_NOTIFICATION_MAX_DELAY
158
+ : this.options.notificationMaxDelay;
159
+ this.rejectUnauthorized = (0, configUtils_1.normalizeBoolean)(this.options.validateCertificate, false);
160
+ /**
161
+ * Optionaler Zaehl-Haken fuer die Aktivitaetsanzeige: ('request', apiPath).
162
+ */
163
+ this.onActivity = typeof this.options.onActivity === 'function' ? this.options.onActivity : null;
164
+ this.agent = new this.transport.Agent({
165
+ // Same reasoning as in dss.js: the dSS closes idle connections, a pooled socket
166
+ // that was closed in the meantime ends in "socket hang up" on the next request.
167
+ keepAlive: false,
168
+ rejectUnauthorized: this.rejectUnauthorized,
169
+ });
170
+ this.activeRequests = new Set();
171
+ this.stopped = false;
172
+ this.websocket = null;
173
+ this.reconnectTimer = null;
174
+ this.notificationsStarting = false;
175
+ this.reconnectAttempts = 0;
176
+ /** Notification types that arrived since the last flush */
177
+ this.pendingNotifications = new Set();
178
+ this.debounceTimer = null;
179
+ this.maxDelayTimer = null;
180
+ }
181
+ /**
182
+ * @returns host and port of the notification websocket
183
+ */
184
+ get notificationHost() {
185
+ const url = new URL(this.baseUrl);
186
+ return url.hostname;
187
+ }
188
+ /* ------------------------------------------------------------------ http */
189
+ /**
190
+ * The credentials for one request. The key is the primary path - it is permanent
191
+ * and needs no renewal. Without a key (or after the dSS rejected it) the session
192
+ * of the classic interface serves as a cookie; DSS.getSessionToken() renews it.
193
+ *
194
+ * @param [forceRenew] fetch a fresh session instead of the cached one
195
+ */
196
+ async authHeaders(forceRenew) {
197
+ if (this.apiKey && !this.apiKeyRejected) {
198
+ return { Authorization: `Bearer ${this.apiKey}` };
199
+ }
200
+ if (!this.getSessionToken) {
201
+ // No key left and no session available - the caller sees the dSS answer
202
+ return { Authorization: `Bearer ${this.apiKey || ''}` };
203
+ }
204
+ return { Cookie: `token=${await this.getSessionToken(forceRenew)}` };
205
+ }
206
+ /**
207
+ * One request against the new API. An answer that rejects the credentials is
208
+ * retried once: a rejected key switches to the session, a stale session is
209
+ * renewed. Only then does the error reach the caller.
210
+ *
211
+ * @param method HTTP method
212
+ * @param apiPath e.g. /api/v1/apartment
213
+ * @param [params] query parameters
214
+ * @param [body] json body
215
+ * @returns the `data` field of the answer, or null for an empty body
216
+ */
217
+ async request(method, apiPath, params, body) {
218
+ const usedKey = !!(this.apiKey && !this.apiKeyRejected);
219
+ try {
220
+ return await this.send(method, apiPath, params, body, await this.authHeaders());
221
+ }
222
+ catch (err) {
223
+ const status = err instanceof SmartHomeError ? err.status : undefined;
224
+ if (this.stopped || !this.getSessionToken || (status !== 401 && status !== 403)) {
225
+ throw err;
226
+ }
227
+ if (usedKey) {
228
+ // The key is gone - revoked in the dSS, or replaced by a newer one of
229
+ // the same name. The login of the classic interface still works.
230
+ this.apiKeyRejected = true;
231
+ this.logger &&
232
+ this.logger.warn(`The dSS rejected the Smart Home API key (HTTP ${status}) - using the login of the ` +
233
+ 'classic interface instead. Create a new key in the adapter configuration when you ' +
234
+ 'want one back.');
235
+ }
236
+ else {
237
+ this.logger && this.logger.debug(`Renewing the session for ${apiPath} after HTTP ${status}`);
238
+ }
239
+ return await this.send(method, apiPath, params, body, await this.authHeaders(true));
240
+ }
241
+ }
242
+ send(method, apiPath, params, body, authHeaders) {
243
+ return new Promise((resolve, reject) => {
244
+ if (this.stopped) {
245
+ const err = new SmartHomeError(`Client is stopped, not requesting ${apiPath}`);
246
+ err.shutdown = true;
247
+ return void reject(err);
248
+ }
249
+ const url = new URL(this.baseUrl + apiPath);
250
+ for (const [key, value] of Object.entries(params || {})) {
251
+ url.searchParams.set(key, String(value));
252
+ }
253
+ const payload = body === undefined ? null : JSON.stringify(body);
254
+ const headers = { ...authHeaders };
255
+ if (payload !== null) {
256
+ headers['Content-Type'] = 'application/json';
257
+ headers['Content-Length'] = Buffer.byteLength(payload);
258
+ }
259
+ // Declared before done(), which has to see the request it belongs to
260
+ let req = undefined;
261
+ const done = (err, value) => {
262
+ if (req) {
263
+ this.activeRequests.delete(req);
264
+ }
265
+ if (err) {
266
+ reject(err);
267
+ }
268
+ else {
269
+ resolve(value);
270
+ }
271
+ };
272
+ this.onActivity && this.onActivity('request', apiPath);
273
+ req = this.transport.request({
274
+ protocol: url.protocol,
275
+ hostname: url.hostname,
276
+ port: url.port,
277
+ path: `${url.pathname}${url.search}`,
278
+ method,
279
+ headers,
280
+ agent: this.agent,
281
+ timeout: this.requestTimeout,
282
+ }, res => {
283
+ let data = '';
284
+ res.setEncoding('utf8');
285
+ res.on('data', chunk => (data += chunk));
286
+ res.on('end', () => {
287
+ const status = res.statusCode || 0;
288
+ if (status >= 300) {
289
+ return done(new SmartHomeError(`HTTP ${status} for ${method} ${apiPath}${data ? `: ${data.slice(0, 200)}` : ''}`, status));
290
+ }
291
+ if (!data) {
292
+ // PATCH and POST answer without a body
293
+ return done(null, null);
294
+ }
295
+ let parsed;
296
+ try {
297
+ parsed = JSON.parse(data);
298
+ }
299
+ catch (err) {
300
+ return done(new SmartHomeError(`Invalid JSON answer for ${apiPath}: ${(0, configUtils_1.errorMessage)(err)}`, status, {
301
+ cause: err,
302
+ }));
303
+ }
304
+ // Every answer of this API is wrapped in a data envelope
305
+ done(null, parsed && typeof parsed === 'object' && 'data' in parsed ? parsed.data : parsed);
306
+ });
307
+ // Without this handler a connection that dies in the middle of the
308
+ // response body would neither reject nor resolve - the promise
309
+ // would hang forever, because req 'error' does not fire either.
310
+ res.on('error', err => {
311
+ if (this.stopped) {
312
+ return done(stoppedError(`Request for ${apiPath} was cancelled by stop()`));
313
+ }
314
+ done(new SmartHomeError(`Response error for ${method} ${apiPath}: ${(0, configUtils_1.errorMessage)(err)}`, undefined, {
315
+ cause: err,
316
+ }));
317
+ });
318
+ });
319
+ this.activeRequests.add(req);
320
+ req.on('timeout', () => {
321
+ const err = new SmartHomeError(`Timeout after ${this.requestTimeout} ms for ${apiPath}`);
322
+ err.code = 'ETIMEDOUT';
323
+ req.destroy(err);
324
+ });
325
+ req.on('error', err => {
326
+ if (this.stopped) {
327
+ const stoppedErr = new SmartHomeError(`Request for ${apiPath} was cancelled by stop()`);
328
+ stoppedErr.shutdown = true;
329
+ return done(stoppedErr);
330
+ }
331
+ done(err);
332
+ });
333
+ req.end(payload === null ? undefined : payload);
334
+ });
335
+ }
336
+ /* -------------------------------------------------------------- reading */
337
+ /**
338
+ * The complete structure in one request. About 260 KB for a flat with 96 devices.
339
+ */
340
+ getApartment() {
341
+ return this.request('GET', '/api/v1/apartment', { include: APARTMENT_INCLUDES });
342
+ }
343
+ /**
344
+ * All current values in one request: apartment level, device outputs, zone
345
+ * measurements, cluster locks and the user defined states.
346
+ */
347
+ getApartmentStatus() {
348
+ return this.request('GET', '/api/v1/apartment/status', { include: STATUS_INCLUDES });
349
+ }
350
+ /**
351
+ * Status of a single zone, about 1 KB. Cheaper than the full status when only one
352
+ * zone is of interest.
353
+ *
354
+ * @param zoneId id of the zone
355
+ */
356
+ getZoneStatus(zoneId) {
357
+ return this.request('GET', `/api/v1/apartment/zones/${encodeURIComponent(String(zoneId))}/status`);
358
+ }
359
+ /**
360
+ * All scenarios with the names the user gave them in digitalSTROM. The id encodes
361
+ * zone, group and scene: applicationZone-z1-g1-s17.
362
+ */
363
+ getScenarios() {
364
+ return this.request('GET', '/api/v1/apartment/scenarios');
365
+ }
366
+ /**
367
+ * @returns the metering points, including their unit and origin
368
+ */
369
+ getMeterings() {
370
+ return this.request('GET', '/api/v1/apartment/meterings');
371
+ }
372
+ /**
373
+ * All meter values in ONE request - the classic API needs two per circuit.
374
+ */
375
+ getMeteringValues() {
376
+ return this.request('GET', '/api/v1/apartment/meterings/values');
377
+ }
378
+ /* -------------------------------------------------------------- writing */
379
+ /**
380
+ * Sets one output of a device.
381
+ *
382
+ * @param deviceId dSUID of the device
383
+ * @param functionBlockId usually identical to the device id
384
+ * @param outputId e.g. brightness, shadePositionOutside
385
+ * @param value in the range the function block declares, usually 0..100
386
+ */
387
+ setOutputValue(deviceId, functionBlockId, outputId, value) {
388
+ return this.request('PATCH', `/api/v1/apartment/dsDevices/${encodeURIComponent(deviceId)}/status`, undefined, [
389
+ {
390
+ op: 'replace',
391
+ path: `/functionBlocks/${functionBlockId}/outputs/${outputId}/value`,
392
+ value: String(value),
393
+ },
394
+ ]);
395
+ }
396
+ /**
397
+ * Sets the set point of the room temperature control of a zone.
398
+ *
399
+ * @param zoneId id of the zone
400
+ * @param value in degrees celsius
401
+ */
402
+ setZoneSetpoint(zoneId, value) {
403
+ return this.request('PATCH', `/api/v1/apartment/zones/${encodeURIComponent(String(zoneId))}/status`, undefined, [{ op: 'replace', path: '/applications/temperature/setpoint', value }]);
404
+ }
405
+ /**
406
+ * Calls a scenario. Its id encodes zone, group and scene, for example
407
+ * applicationZone-z2274-g1-s18.
408
+ *
409
+ * @param scenarioId id of the scenario
410
+ */
411
+ invokeScenario(scenarioId) {
412
+ return this.request('POST', `/api/v1/apartment/scenarios/${encodeURIComponent(scenarioId)}/invoke`, undefined, {});
413
+ }
414
+ /* -------------------------------------------------------- notifications */
415
+ /**
416
+ * Opens the notification websocket and keeps it open.
417
+ *
418
+ * The connection carries exactly two message types and no payload, so every
419
+ * notification only says THAT something changed. The consumer has to read the status
420
+ * again - which is why the events are debounced here: a moving blind produces several
421
+ * notifications per second, and every one of them would cost a 59 KB status read.
422
+ *
423
+ * Resolves WITHOUT a connection when there is nothing to do: after stop(), when a
424
+ * socket already exists and when another start is still waiting for the login. The
425
+ * caller therefore has to look at the socket before reporting an open channel.
426
+ *
427
+ * @returns resolves once the socket is connected, or immediately in
428
+ * the cases above
429
+ */
430
+ async startNotifications() {
431
+ if (this.stopped || this.websocket || this.notificationsStarting) {
432
+ return;
433
+ }
434
+ // Same credentials as the REST calls, so the channel keeps working when the key
435
+ // is missing or rejected. A failing session login must plan the next attempt
436
+ // just like a failing connect, otherwise the reconnects end here for good.
437
+ let headers;
438
+ this.notificationsStarting = true;
439
+ try {
440
+ headers = await this.authHeaders();
441
+ }
442
+ catch (err) {
443
+ if (!this.stopped) {
444
+ this.scheduleReconnect();
445
+ }
446
+ throw err;
447
+ }
448
+ finally {
449
+ this.notificationsStarting = false;
450
+ }
451
+ // stop() may have run while waiting for the login
452
+ if (this.stopped) {
453
+ return;
454
+ }
455
+ const socket = new websocket_1.MiniWebsocket({
456
+ host: this.notificationHost,
457
+ port: this.notificationPort,
458
+ path: '/api/v1/apartment/notifications',
459
+ headers,
460
+ // The notification port speaks plain ws, unlike the REST API on 8080
461
+ secure: false,
462
+ rejectUnauthorized: this.rejectUnauthorized,
463
+ });
464
+ this.websocket = socket;
465
+ socket.on('message', (text) => this.handleNotification(text));
466
+ socket.on('error', (err) => {
467
+ this.logger && this.logger.debug(`Notification websocket error: ${(0, configUtils_1.errorMessage)(err)}`);
468
+ });
469
+ socket.on('close', () => {
470
+ if (this.websocket === socket) {
471
+ this.websocket = null;
472
+ }
473
+ if (!this.stopped) {
474
+ this.emit('notificationClosed');
475
+ this.scheduleReconnect();
476
+ }
477
+ });
478
+ try {
479
+ await socket.connect();
480
+ }
481
+ catch (err) {
482
+ this.websocket = null;
483
+ if (!this.stopped) {
484
+ this.scheduleReconnect();
485
+ }
486
+ throw err;
487
+ }
488
+ // SignalR handshake. The dSS answers with an empty object and then sends its
489
+ // notifications, every message terminated by the record separator.
490
+ socket.send(`${JSON.stringify({ protocol: 'json', version: 1 })}${RECORD_SEPARATOR}`);
491
+ this.reconnectAttempts = 0;
492
+ this.emit('notificationConnected');
493
+ }
494
+ /**
495
+ * @param text one or more SignalR messages
496
+ */
497
+ handleNotification(text) {
498
+ for (const part of text.split(RECORD_SEPARATOR)) {
499
+ if (!part.trim()) {
500
+ continue;
501
+ }
502
+ let message;
503
+ try {
504
+ message = JSON.parse(part);
505
+ }
506
+ catch (err) {
507
+ this.logger && this.logger.debug(`Unreadable notification: ${(0, configUtils_1.errorMessage)(err)}`);
508
+ continue;
509
+ }
510
+ const args = Array.isArray(message && message.arguments) ? message.arguments : [];
511
+ for (const argument of args) {
512
+ if (argument && argument.type) {
513
+ this.pendingNotifications.add(argument.type);
514
+ // Vor der Entprellung: wer zaehlen will, wie oft der dSS wirklich
515
+ // meldet, braucht die einzelne Meldung und nicht die Zusammenfassung
516
+ this.emit('notification', argument.type);
517
+ }
518
+ }
519
+ if (args.length) {
520
+ this.scheduleFlush();
521
+ }
522
+ }
523
+ }
524
+ /**
525
+ * Collects notifications and reports them at most every notificationDebounce ms,
526
+ * and at the latest after notificationMaxDelay.
527
+ */
528
+ scheduleFlush() {
529
+ if (!this.notificationDebounce) {
530
+ return void this.flushNotifications();
531
+ }
532
+ if (this.debounceTimer) {
533
+ clearTimeout(this.debounceTimer);
534
+ }
535
+ this.debounceTimer = setTimeout(() => this.flushNotifications(), this.notificationDebounce);
536
+ if (this.notificationMaxDelay && !this.maxDelayTimer) {
537
+ this.maxDelayTimer = setTimeout(() => this.flushNotifications(), this.notificationMaxDelay);
538
+ }
539
+ }
540
+ flushNotifications() {
541
+ if (this.debounceTimer) {
542
+ clearTimeout(this.debounceTimer);
543
+ this.debounceTimer = null;
544
+ }
545
+ if (this.maxDelayTimer) {
546
+ clearTimeout(this.maxDelayTimer);
547
+ this.maxDelayTimer = null;
548
+ }
549
+ if (!this.pendingNotifications.size || this.stopped) {
550
+ this.pendingNotifications.clear();
551
+ return;
552
+ }
553
+ const types = [...this.pendingNotifications];
554
+ this.pendingNotifications.clear();
555
+ if (types.includes('apartmentStructureChanged')) {
556
+ this.emit('structureChanged', types);
557
+ }
558
+ if (types.includes('apartmentStatusChanged')) {
559
+ this.emit('statusChanged', types);
560
+ }
561
+ }
562
+ scheduleReconnect() {
563
+ if (this.reconnectTimer || this.stopped) {
564
+ return;
565
+ }
566
+ const delay = Math.min(RECONNECT_BASE_DELAY * 2 ** this.reconnectAttempts, RECONNECT_MAX_DELAY);
567
+ this.reconnectAttempts++;
568
+ this.reconnectTimer = setTimeout(() => {
569
+ this.reconnectTimer = null;
570
+ if (this.stopped) {
571
+ return;
572
+ }
573
+ this.startNotifications().catch(err => {
574
+ this.logger && this.logger.debug(`Notification reconnect failed: ${(0, configUtils_1.errorMessage)(err)}`);
575
+ });
576
+ }, delay);
577
+ }
578
+ stopNotifications() {
579
+ if (this.reconnectTimer) {
580
+ clearTimeout(this.reconnectTimer);
581
+ this.reconnectTimer = null;
582
+ }
583
+ if (this.debounceTimer) {
584
+ clearTimeout(this.debounceTimer);
585
+ this.debounceTimer = null;
586
+ }
587
+ if (this.maxDelayTimer) {
588
+ clearTimeout(this.maxDelayTimer);
589
+ this.maxDelayTimer = null;
590
+ }
591
+ this.pendingNotifications.clear();
592
+ if (this.websocket) {
593
+ const socket = this.websocket;
594
+ this.websocket = null;
595
+ socket.removeAllListeners();
596
+ // A socket error arriving between here and the close would hit an emitter
597
+ // without any 'error' listener, which throws as an uncaught exception
598
+ socket.on('error', () => { });
599
+ socket.close();
600
+ }
601
+ }
602
+ stop() {
603
+ this.stopped = true;
604
+ this.stopNotifications();
605
+ this.activeRequests.forEach(req => req.destroy());
606
+ this.activeRequests.clear();
607
+ this.agent.destroy();
608
+ }
609
+ /* ---------------------------------------------------------- api key */
610
+ /**
611
+ * Creates the bearer key for this API, once.
612
+ *
613
+ * The key is created through the CLASSIC api: an existing app token becomes a session
614
+ * token, and that session creates the application token of the new API. The user
615
+ * therefore does not have to enter the password again if the adapter is already
616
+ * configured.
617
+ *
618
+ * @param options host, credentials and name of the key
619
+ * @returns the bearer key
620
+ */
621
+ static async createApiKey(options) {
622
+ const dss = new dss_1.DSS({
623
+ host: options.host,
624
+ appToken: options.appToken,
625
+ validateCertificate: options.validateCertificate,
626
+ logger: options.logger,
627
+ });
628
+ let client = null;
629
+ const signal = options.signal;
630
+ const abort = () => {
631
+ dss.stop();
632
+ client && client.stop();
633
+ };
634
+ signal && signal.addEventListener('abort', abort, { once: true });
635
+ try {
636
+ if (signal && signal.aborted) {
637
+ throw stoppedError('Smart Home API key creation was cancelled');
638
+ }
639
+ let sessionToken;
640
+ if (options.appToken) {
641
+ // The DSS client already keeps a session, asking it avoids a second login
642
+ sessionToken = await dss.getSessionToken();
643
+ }
644
+ else {
645
+ const answer = await dss.httpRequest('/json/system/login', {
646
+ user: options.user,
647
+ password: options.password,
648
+ });
649
+ // A wrong password is answered with HTTP 200 and ok:false - without this
650
+ // check the actual reason from the dSS would be thrown away
651
+ if (!answer || answer.ok !== true) {
652
+ throw new SmartHomeError(`Login failed: ${(answer && answer.message) || 'unknown error'}`);
653
+ }
654
+ sessionToken = answer.result && answer.result.token;
655
+ }
656
+ if (!sessionToken) {
657
+ throw new SmartHomeError('The dSS did not return a session token');
658
+ }
659
+ if (signal && signal.aborted) {
660
+ throw stoppedError('Smart Home API key creation was cancelled');
661
+ }
662
+ client = new DSSSmartHome({
663
+ host: options.host,
664
+ apiKey: '',
665
+ validateCertificate: options.validateCertificate,
666
+ logger: options.logger,
667
+ });
668
+ // The answer carries the key in the Location header, not in the body, so
669
+ // the raw request is done here instead of through request().
670
+ const key = await client.requestApplicationToken(sessionToken, options.name || 'ioBroker.digitalstrom');
671
+ if (signal && signal.aborted) {
672
+ throw stoppedError('Smart Home API key creation was cancelled');
673
+ }
674
+ return key;
675
+ }
676
+ finally {
677
+ signal && signal.removeEventListener('abort', abort);
678
+ client && client.stop();
679
+ dss.stop();
680
+ }
681
+ }
682
+ /**
683
+ * POST /api/v1/apartment/applicationTokens. Answers with 201 and the key in the
684
+ * Location header.
685
+ *
686
+ * @param sessionToken session token of the classic API
687
+ * @param name name of the application, visible in the dSS
688
+ * @returns the bearer key
689
+ */
690
+ requestApplicationToken(sessionToken, name) {
691
+ return new Promise((resolve, reject) => {
692
+ if (this.stopped) {
693
+ return void reject(stoppedError('Smart Home API client is stopped'));
694
+ }
695
+ const url = new URL(`${this.baseUrl}/api/v1/apartment/applicationTokens`);
696
+ url.searchParams.set('token', sessionToken);
697
+ const payload = JSON.stringify({
698
+ data: { type: 'applicationToken', attributes: { name } },
699
+ });
700
+ let settled = false;
701
+ // Declared before done(), which has to see the request it belongs to
702
+ let req = undefined;
703
+ const done = (err, value) => {
704
+ if (settled) {
705
+ return;
706
+ }
707
+ settled = true;
708
+ if (req) {
709
+ this.activeRequests.delete(req);
710
+ }
711
+ if (err) {
712
+ reject(err);
713
+ }
714
+ else if (typeof value === 'string') {
715
+ resolve(value);
716
+ }
717
+ else {
718
+ reject(new SmartHomeError('The dSS did not return an application token'));
719
+ }
720
+ };
721
+ req = this.transport.request({
722
+ protocol: url.protocol,
723
+ hostname: url.hostname,
724
+ port: url.port,
725
+ path: `${url.pathname}${url.search}`,
726
+ method: 'POST',
727
+ headers: {
728
+ 'Content-Type': 'application/json',
729
+ 'Content-Length': Buffer.byteLength(payload),
730
+ },
731
+ agent: this.agent,
732
+ timeout: this.requestTimeout,
733
+ }, res => {
734
+ let data = '';
735
+ res.setEncoding('utf8');
736
+ res.on('data', chunk => (data += chunk));
737
+ res.on('end', () => {
738
+ if (res.statusCode !== 201) {
739
+ return done(new SmartHomeError(`Could not create the application token (HTTP ${res.statusCode})${data ? `: ${data.slice(0, 200)}` : ''}`, res.statusCode));
740
+ }
741
+ const location = String(res.headers.location || '');
742
+ const key = location.split('/').filter(Boolean).pop();
743
+ if (!key) {
744
+ return done(new SmartHomeError('The dSS answered without a usable Location header, no key received'));
745
+ }
746
+ done(null, key);
747
+ });
748
+ res.on('error', err => {
749
+ if (this.stopped) {
750
+ return done(stoppedError('Smart Home API key creation was cancelled'));
751
+ }
752
+ done(new SmartHomeError(`Response error while creating the application token: ${(0, configUtils_1.errorMessage)(err)}`, undefined, {
753
+ cause: err,
754
+ }));
755
+ });
756
+ });
757
+ this.activeRequests.add(req);
758
+ req.on('timeout', () => {
759
+ const err = new SmartHomeError('Timeout while creating the application token');
760
+ err.code = 'ETIMEDOUT';
761
+ req.destroy(err);
762
+ });
763
+ req.on('error', err => done(this.stopped ? stoppedError('Smart Home API key creation was cancelled') : err));
764
+ req.end(payload);
765
+ });
766
+ }
767
+ }
768
+ exports.DSSSmartHome = DSSSmartHome;
769
+ //# sourceMappingURL=dssSmartHome.js.map