@camstack/addon-provider-homematic 1.2.203 → 1.2.204

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/CHANGELOG.md CHANGED
@@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [1.2.204] - 2026-11-16
11
+
12
+ ### Fixed
13
+
14
+ - Uses nodehomematic 0.9.1: a refused CCU login backs off instead of locking out, the session heals after a CCU reboot, and a 5xx from a booting CCU is retried.
15
+
10
16
  ## [1.2.203] - 2026-11-15
11
17
 
12
18
  ### Changed
package/dist/addon.js CHANGED
@@ -134110,6 +134110,25 @@ var UnsupportedError = class extends BaseHomematicError {};
134110
134110
  var ValidationError = class extends BaseHomematicError {};
134111
134111
  var NoConnectionError = class extends BaseHomematicError {};
134112
134112
  var CircuitBreakerOpenError = class extends BaseHomematicError {};
134113
+ var LoginBackoffError = class extends BaseHomematicError {
134114
+ /** When the next real login attempt may go out (epoch ms). */
134115
+ retryAt;
134116
+ /** Consecutive failed logins so far. */
134117
+ failures;
134118
+ constructor(retryAt, failures) {
134119
+ super(`login backing off after ${failures} consecutive failure(s); next attempt at ${new Date(retryAt).toISOString()}`);
134120
+ this.retryAt = retryAt;
134121
+ this.failures = failures;
134122
+ }
134123
+ };
134124
+ var BackendUnavailableError = class extends BaseHomematicError {
134125
+ /** The HTTP status code the CCU answered. */
134126
+ status;
134127
+ constructor(status, message) {
134128
+ super(message);
134129
+ this.status = status;
134130
+ }
134131
+ };
134113
134132
  var AuthFailureError = class extends BaseHomematicError {};
134114
134133
  var InternalBackendError = class extends BaseHomematicError {};
134115
134134
  var CommandSupersededError = class extends BaseHomematicError {};
@@ -135121,8 +135140,22 @@ var JsonRpcMethod = {
135121
135140
  SESSION_RENEW: "Session.renew",
135122
135141
  SYSTEM_LIST_METHODS: "system.listMethods"
135123
135142
  };
135124
- JsonRpcMethod.SESSION_LOGIN, JsonRpcMethod.SESSION_LOGOUT, JsonRpcMethod.SESSION_RENEW;
135143
+ var SESSION_BYPASS_METHODS = /* @__PURE__ */ new Set([
135144
+ JsonRpcMethod.SESSION_LOGIN,
135145
+ JsonRpcMethod.SESSION_LOGOUT,
135146
+ JsonRpcMethod.SESSION_RENEW
135147
+ ]);
135125
135148
  var DEFAULT_MAX_CONCURRENT = 3;
135149
+ var DEFAULT_RETRY_DELAYS_MS = [
135150
+ 500,
135151
+ 1e3,
135152
+ 2e3
135153
+ ];
135154
+ function delay(ms) {
135155
+ return new Promise((resolve) => {
135156
+ setTimeout(resolve, ms);
135157
+ });
135158
+ }
135126
135159
  function stringifyParams(params) {
135127
135160
  const out = {};
135128
135161
  for (const [key, value] of Object.entries(params)) if (value !== null && typeof value === "object") out[key] = JSON.stringify(value);
@@ -135153,11 +135186,13 @@ var JsonRpcClient = class {
135153
135186
  timeoutMs;
135154
135187
  dispatcher;
135155
135188
  semaphore;
135189
+ retryDelaysMs;
135156
135190
  constructor(options) {
135157
135191
  const base = options.url.replace(/\/+$/, "");
135158
135192
  this.endpoint = `${base}${JSON_RPC_PATH$2}`;
135159
135193
  this.timeoutMs = options.timeoutMs ?? TIMEOUTS.rpc;
135160
135194
  this.semaphore = new Semaphore(options.maxConcurrent ?? DEFAULT_MAX_CONCURRENT);
135195
+ this.retryDelaysMs = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
135161
135196
  if (options.tls?.rejectUnauthorized === false) this.dispatcher = new import_undici.Agent({ connect: { rejectUnauthorized: false } });
135162
135197
  else this.dispatcher = void 0;
135163
135198
  }
@@ -135175,6 +135210,16 @@ var JsonRpcClient = class {
135175
135210
  id: 0
135176
135211
  };
135177
135212
  const body = Buffer.from(JSON.stringify(envelope), "utf-8");
135213
+ const delays = SESSION_BYPASS_METHODS.has(method) ? [] : this.retryDelaysMs;
135214
+ for (let attempt = 0;; attempt += 1) try {
135215
+ return await this.sendGuarded(body);
135216
+ } catch (err) {
135217
+ const wait = delays[attempt];
135218
+ if (!(err instanceof BackendUnavailableError) || wait === void 0) throw err;
135219
+ await delay(wait);
135220
+ }
135221
+ }
135222
+ async sendGuarded(body) {
135178
135223
  await this.semaphore.acquire();
135179
135224
  try {
135180
135225
  return await this.send(body);
@@ -135186,6 +135231,7 @@ var JsonRpcClient = class {
135186
135231
  const controller = new AbortController();
135187
135232
  const timer = setTimeout(() => controller.abort(), this.timeoutMs);
135188
135233
  let raw;
135234
+ let status;
135189
135235
  try {
135190
135236
  const init = {
135191
135237
  method: "POST",
@@ -135197,13 +135243,16 @@ var JsonRpcClient = class {
135197
135243
  signal: controller.signal
135198
135244
  };
135199
135245
  if (this.dispatcher) init.dispatcher = this.dispatcher;
135200
- const arrayBuffer = await (await (0, import_undici.fetch)(this.endpoint, init)).arrayBuffer();
135246
+ const response = await (0, import_undici.fetch)(this.endpoint, init);
135247
+ status = response.status;
135248
+ const arrayBuffer = await response.arrayBuffer();
135201
135249
  raw = Buffer.from(arrayBuffer);
135202
135250
  } catch (err) {
135203
135251
  throw mapTransportError(err);
135204
135252
  } finally {
135205
135253
  clearTimeout(timer);
135206
135254
  }
135255
+ if (status >= 500) throw new BackendUnavailableError(status, `JSON-RPC endpoint answered HTTP ${status}`);
135207
135256
  if (raw.length === 0) throw new ClientError("JSON-RPC response had an empty body");
135208
135257
  let parsed;
135209
135258
  try {
@@ -135221,14 +135270,8 @@ var JsonRpcClient = class {
135221
135270
  };
135222
135271
  var DEFAULT_SESSION_AGE_SECONDS = 90;
135223
135272
  var INITIAL_BACKOFF_MS = 1e3;
135224
- var MAX_BACKOFF_MS = 6e4;
135273
+ var MAX_BACKOFF_MS = 3e5;
135225
135274
  var BACKOFF_FACTOR = 2;
135226
- var MAX_CONSECUTIVE_FAILURES = 10;
135227
- function delay(ms) {
135228
- return new Promise((resolve) => {
135229
- setTimeout(resolve, ms);
135230
- });
135231
- }
135232
135275
  var SessionManager = class {
135233
135276
  client;
135234
135277
  username;
@@ -135238,6 +135281,9 @@ var SessionManager = class {
135238
135281
  currentSessionId;
135239
135282
  lastRefresh = 0;
135240
135283
  consecutiveFailures = 0;
135284
+ nextAttemptAt = 0;
135285
+ inFlightLogin;
135286
+ inFlightEnsure;
135241
135287
  constructor(options) {
135242
135288
  this.client = options.client;
135243
135289
  this.username = options.username;
@@ -135251,65 +135297,127 @@ var SessionManager = class {
135251
135297
  }
135252
135298
  /**
135253
135299
  * Log in with username/password (no session id), store the resulting session
135254
- * id, and return it. Applies failed-login rate limiting: each consecutive
135255
- * failure waits an exponentially growing backoff (1s → 60s); after
135256
- * {@link MAX_CONSECUTIVE_FAILURES} failures it throws without contacting the
135257
- * backend. A success resets the failure counter.
135258
- */
135259
- async login() {
135260
- if (this.consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) throw new BaseHomematicError(`login rate limit reached after ${MAX_CONSECUTIVE_FAILURES} consecutive failures`);
135261
- if (this.consecutiveFailures > 0) await delay(this.backoffDelayMs());
135262
- try {
135263
- const result = await this.client.post(JsonRpcMethod.SESSION_LOGIN, {
135264
- username: this.username,
135265
- password: this.password
135266
- });
135267
- const id = String(result);
135268
- this.currentSessionId = id;
135269
- this.lastRefresh = this.now();
135270
- this.consecutiveFailures = 0;
135271
- return id;
135272
- } catch (err) {
135273
- this.consecutiveFailures += 1;
135274
- throw err;
135275
- }
135300
+ * id, and return it. Inside an open backoff window it throws
135301
+ * {@link LoginBackoffError} without contacting the CCU. Concurrent calls
135302
+ * share one request.
135303
+ */
135304
+ login() {
135305
+ if (this.inFlightLogin !== void 0) return this.inFlightLogin;
135306
+ if (this.consecutiveFailures > 0 && this.now() < this.nextAttemptAt) return Promise.reject(new LoginBackoffError(this.nextAttemptAt, this.consecutiveFailures));
135307
+ const attempt = this.sendLogin().finally(() => {
135308
+ this.inFlightLogin = void 0;
135309
+ });
135310
+ this.inFlightLogin = attempt;
135311
+ return attempt;
135312
+ }
135313
+ /** Close the backoff window: the next login goes out at once (the CCU answered again). */
135314
+ resetBackoff() {
135315
+ this.consecutiveFailures = 0;
135316
+ this.nextAttemptAt = 0;
135317
+ }
135318
+ /** Force a renew on the next {@link ensureSession} (the CCU may have restarted). */
135319
+ markStale() {
135320
+ this.lastRefresh = Number.NEGATIVE_INFINITY;
135276
135321
  }
135277
135322
  /**
135278
135323
  * Renew the current session if it is older than the session-age window. If it
135279
- * was refreshed recently this is a no-op. On {@link AuthFailureError} the old
135280
- * session is logged out (best-effort) and a fresh login is performed.
135324
+ * was refreshed recently this is a no-op. A renew that does not answer `true`
135325
+ * or is refused drops the session and logs in again; a renew that fails for
135326
+ * another reason (CCU unreachable) drops the session and rethrows, so the
135327
+ * next call logs in instead of reusing an id the CCU may have forgotten.
135281
135328
  */
135282
135329
  async renew() {
135283
- if (this.currentSessionId === void 0) {
135330
+ const id = this.currentSessionId;
135331
+ if (id === void 0) {
135284
135332
  await this.login();
135285
135333
  return;
135286
135334
  }
135287
135335
  if (this.now() - this.lastRefresh < this.sessionAgeMs) return;
135336
+ let result;
135288
135337
  try {
135289
- if (await this.client.post(JsonRpcMethod.SESSION_RENEW, void 0, { sessionId: this.currentSessionId }) === true) this.lastRefresh = this.now();
135338
+ result = await this.client.post(JsonRpcMethod.SESSION_RENEW, void 0, { sessionId: id });
135290
135339
  } catch (err) {
135340
+ this.dropSession(id);
135291
135341
  if (err instanceof AuthFailureError) {
135292
- await this.logout();
135342
+ await this.client.post(JsonRpcMethod.SESSION_LOGOUT, void 0, { sessionId: id }).catch(() => void 0);
135293
135343
  await this.login();
135294
135344
  return;
135295
135345
  }
135296
135346
  throw err;
135297
135347
  }
135348
+ if (result === true) {
135349
+ this.lastRefresh = this.now();
135350
+ return;
135351
+ }
135352
+ this.dropSession(id);
135353
+ await this.login();
135298
135354
  }
135299
- /** Log out the current session (best-effort) and clear it. No-op if none. */
135355
+ /**
135356
+ * Log out the current session (best-effort) and clear it. No-op if none. A
135357
+ * login still in flight is awaited first, so its session is logged out too.
135358
+ */
135300
135359
  async logout() {
135360
+ if (this.inFlightLogin !== void 0) await this.inFlightLogin.catch(() => void 0);
135301
135361
  const id = this.currentSessionId;
135302
135362
  if (id === void 0) return;
135303
135363
  this.currentSessionId = void 0;
135304
135364
  await this.client.post(JsonRpcMethod.SESSION_LOGOUT, void 0, { sessionId: id });
135305
135365
  }
135306
- /** Ensure a usable session exists: login if none, else renew. Returns the id. */
135307
- async ensureSession() {
135366
+ /** Ensure a usable session exists: login if none, else renew. Returns the id. Concurrent calls share one pass. */
135367
+ ensureSession() {
135368
+ if (this.inFlightEnsure !== void 0) return this.inFlightEnsure;
135369
+ const pass = this.runEnsure().finally(() => {
135370
+ this.inFlightEnsure = void 0;
135371
+ });
135372
+ this.inFlightEnsure = pass;
135373
+ return pass;
135374
+ }
135375
+ /**
135376
+ * A client that sends through this session: a call carrying a session id that
135377
+ * the CCU refuses as `access denied` drops that session, logs in again and is
135378
+ * retried once with the new id. Calls without a session id pass through.
135379
+ */
135380
+ boundClient() {
135381
+ return { post: async (method, params, opts) => {
135382
+ const sid = opts?.sessionId;
135383
+ if (sid === void 0) return this.client.post(method, params, opts);
135384
+ try {
135385
+ return await this.client.post(method, params, opts);
135386
+ } catch (err) {
135387
+ if (!(err instanceof AuthFailureError)) throw err;
135388
+ this.dropSession(sid);
135389
+ const fresh = await this.ensureSession();
135390
+ return this.client.post(method, params, { sessionId: fresh });
135391
+ }
135392
+ } };
135393
+ }
135394
+ async runEnsure() {
135308
135395
  if (this.currentSessionId === void 0) return this.login();
135309
135396
  await this.renew();
135310
135397
  if (this.currentSessionId === void 0) return this.login();
135311
135398
  return this.currentSessionId;
135312
135399
  }
135400
+ async sendLogin() {
135401
+ try {
135402
+ const result = await this.client.post(JsonRpcMethod.SESSION_LOGIN, {
135403
+ username: this.username,
135404
+ password: this.password
135405
+ });
135406
+ const id = String(result);
135407
+ this.currentSessionId = id;
135408
+ this.lastRefresh = this.now();
135409
+ this.resetBackoff();
135410
+ return id;
135411
+ } catch (err) {
135412
+ this.consecutiveFailures += 1;
135413
+ this.nextAttemptAt = this.now() + this.backoffDelayMs();
135414
+ throw err;
135415
+ }
135416
+ }
135417
+ /** Forget `id` if it is still the current session (a newer one stays). */
135418
+ dropSession(id) {
135419
+ if (this.currentSessionId === id) this.currentSessionId = void 0;
135420
+ }
135313
135421
  backoffDelayMs() {
135314
135422
  const exp = INITIAL_BACKOFF_MS * BACKOFF_FACTOR ** (this.consecutiveFailures - 1);
135315
135423
  return Math.min(exp, MAX_BACKOFF_MS);
@@ -137785,7 +137893,7 @@ var HubFetcher = class {
137785
137893
  this.client = options.client;
137786
137894
  this.getSessionId = options.getSessionId;
137787
137895
  }
137788
- sid() {
137896
+ async sid() {
137789
137897
  return this.getSessionId();
137790
137898
  }
137791
137899
  /**
@@ -137794,14 +137902,14 @@ var HubFetcher = class {
137794
137902
  * tolerated (such a variable is treated as read-only).
137795
137903
  */
137796
137904
  async fetchSystemVariables() {
137797
- const sid = this.sid();
137905
+ const sid = await this.sid();
137798
137906
  const entries = asRecordArray2(await this.client.post(JsonRpcMethod.SYSVAR_GET_ALL, void 0, sidOpts(sid)));
137799
137907
  const descriptions = await this.fetchSysVarDescriptions();
137800
137908
  return entries.map((entry) => this.toSystemVariable(entry, descriptions));
137801
137909
  }
137802
137910
  /** Read a single system variable's raw value by name. */
137803
137911
  async getSystemVariable(name2) {
137804
- const sid = this.sid();
137912
+ const sid = await this.sid();
137805
137913
  const raw = await this.client.post(JsonRpcMethod.SYSVAR_GET_VALUE_BY_NAME, { name: name2 }, sidOpts(sid));
137806
137914
  if (typeof raw === "string" || typeof raw === "number" || typeof raw === "boolean") return raw;
137807
137915
  if (raw === null || raw === void 0) return null;
@@ -137813,7 +137921,7 @@ var HubFetcher = class {
137813
137921
  * `SET_SYSTEM_VARIABLE`. A null value is rejected.
137814
137922
  */
137815
137923
  async setSystemVariable(name2, value) {
137816
- const sid = this.sid();
137924
+ const sid = await this.sid();
137817
137925
  if (value === null) throw new ValidationError(`Cannot set system variable "${name2}" to null`);
137818
137926
  if (typeof value === "boolean") {
137819
137927
  await this.client.post(JsonRpcMethod.SYSVAR_SET_BOOL, {
@@ -137836,7 +137944,7 @@ var HubFetcher = class {
137836
137944
  }
137837
137945
  /** Fetch all programs, coercing flags to booleans. */
137838
137946
  async fetchPrograms() {
137839
- const sid = this.sid();
137947
+ const sid = await this.sid();
137840
137948
  return asRecordArray2(await this.client.post(JsonRpcMethod.PROGRAM_GET_ALL, void 0, sidOpts(sid))).map((entry) => {
137841
137949
  const lastExecuteTime = entry.lastExecuteTime;
137842
137950
  return {
@@ -137850,12 +137958,12 @@ var HubFetcher = class {
137850
137958
  }
137851
137959
  /** Execute a program by id. */
137852
137960
  async runProgram(id) {
137853
- const sid = this.sid();
137961
+ const sid = await this.sid();
137854
137962
  await this.client.post(JsonRpcMethod.PROGRAM_EXECUTE, { id }, sidOpts(sid));
137855
137963
  }
137856
137964
  /** Enable/disable a program via the ReGa `SET_PROGRAM_STATE` script. */
137857
137965
  async setProgramActive(id, active) {
137858
- const sid = this.sid();
137966
+ const sid = await this.sid();
137859
137967
  await runScript(this.client, sid, SET_PROGRAM_STATE, {
137860
137968
  id,
137861
137969
  state: active ? 1 : 0
@@ -137866,7 +137974,7 @@ var HubFetcher = class {
137866
137974
  * channel address, decoding the latin1 `UriEncode`d names. Tolerates empty.
137867
137975
  */
137868
137976
  async fetchRoomsFunctions() {
137869
- const sid = this.sid();
137977
+ const sid = await this.sid();
137870
137978
  const parsed = await runScript(this.client, sid, GET_ROOMS_FUNCTIONS);
137871
137979
  return {
137872
137980
  rooms: toDecodedMap(isRecord5(parsed) ? parsed.rooms : void 0),
@@ -137875,7 +137983,7 @@ var HubFetcher = class {
137875
137983
  }
137876
137984
  /** Build the `SYSVAR_DESCRIPTIONS` map: sysvar id → description text. */
137877
137985
  async fetchSysVarDescriptions() {
137878
- const sid = this.sid();
137986
+ const sid = await this.sid();
137879
137987
  const out = /* @__PURE__ */ new Map();
137880
137988
  try {
137881
137989
  const parsed = await runScript(this.client, sid, SYSVAR_DESCRIPTIONS);
@@ -138511,10 +138619,14 @@ var CentralUnit = class {
138511
138619
  */
138512
138620
  getHubFetcher() {
138513
138621
  if (this.jsonClient === void 0) return void 0;
138514
- const client = this.jsonClient;
138622
+ const session = this.session;
138623
+ if (session === void 0) return new HubFetcher({
138624
+ client: this.jsonClient,
138625
+ getSessionId: () => void 0
138626
+ });
138515
138627
  return new HubFetcher({
138516
- client,
138517
- getSessionId: () => this.session?.sessionId
138628
+ client: session.boundClient(),
138629
+ getSessionId: () => session.ensureSession()
138518
138630
  });
138519
138631
  }
138520
138632
  /**
@@ -138525,7 +138637,7 @@ var CentralUnit = class {
138525
138637
  */
138526
138638
  getManagement() {
138527
138639
  return new CcuManagement({
138528
- json: this.jsonClient,
138640
+ json: this.session !== void 0 ? this.session.boundClient() : this.jsonClient,
138529
138641
  webUi: this.webUi,
138530
138642
  getSessionId: () => this.session !== void 0 ? this.session.ensureSession() : Promise.resolve(void 0),
138531
138643
  interfaceClient: (iface) => {
@@ -138715,13 +138827,14 @@ var CentralUnit = class {
138715
138827
  this.webUi = this.options.webUiClient;
138716
138828
  } else {
138717
138829
  const scheme = this.tls ? "https" : "http";
138718
- const client = new JsonRpcClient({ url: `${scheme}://${this.host}` });
138830
+ const client = new JsonRpcClient({ url: this.options.jsonRpcUrl ?? `${scheme}://${this.host}` });
138719
138831
  this.jsonClient = client;
138720
138832
  this.webUi = this.options.webUiClient ?? new WebUiHttpClient({ url: `${scheme}://${this.host}` });
138721
138833
  this.session = new SessionManager({
138722
138834
  client,
138723
138835
  username: this.credentials.username,
138724
- password: this.credentials.password
138836
+ password: this.credentials.password,
138837
+ now: this.now
138725
138838
  });
138726
138839
  }
138727
138840
  }
@@ -138871,8 +138984,9 @@ var CentralUnit = class {
138871
138984
  async fetchDetails() {
138872
138985
  if (this.jsonClient === void 0) return void 0;
138873
138986
  try {
138874
- const sessionId = this.session !== void 0 ? await this.session.ensureSession() : void 0;
138875
- return await mergeDetails(this.jsonClient, sessionId);
138987
+ if (this.session === void 0) return await mergeDetails(this.jsonClient);
138988
+ const sessionId = await this.session.ensureSession();
138989
+ return await mergeDetails(this.session.boundClient(), sessionId);
138876
138990
  } catch {
138877
138991
  return;
138878
138992
  }
@@ -139010,6 +139124,8 @@ var CentralUnit = class {
139010
139124
  } catch {}
139011
139125
  await runtime.client.initProxy();
139012
139126
  runtime.pingPong.reset();
139127
+ this.session?.resetBackoff();
139128
+ this.session?.markStale();
139013
139129
  }
139014
139130
  async reloadData(interfaceId2) {
139015
139131
  const runtime = this.runtimes.get(interfaceId2);
package/dist/addon.mjs CHANGED
@@ -134111,6 +134111,25 @@ var UnsupportedError = class extends BaseHomematicError {};
134111
134111
  var ValidationError = class extends BaseHomematicError {};
134112
134112
  var NoConnectionError = class extends BaseHomematicError {};
134113
134113
  var CircuitBreakerOpenError = class extends BaseHomematicError {};
134114
+ var LoginBackoffError = class extends BaseHomematicError {
134115
+ /** When the next real login attempt may go out (epoch ms). */
134116
+ retryAt;
134117
+ /** Consecutive failed logins so far. */
134118
+ failures;
134119
+ constructor(retryAt, failures) {
134120
+ super(`login backing off after ${failures} consecutive failure(s); next attempt at ${new Date(retryAt).toISOString()}`);
134121
+ this.retryAt = retryAt;
134122
+ this.failures = failures;
134123
+ }
134124
+ };
134125
+ var BackendUnavailableError = class extends BaseHomematicError {
134126
+ /** The HTTP status code the CCU answered. */
134127
+ status;
134128
+ constructor(status, message) {
134129
+ super(message);
134130
+ this.status = status;
134131
+ }
134132
+ };
134114
134133
  var AuthFailureError = class extends BaseHomematicError {};
134115
134134
  var InternalBackendError = class extends BaseHomematicError {};
134116
134135
  var CommandSupersededError = class extends BaseHomematicError {};
@@ -135122,8 +135141,22 @@ var JsonRpcMethod = {
135122
135141
  SESSION_RENEW: "Session.renew",
135123
135142
  SYSTEM_LIST_METHODS: "system.listMethods"
135124
135143
  };
135125
- JsonRpcMethod.SESSION_LOGIN, JsonRpcMethod.SESSION_LOGOUT, JsonRpcMethod.SESSION_RENEW;
135144
+ var SESSION_BYPASS_METHODS = /* @__PURE__ */ new Set([
135145
+ JsonRpcMethod.SESSION_LOGIN,
135146
+ JsonRpcMethod.SESSION_LOGOUT,
135147
+ JsonRpcMethod.SESSION_RENEW
135148
+ ]);
135126
135149
  var DEFAULT_MAX_CONCURRENT = 3;
135150
+ var DEFAULT_RETRY_DELAYS_MS = [
135151
+ 500,
135152
+ 1e3,
135153
+ 2e3
135154
+ ];
135155
+ function delay(ms) {
135156
+ return new Promise((resolve) => {
135157
+ setTimeout(resolve, ms);
135158
+ });
135159
+ }
135127
135160
  function stringifyParams(params) {
135128
135161
  const out = {};
135129
135162
  for (const [key, value] of Object.entries(params)) if (value !== null && typeof value === "object") out[key] = JSON.stringify(value);
@@ -135154,11 +135187,13 @@ var JsonRpcClient = class {
135154
135187
  timeoutMs;
135155
135188
  dispatcher;
135156
135189
  semaphore;
135190
+ retryDelaysMs;
135157
135191
  constructor(options) {
135158
135192
  const base = options.url.replace(/\/+$/, "");
135159
135193
  this.endpoint = `${base}${JSON_RPC_PATH$2}`;
135160
135194
  this.timeoutMs = options.timeoutMs ?? TIMEOUTS.rpc;
135161
135195
  this.semaphore = new Semaphore(options.maxConcurrent ?? DEFAULT_MAX_CONCURRENT);
135196
+ this.retryDelaysMs = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
135162
135197
  if (options.tls?.rejectUnauthorized === false) this.dispatcher = new import_undici.Agent({ connect: { rejectUnauthorized: false } });
135163
135198
  else this.dispatcher = void 0;
135164
135199
  }
@@ -135176,6 +135211,16 @@ var JsonRpcClient = class {
135176
135211
  id: 0
135177
135212
  };
135178
135213
  const body = Buffer.from(JSON.stringify(envelope), "utf-8");
135214
+ const delays = SESSION_BYPASS_METHODS.has(method) ? [] : this.retryDelaysMs;
135215
+ for (let attempt = 0;; attempt += 1) try {
135216
+ return await this.sendGuarded(body);
135217
+ } catch (err) {
135218
+ const wait = delays[attempt];
135219
+ if (!(err instanceof BackendUnavailableError) || wait === void 0) throw err;
135220
+ await delay(wait);
135221
+ }
135222
+ }
135223
+ async sendGuarded(body) {
135179
135224
  await this.semaphore.acquire();
135180
135225
  try {
135181
135226
  return await this.send(body);
@@ -135187,6 +135232,7 @@ var JsonRpcClient = class {
135187
135232
  const controller = new AbortController();
135188
135233
  const timer = setTimeout(() => controller.abort(), this.timeoutMs);
135189
135234
  let raw;
135235
+ let status;
135190
135236
  try {
135191
135237
  const init = {
135192
135238
  method: "POST",
@@ -135198,13 +135244,16 @@ var JsonRpcClient = class {
135198
135244
  signal: controller.signal
135199
135245
  };
135200
135246
  if (this.dispatcher) init.dispatcher = this.dispatcher;
135201
- const arrayBuffer = await (await (0, import_undici.fetch)(this.endpoint, init)).arrayBuffer();
135247
+ const response = await (0, import_undici.fetch)(this.endpoint, init);
135248
+ status = response.status;
135249
+ const arrayBuffer = await response.arrayBuffer();
135202
135250
  raw = Buffer.from(arrayBuffer);
135203
135251
  } catch (err) {
135204
135252
  throw mapTransportError(err);
135205
135253
  } finally {
135206
135254
  clearTimeout(timer);
135207
135255
  }
135256
+ if (status >= 500) throw new BackendUnavailableError(status, `JSON-RPC endpoint answered HTTP ${status}`);
135208
135257
  if (raw.length === 0) throw new ClientError("JSON-RPC response had an empty body");
135209
135258
  let parsed;
135210
135259
  try {
@@ -135222,14 +135271,8 @@ var JsonRpcClient = class {
135222
135271
  };
135223
135272
  var DEFAULT_SESSION_AGE_SECONDS = 90;
135224
135273
  var INITIAL_BACKOFF_MS = 1e3;
135225
- var MAX_BACKOFF_MS = 6e4;
135274
+ var MAX_BACKOFF_MS = 3e5;
135226
135275
  var BACKOFF_FACTOR = 2;
135227
- var MAX_CONSECUTIVE_FAILURES = 10;
135228
- function delay(ms) {
135229
- return new Promise((resolve) => {
135230
- setTimeout(resolve, ms);
135231
- });
135232
- }
135233
135276
  var SessionManager = class {
135234
135277
  client;
135235
135278
  username;
@@ -135239,6 +135282,9 @@ var SessionManager = class {
135239
135282
  currentSessionId;
135240
135283
  lastRefresh = 0;
135241
135284
  consecutiveFailures = 0;
135285
+ nextAttemptAt = 0;
135286
+ inFlightLogin;
135287
+ inFlightEnsure;
135242
135288
  constructor(options) {
135243
135289
  this.client = options.client;
135244
135290
  this.username = options.username;
@@ -135252,65 +135298,127 @@ var SessionManager = class {
135252
135298
  }
135253
135299
  /**
135254
135300
  * Log in with username/password (no session id), store the resulting session
135255
- * id, and return it. Applies failed-login rate limiting: each consecutive
135256
- * failure waits an exponentially growing backoff (1s → 60s); after
135257
- * {@link MAX_CONSECUTIVE_FAILURES} failures it throws without contacting the
135258
- * backend. A success resets the failure counter.
135259
- */
135260
- async login() {
135261
- if (this.consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) throw new BaseHomematicError(`login rate limit reached after ${MAX_CONSECUTIVE_FAILURES} consecutive failures`);
135262
- if (this.consecutiveFailures > 0) await delay(this.backoffDelayMs());
135263
- try {
135264
- const result = await this.client.post(JsonRpcMethod.SESSION_LOGIN, {
135265
- username: this.username,
135266
- password: this.password
135267
- });
135268
- const id = String(result);
135269
- this.currentSessionId = id;
135270
- this.lastRefresh = this.now();
135271
- this.consecutiveFailures = 0;
135272
- return id;
135273
- } catch (err) {
135274
- this.consecutiveFailures += 1;
135275
- throw err;
135276
- }
135301
+ * id, and return it. Inside an open backoff window it throws
135302
+ * {@link LoginBackoffError} without contacting the CCU. Concurrent calls
135303
+ * share one request.
135304
+ */
135305
+ login() {
135306
+ if (this.inFlightLogin !== void 0) return this.inFlightLogin;
135307
+ if (this.consecutiveFailures > 0 && this.now() < this.nextAttemptAt) return Promise.reject(new LoginBackoffError(this.nextAttemptAt, this.consecutiveFailures));
135308
+ const attempt = this.sendLogin().finally(() => {
135309
+ this.inFlightLogin = void 0;
135310
+ });
135311
+ this.inFlightLogin = attempt;
135312
+ return attempt;
135313
+ }
135314
+ /** Close the backoff window: the next login goes out at once (the CCU answered again). */
135315
+ resetBackoff() {
135316
+ this.consecutiveFailures = 0;
135317
+ this.nextAttemptAt = 0;
135318
+ }
135319
+ /** Force a renew on the next {@link ensureSession} (the CCU may have restarted). */
135320
+ markStale() {
135321
+ this.lastRefresh = Number.NEGATIVE_INFINITY;
135277
135322
  }
135278
135323
  /**
135279
135324
  * Renew the current session if it is older than the session-age window. If it
135280
- * was refreshed recently this is a no-op. On {@link AuthFailureError} the old
135281
- * session is logged out (best-effort) and a fresh login is performed.
135325
+ * was refreshed recently this is a no-op. A renew that does not answer `true`
135326
+ * or is refused drops the session and logs in again; a renew that fails for
135327
+ * another reason (CCU unreachable) drops the session and rethrows, so the
135328
+ * next call logs in instead of reusing an id the CCU may have forgotten.
135282
135329
  */
135283
135330
  async renew() {
135284
- if (this.currentSessionId === void 0) {
135331
+ const id = this.currentSessionId;
135332
+ if (id === void 0) {
135285
135333
  await this.login();
135286
135334
  return;
135287
135335
  }
135288
135336
  if (this.now() - this.lastRefresh < this.sessionAgeMs) return;
135337
+ let result;
135289
135338
  try {
135290
- if (await this.client.post(JsonRpcMethod.SESSION_RENEW, void 0, { sessionId: this.currentSessionId }) === true) this.lastRefresh = this.now();
135339
+ result = await this.client.post(JsonRpcMethod.SESSION_RENEW, void 0, { sessionId: id });
135291
135340
  } catch (err) {
135341
+ this.dropSession(id);
135292
135342
  if (err instanceof AuthFailureError) {
135293
- await this.logout();
135343
+ await this.client.post(JsonRpcMethod.SESSION_LOGOUT, void 0, { sessionId: id }).catch(() => void 0);
135294
135344
  await this.login();
135295
135345
  return;
135296
135346
  }
135297
135347
  throw err;
135298
135348
  }
135349
+ if (result === true) {
135350
+ this.lastRefresh = this.now();
135351
+ return;
135352
+ }
135353
+ this.dropSession(id);
135354
+ await this.login();
135299
135355
  }
135300
- /** Log out the current session (best-effort) and clear it. No-op if none. */
135356
+ /**
135357
+ * Log out the current session (best-effort) and clear it. No-op if none. A
135358
+ * login still in flight is awaited first, so its session is logged out too.
135359
+ */
135301
135360
  async logout() {
135361
+ if (this.inFlightLogin !== void 0) await this.inFlightLogin.catch(() => void 0);
135302
135362
  const id = this.currentSessionId;
135303
135363
  if (id === void 0) return;
135304
135364
  this.currentSessionId = void 0;
135305
135365
  await this.client.post(JsonRpcMethod.SESSION_LOGOUT, void 0, { sessionId: id });
135306
135366
  }
135307
- /** Ensure a usable session exists: login if none, else renew. Returns the id. */
135308
- async ensureSession() {
135367
+ /** Ensure a usable session exists: login if none, else renew. Returns the id. Concurrent calls share one pass. */
135368
+ ensureSession() {
135369
+ if (this.inFlightEnsure !== void 0) return this.inFlightEnsure;
135370
+ const pass = this.runEnsure().finally(() => {
135371
+ this.inFlightEnsure = void 0;
135372
+ });
135373
+ this.inFlightEnsure = pass;
135374
+ return pass;
135375
+ }
135376
+ /**
135377
+ * A client that sends through this session: a call carrying a session id that
135378
+ * the CCU refuses as `access denied` drops that session, logs in again and is
135379
+ * retried once with the new id. Calls without a session id pass through.
135380
+ */
135381
+ boundClient() {
135382
+ return { post: async (method, params, opts) => {
135383
+ const sid = opts?.sessionId;
135384
+ if (sid === void 0) return this.client.post(method, params, opts);
135385
+ try {
135386
+ return await this.client.post(method, params, opts);
135387
+ } catch (err) {
135388
+ if (!(err instanceof AuthFailureError)) throw err;
135389
+ this.dropSession(sid);
135390
+ const fresh = await this.ensureSession();
135391
+ return this.client.post(method, params, { sessionId: fresh });
135392
+ }
135393
+ } };
135394
+ }
135395
+ async runEnsure() {
135309
135396
  if (this.currentSessionId === void 0) return this.login();
135310
135397
  await this.renew();
135311
135398
  if (this.currentSessionId === void 0) return this.login();
135312
135399
  return this.currentSessionId;
135313
135400
  }
135401
+ async sendLogin() {
135402
+ try {
135403
+ const result = await this.client.post(JsonRpcMethod.SESSION_LOGIN, {
135404
+ username: this.username,
135405
+ password: this.password
135406
+ });
135407
+ const id = String(result);
135408
+ this.currentSessionId = id;
135409
+ this.lastRefresh = this.now();
135410
+ this.resetBackoff();
135411
+ return id;
135412
+ } catch (err) {
135413
+ this.consecutiveFailures += 1;
135414
+ this.nextAttemptAt = this.now() + this.backoffDelayMs();
135415
+ throw err;
135416
+ }
135417
+ }
135418
+ /** Forget `id` if it is still the current session (a newer one stays). */
135419
+ dropSession(id) {
135420
+ if (this.currentSessionId === id) this.currentSessionId = void 0;
135421
+ }
135314
135422
  backoffDelayMs() {
135315
135423
  const exp = INITIAL_BACKOFF_MS * BACKOFF_FACTOR ** (this.consecutiveFailures - 1);
135316
135424
  return Math.min(exp, MAX_BACKOFF_MS);
@@ -137786,7 +137894,7 @@ var HubFetcher = class {
137786
137894
  this.client = options.client;
137787
137895
  this.getSessionId = options.getSessionId;
137788
137896
  }
137789
- sid() {
137897
+ async sid() {
137790
137898
  return this.getSessionId();
137791
137899
  }
137792
137900
  /**
@@ -137795,14 +137903,14 @@ var HubFetcher = class {
137795
137903
  * tolerated (such a variable is treated as read-only).
137796
137904
  */
137797
137905
  async fetchSystemVariables() {
137798
- const sid = this.sid();
137906
+ const sid = await this.sid();
137799
137907
  const entries = asRecordArray2(await this.client.post(JsonRpcMethod.SYSVAR_GET_ALL, void 0, sidOpts(sid)));
137800
137908
  const descriptions = await this.fetchSysVarDescriptions();
137801
137909
  return entries.map((entry) => this.toSystemVariable(entry, descriptions));
137802
137910
  }
137803
137911
  /** Read a single system variable's raw value by name. */
137804
137912
  async getSystemVariable(name2) {
137805
- const sid = this.sid();
137913
+ const sid = await this.sid();
137806
137914
  const raw = await this.client.post(JsonRpcMethod.SYSVAR_GET_VALUE_BY_NAME, { name: name2 }, sidOpts(sid));
137807
137915
  if (typeof raw === "string" || typeof raw === "number" || typeof raw === "boolean") return raw;
137808
137916
  if (raw === null || raw === void 0) return null;
@@ -137814,7 +137922,7 @@ var HubFetcher = class {
137814
137922
  * `SET_SYSTEM_VARIABLE`. A null value is rejected.
137815
137923
  */
137816
137924
  async setSystemVariable(name2, value) {
137817
- const sid = this.sid();
137925
+ const sid = await this.sid();
137818
137926
  if (value === null) throw new ValidationError(`Cannot set system variable "${name2}" to null`);
137819
137927
  if (typeof value === "boolean") {
137820
137928
  await this.client.post(JsonRpcMethod.SYSVAR_SET_BOOL, {
@@ -137837,7 +137945,7 @@ var HubFetcher = class {
137837
137945
  }
137838
137946
  /** Fetch all programs, coercing flags to booleans. */
137839
137947
  async fetchPrograms() {
137840
- const sid = this.sid();
137948
+ const sid = await this.sid();
137841
137949
  return asRecordArray2(await this.client.post(JsonRpcMethod.PROGRAM_GET_ALL, void 0, sidOpts(sid))).map((entry) => {
137842
137950
  const lastExecuteTime = entry.lastExecuteTime;
137843
137951
  return {
@@ -137851,12 +137959,12 @@ var HubFetcher = class {
137851
137959
  }
137852
137960
  /** Execute a program by id. */
137853
137961
  async runProgram(id) {
137854
- const sid = this.sid();
137962
+ const sid = await this.sid();
137855
137963
  await this.client.post(JsonRpcMethod.PROGRAM_EXECUTE, { id }, sidOpts(sid));
137856
137964
  }
137857
137965
  /** Enable/disable a program via the ReGa `SET_PROGRAM_STATE` script. */
137858
137966
  async setProgramActive(id, active) {
137859
- const sid = this.sid();
137967
+ const sid = await this.sid();
137860
137968
  await runScript(this.client, sid, SET_PROGRAM_STATE, {
137861
137969
  id,
137862
137970
  state: active ? 1 : 0
@@ -137867,7 +137975,7 @@ var HubFetcher = class {
137867
137975
  * channel address, decoding the latin1 `UriEncode`d names. Tolerates empty.
137868
137976
  */
137869
137977
  async fetchRoomsFunctions() {
137870
- const sid = this.sid();
137978
+ const sid = await this.sid();
137871
137979
  const parsed = await runScript(this.client, sid, GET_ROOMS_FUNCTIONS);
137872
137980
  return {
137873
137981
  rooms: toDecodedMap(isRecord5(parsed) ? parsed.rooms : void 0),
@@ -137876,7 +137984,7 @@ var HubFetcher = class {
137876
137984
  }
137877
137985
  /** Build the `SYSVAR_DESCRIPTIONS` map: sysvar id → description text. */
137878
137986
  async fetchSysVarDescriptions() {
137879
- const sid = this.sid();
137987
+ const sid = await this.sid();
137880
137988
  const out = /* @__PURE__ */ new Map();
137881
137989
  try {
137882
137990
  const parsed = await runScript(this.client, sid, SYSVAR_DESCRIPTIONS);
@@ -138512,10 +138620,14 @@ var CentralUnit = class {
138512
138620
  */
138513
138621
  getHubFetcher() {
138514
138622
  if (this.jsonClient === void 0) return void 0;
138515
- const client = this.jsonClient;
138623
+ const session = this.session;
138624
+ if (session === void 0) return new HubFetcher({
138625
+ client: this.jsonClient,
138626
+ getSessionId: () => void 0
138627
+ });
138516
138628
  return new HubFetcher({
138517
- client,
138518
- getSessionId: () => this.session?.sessionId
138629
+ client: session.boundClient(),
138630
+ getSessionId: () => session.ensureSession()
138519
138631
  });
138520
138632
  }
138521
138633
  /**
@@ -138526,7 +138638,7 @@ var CentralUnit = class {
138526
138638
  */
138527
138639
  getManagement() {
138528
138640
  return new CcuManagement({
138529
- json: this.jsonClient,
138641
+ json: this.session !== void 0 ? this.session.boundClient() : this.jsonClient,
138530
138642
  webUi: this.webUi,
138531
138643
  getSessionId: () => this.session !== void 0 ? this.session.ensureSession() : Promise.resolve(void 0),
138532
138644
  interfaceClient: (iface) => {
@@ -138716,13 +138828,14 @@ var CentralUnit = class {
138716
138828
  this.webUi = this.options.webUiClient;
138717
138829
  } else {
138718
138830
  const scheme = this.tls ? "https" : "http";
138719
- const client = new JsonRpcClient({ url: `${scheme}://${this.host}` });
138831
+ const client = new JsonRpcClient({ url: this.options.jsonRpcUrl ?? `${scheme}://${this.host}` });
138720
138832
  this.jsonClient = client;
138721
138833
  this.webUi = this.options.webUiClient ?? new WebUiHttpClient({ url: `${scheme}://${this.host}` });
138722
138834
  this.session = new SessionManager({
138723
138835
  client,
138724
138836
  username: this.credentials.username,
138725
- password: this.credentials.password
138837
+ password: this.credentials.password,
138838
+ now: this.now
138726
138839
  });
138727
138840
  }
138728
138841
  }
@@ -138872,8 +138985,9 @@ var CentralUnit = class {
138872
138985
  async fetchDetails() {
138873
138986
  if (this.jsonClient === void 0) return void 0;
138874
138987
  try {
138875
- const sessionId = this.session !== void 0 ? await this.session.ensureSession() : void 0;
138876
- return await mergeDetails(this.jsonClient, sessionId);
138988
+ if (this.session === void 0) return await mergeDetails(this.jsonClient);
138989
+ const sessionId = await this.session.ensureSession();
138990
+ return await mergeDetails(this.session.boundClient(), sessionId);
138877
138991
  } catch {
138878
138992
  return;
138879
138993
  }
@@ -139011,6 +139125,8 @@ var CentralUnit = class {
139011
139125
  } catch {}
139012
139126
  await runtime.client.initProxy();
139013
139127
  runtime.pingPong.reset();
139128
+ this.session?.resetBackoff();
139129
+ this.session?.markStale();
139014
139130
  }
139015
139131
  async reloadData(interfaceId2) {
139016
139132
  const runtime = this.runtimes.get(interfaceId2);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@camstack/addon-provider-homematic",
3
- "version": "1.2.203",
3
+ "version": "1.2.204",
4
4
  "description": "Homematic / HomematicIP (CCU3 / RaspberryMatic) device-provider addon for CamStack — wraps the nodehomematic library",
5
5
  "keywords": [
6
6
  "camstack",
@@ -105,7 +105,7 @@
105
105
  "dev:page": "vite -c vite.page.config.ts"
106
106
  },
107
107
  "dependencies": {
108
- "nodehomematic": "^0.9.0"
108
+ "nodehomematic": "^0.9.1"
109
109
  },
110
110
  "peerDependencies": {
111
111
  "@camstack/types": "*",