@camstack/addon-provider-homematic 1.2.164 → 1.2.165

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/dist/addon.mjs CHANGED
@@ -57011,6 +57011,12 @@ var TerminalInstanceInfoSchema = object({
57011
57011
  instanceId: string(),
57012
57012
  cameraStableId: string(),
57013
57013
  nodeId: string(),
57014
+ /**
57015
+ * False while the node the instance is bound to is not in the cluster
57016
+ * topology (forgotten, renamed, re-paired). The instance is kept; the
57017
+ * operator re-points it with `updateInstance({ targetNodeId })`.
57018
+ */
57019
+ nodeInCluster: boolean(),
57014
57020
  profileId: string(),
57015
57021
  profileLabel: string(),
57016
57022
  name: string(),
@@ -57060,6 +57066,8 @@ method(_void(), array(TerminalProfileInfoSchema).readonly(), { auth: "admin" }),
57060
57066
  auth: "admin"
57061
57067
  }), method(object({
57062
57068
  instanceId: string().min(1),
57069
+ /** Re-point the instance to another node; the profile must exist there. */
57070
+ targetNodeId: string().min(1).max(256).optional(),
57063
57071
  name: string().trim().min(1).max(160).optional(),
57064
57072
  executable: string().max(1024).optional(),
57065
57073
  args: array(string().max(2048)).max(64).optional(),
@@ -113229,6 +113237,19 @@ var CircuitBreakerOpenError = class extends BaseHomematicError {};
113229
113237
  var AuthFailureError = class extends BaseHomematicError {};
113230
113238
  var InternalBackendError = class extends BaseHomematicError {};
113231
113239
  var CommandSupersededError = class extends BaseHomematicError {};
113240
+ var CcuManagementError = class extends BaseHomematicError {
113241
+ /** The XML-RPC / JSON-RPC method that failed. */
113242
+ method;
113243
+ /** The underlying typed error (or whatever was thrown). */
113244
+ original;
113245
+ constructor(method, original) {
113246
+ const detail = original instanceof Error ? original.message : String(original);
113247
+ super(`${method} failed: ${detail}`);
113248
+ this.method = method;
113249
+ this.original = original;
113250
+ }
113251
+ };
113252
+ var GroupWriteVerificationError = class extends BaseHomematicError {};
113232
113253
  var DescriptionNotFoundError = class extends BaseHomematicError {};
113233
113254
  var InvalidStateTransitionError = class extends BaseHomematicError {};
113234
113255
  var TimeoutError = class extends BaseHomematicError {};
@@ -113982,6 +114003,54 @@ var InterfaceClient = class {
113982
114003
  const result = await this.callGuarded("getInstallMode", []);
113983
114004
  return typeof result === "number" ? result : 0;
113984
114005
  }
114006
+ /**
114007
+ * `listBidcosInterfaces()` → the radio gateways of a BidCos interface.
114008
+ *
114009
+ * Source: HomeMatic XML-RPC interface spec (rfd), as consumed by the WebUI in
114010
+ * eq-3/occu `WebUI/www/api/methods/interface/listbidcosinterfaces.tcl`
114011
+ * (fields ADDRESS, DESCRIPTION, DUTY_CYCLE, CONNECTED, DEFAULT,
114012
+ * FIRMWARE_VERSION, TYPE). A field the CCU did not send is `null`, never 0.
114013
+ */
114014
+ async listBidcosInterfaces() {
114015
+ const result = await this.managementCall("listBidcosInterfaces", []);
114016
+ if (!Array.isArray(result)) return [];
114017
+ const gateways = [];
114018
+ for (const entry of result) if (isStruct(entry)) gateways.push(toRadioGateway(entry));
114019
+ return gateways;
114020
+ }
114021
+ /**
114022
+ * `setInstallMode(on[, seconds[, mode]])` — open or close the pairing window.
114023
+ *
114024
+ * Source: HomeMatic XML-RPC interface spec; the WebUI forwards the same call
114025
+ * in eq-3/occu `WebUI/www/api/methods/interface/setinstallmode.tcl` and
114026
+ * `setinstallmodehmip.tcl` (`setInstallMode(bool on, int time)`). `mode`
114027
+ * (1 normal, 2 with the HomeMatic Secure key) is BidCos-only and is sent only
114028
+ * when given.
114029
+ */
114030
+ async setInstallMode(request) {
114031
+ const params = [request.on];
114032
+ if (request.seconds !== void 0) params.push(request.seconds);
114033
+ if (request.mode !== void 0) params.push(request.mode);
114034
+ await this.managementCall("setInstallMode", params);
114035
+ }
114036
+ /**
114037
+ * `getInstallMode()` → seconds left of the pairing window, or `null` when the
114038
+ * CCU answered something that is not an integer (never a fake 0).
114039
+ */
114040
+ async getInstallModeRemaining() {
114041
+ const result = await this.managementCall("getInstallMode", []);
114042
+ return typeof result === "number" && Number.isInteger(result) ? result : null;
114043
+ }
114044
+ /**
114045
+ * `deleteDevice(address, flags)` — remove a device from the interface.
114046
+ *
114047
+ * Source: eq-3/occu `WebUI/www/api/methods/interface/deletedevice.tcl`:
114048
+ * flags 0x01 reset to factory, 0x02 force (also when unreachable), 0x04 defer
114049
+ * until the device is next reachable.
114050
+ */
114051
+ async deleteDevice(address, flags) {
114052
+ await this.managementCall("deleteDevice", [address, flags]);
114053
+ }
113985
114054
  /** `getVersion()` (bypass) → backend version string. */
113986
114055
  async getVersion() {
113987
114056
  return scalarToString(await this.callGuarded("getVersion", [], { bypassBreaker: true }));
@@ -113992,6 +114061,18 @@ var InterfaceClient = class {
113992
114061
  return Array.isArray(result) ? result.map(scalarToString) : [];
113993
114062
  }
113994
114063
  /**
114064
+ * A management call: guarded like any other, but a failure is rethrown as a
114065
+ * {@link CcuManagementError} naming the method and keeping the CCU fault text.
114066
+ */
114067
+ async managementCall(method, params) {
114068
+ try {
114069
+ return await this.callGuarded(method, params);
114070
+ } catch (err) {
114071
+ if (err instanceof BaseHomematicError) throw new CcuManagementError(method, err);
114072
+ throw err;
114073
+ }
114074
+ }
114075
+ /**
113995
114076
  * Invoke `method`, gating non-bypass calls behind the circuit breaker.
113996
114077
  * Bypass methods skip the breaker entirely (no success/failure recorded).
113997
114078
  */
@@ -114046,17 +114127,48 @@ function asDeviceDescriptionArray(value) {
114046
114127
  function asParamsetDescription(value) {
114047
114128
  return asStruct(value);
114048
114129
  }
114130
+ function stringOrNull(value) {
114131
+ return typeof value === "string" && value !== "" ? value : null;
114132
+ }
114133
+ function numberOrNull(value) {
114134
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
114135
+ }
114136
+ function flagOrNull(value) {
114137
+ if (typeof value === "boolean") return value;
114138
+ if (value === 1) return true;
114139
+ if (value === 0) return false;
114140
+ return null;
114141
+ }
114142
+ function toRadioGateway(entry) {
114143
+ const connected = flagOrNull(entry["CONNECTED"]);
114144
+ return {
114145
+ address: stringOrNull(entry["ADDRESS"]) ?? "",
114146
+ description: stringOrNull(entry["DESCRIPTION"]),
114147
+ dutyCycle: numberOrNull(entry["DUTY_CYCLE"]),
114148
+ connected,
114149
+ isDefault: flagOrNull(entry["DEFAULT"]) === true,
114150
+ firmware: stringOrNull(entry["FIRMWARE_VERSION"]),
114151
+ type: stringOrNull(entry["TYPE"])
114152
+ };
114153
+ }
114049
114154
  var SESSION_ID_PARAM = "_session_id_";
114050
114155
  var JsonRpcMethod = {
114051
114156
  CCU_GET_AUTH_ENABLED: "CCU.getAuthEnabled",
114052
114157
  CCU_GET_HTTPS_REDIRECT_ENABLED: "CCU.getHttpsRedirectEnabled",
114158
+ CCU_GET_VERSION: "CCU.getVersion",
114159
+ CCU_GET_SERIAL: "CCU.getSerial",
114160
+ CCU_GET_HEATING_GROUP_LIST: "CCU.getHeatingGroupList",
114053
114161
  DEVICE_LIST_ALL_DETAIL: "Device.listAllDetail",
114162
+ DEVICE_GET_REGA_ID_BY_ADDRESS: "Device.getReGaIDByAddress",
114054
114163
  DEVICE_SET_NAME: "Device.setName",
114055
114164
  CHANNEL_SET_NAME: "Channel.setName",
114056
114165
  INTERFACE_LIST_INTERFACES: "Interface.listInterfaces",
114057
114166
  INTERFACE_LIST_DEVICES: "Interface.listDevices",
114167
+ INTERFACE_IS_PRESENT: "Interface.isPresent",
114168
+ INTERFACE_GET_DUTY_CYCLE: "Interface.getDutyCycle",
114058
114169
  INTERFACE_GET_INSTALL_MODE: "Interface.getInstallMode",
114059
114170
  INTERFACE_SET_INSTALL_MODE_HMIP: "Interface.setInstallModeHMIP",
114171
+ INTERFACE_SET_METADATA: "Interface.setMetadata",
114060
114172
  PROGRAM_GET_ALL: "Program.getAll",
114061
114173
  PROGRAM_EXECUTE: "Program.execute",
114062
114174
  SYSVAR_GET_ALL: "SysVar.getAll",
@@ -114265,6 +114377,691 @@ var SessionManager = class {
114265
114377
  return Math.min(exp, MAX_BACKOFF_MS);
114266
114378
  }
114267
114379
  };
114380
+ var FORM_CONTENT_TYPE = "application/x-www-form-urlencoded; charset=UTF-8";
114381
+ var ESCAPE_SAFE = /[A-Za-z0-9@*_+\-./]/;
114382
+ function jsEscape(text) {
114383
+ let out = "";
114384
+ for (const ch of text) {
114385
+ const unit = ch.charCodeAt(0);
114386
+ if (ESCAPE_SAFE.test(ch)) out += ch;
114387
+ else if (ch.length === 1 && unit < 256) out += `%${unit.toString(16).toUpperCase().padStart(2, "0")}`;
114388
+ else for (let i = 0; i < ch.length; i += 1) out += `%u${ch.charCodeAt(i).toString(16).toUpperCase().padStart(4, "0")}`;
114389
+ }
114390
+ return out;
114391
+ }
114392
+ var WebUiHttpClient = class {
114393
+ base;
114394
+ timeoutMs;
114395
+ fetchFn;
114396
+ dispatcher;
114397
+ constructor(options) {
114398
+ this.base = options.url.replace(/\/+$/, "");
114399
+ this.timeoutMs = options.timeoutMs ?? TIMEOUTS.rpc;
114400
+ this.dispatcher = options.rejectUnauthorized === false ? new import_undici.Agent({ connect: { rejectUnauthorized: false } }) : void 0;
114401
+ this.fetchFn = options.fetch ?? this.defaultFetch.bind(this);
114402
+ }
114403
+ get(path, sessionId) {
114404
+ return this.request("GET", path, sessionId, void 0);
114405
+ }
114406
+ post(path, sessionId, body) {
114407
+ return this.request("POST", path, sessionId, body);
114408
+ }
114409
+ async close() {
114410
+ await this.dispatcher?.close();
114411
+ }
114412
+ async request(method, path, sessionId, body) {
114413
+ const url = `${this.base}${path}?sid=${encodeURIComponent(sessionId)}`;
114414
+ const controller = new AbortController();
114415
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
114416
+ try {
114417
+ const response = await this.fetchFn(url, {
114418
+ method,
114419
+ headers: body === void 0 ? {} : { "Content-Type": FORM_CONTENT_TYPE },
114420
+ body,
114421
+ signal: controller.signal
114422
+ });
114423
+ const text = await response.text();
114424
+ if (response.status < 200 || response.status >= 300) throw new ClientError(`HTTP ${response.status}`);
114425
+ return text;
114426
+ } catch (err) {
114427
+ const mapped = err instanceof ClientError ? err : mapTransportError(err);
114428
+ throw new CcuManagementError(`${method} ${path}`, /* @__PURE__ */ new Error(`${mapped.name}: ${mapped.message.split(sessionId).join("<sid>")}`));
114429
+ } finally {
114430
+ clearTimeout(timer);
114431
+ }
114432
+ }
114433
+ async defaultFetch(url, init) {
114434
+ const req = {
114435
+ method: init.method,
114436
+ headers: init.headers,
114437
+ signal: init.signal
114438
+ };
114439
+ if (init.body !== void 0) req.body = init.body;
114440
+ if (this.dispatcher) req.dispatcher = this.dispatcher;
114441
+ return (0, import_undici.fetch)(url, req);
114442
+ }
114443
+ };
114444
+ function escapeRegaString(s) {
114445
+ return s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
114446
+ }
114447
+ var CONTROL_CHARS = /[\u0000-\u001F]/g;
114448
+ function sanitizeJsonControlChars(s) {
114449
+ return s.replace(CONTROL_CHARS, "");
114450
+ }
114451
+ function decodeRegaName(encoded) {
114452
+ const bytes = [];
114453
+ for (let i = 0; i < encoded.length; i += 1) {
114454
+ const ch = encoded[i];
114455
+ if (ch === "%" && i + 2 < encoded.length) {
114456
+ const hex = encoded.slice(i + 1, i + 3);
114457
+ const byte = Number.parseInt(hex, 16);
114458
+ if (!Number.isNaN(byte) && /^[0-9a-fA-F]{2}$/.test(hex)) {
114459
+ bytes.push(byte);
114460
+ i += 2;
114461
+ continue;
114462
+ }
114463
+ }
114464
+ if (ch === "+") {
114465
+ bytes.push(32);
114466
+ continue;
114467
+ }
114468
+ bytes.push(ch.charCodeAt(0) & 255);
114469
+ }
114470
+ return Buffer.from(bytes).toString("latin1");
114471
+ }
114472
+ function substitute(body, params) {
114473
+ let out = body;
114474
+ for (const [key, value] of Object.entries(params)) {
114475
+ const escaped = escapeRegaString(String(value));
114476
+ out = out.split(`##${key}##`).join(escaped);
114477
+ }
114478
+ return out;
114479
+ }
114480
+ async function runScript(client, sessionId, body, params) {
114481
+ const script = params ? substitute(body, params) : body;
114482
+ const result = await client.post(JsonRpcMethod.REGA_RUN_SCRIPT, { script }, sessionId !== void 0 ? { sessionId } : void 0);
114483
+ if (result === void 0 || result === null) throw new ClientError("ReGa.runScript returned no result");
114484
+ if (typeof result === "string") return JSON.parse(sanitizeJsonControlChars(result));
114485
+ return result;
114486
+ }
114487
+ var SET_SYSTEM_VARIABLE = `object sv = dom.GetObject("##name##");
114488
+ if (sv) {
114489
+ sv.State("##value##");
114490
+ }`;
114491
+ var SET_PROGRAM_STATE = `object prog = dom.GetObject(##id##);
114492
+ if (prog) {
114493
+ prog.Active(##state##);
114494
+ }`;
114495
+ var SYSVAR_DESCRIPTIONS = `string sSysVarId;
114496
+ string sSep = "";
114497
+ WriteLine("[");
114498
+ foreach(sSysVarId, dom.GetObject(ID_SYSTEM_VARIABLES).EnumUsedIDs()) {
114499
+ object oSysVar = dom.GetObject(sSysVarId);
114500
+ Write(sSep);
114501
+ Write("{");
114502
+ Write("\\"id\\":");
114503
+ Write(oSysVar.ID());
114504
+ Write(",\\"description\\":\\"");
114505
+ Write(oSysVar.DPInfo().UriEncode());
114506
+ Write("\\"}");
114507
+ sSep = ",";
114508
+ }
114509
+ WriteLine("]");`;
114510
+ var GET_ROOMS_FUNCTIONS = `string sChnId;
114511
+ string sRoomId;
114512
+ string sFuncId;
114513
+ string sChnSepR = "";
114514
+ string sChnSepF = "";
114515
+ Write("{\\"rooms\\":{");
114516
+ foreach(sChnId, dom.GetObject(ID_CHANNELS).EnumUsedIDs()) {
114517
+ object oChn = dom.GetObject(sChnId);
114518
+ if (oChn) {
114519
+ string sAddr = oChn.Address();
114520
+ object oRooms = oChn.ChnRoom();
114521
+ if (oRooms && oRooms.Count() > 0) {
114522
+ Write(sChnSepR);
114523
+ Write("\\"");
114524
+ Write(sAddr);
114525
+ Write("\\":[");
114526
+ string sRoomSep = "";
114527
+ foreach(sRoomId, oRooms) {
114528
+ object oRoom = dom.GetObject(sRoomId);
114529
+ Write(sRoomSep);
114530
+ Write("\\"");
114531
+ Write(oRoom.Name().UriEncode());
114532
+ Write("\\"");
114533
+ sRoomSep = ",";
114534
+ }
114535
+ Write("]");
114536
+ sChnSepR = ",";
114537
+ }
114538
+ }
114539
+ }
114540
+ Write("},\\"functions\\":{");
114541
+ foreach(sChnId, dom.GetObject(ID_CHANNELS).EnumUsedIDs()) {
114542
+ object oChn = dom.GetObject(sChnId);
114543
+ if (oChn) {
114544
+ string sAddr = oChn.Address();
114545
+ object oFuncs = oChn.ChnFunction();
114546
+ if (oFuncs && oFuncs.Count() > 0) {
114547
+ Write(sChnSepF);
114548
+ Write("\\"");
114549
+ Write(sAddr);
114550
+ Write("\\":[");
114551
+ string sFuncSep = "";
114552
+ foreach(sFuncId, oFuncs) {
114553
+ object oFunc = dom.GetObject(sFuncId);
114554
+ Write(sFuncSep);
114555
+ Write("\\"");
114556
+ Write(oFunc.Name().UriEncode());
114557
+ Write("\\"");
114558
+ sFuncSep = ",";
114559
+ }
114560
+ Write("]");
114561
+ sChnSepF = ",";
114562
+ }
114563
+ }
114564
+ }
114565
+ Write("}}");`;
114566
+ var GET_SERVICE_MESSAGES = `string sAID;
114567
+ string sSep = "";
114568
+ Write("[");
114569
+ foreach(sAID, dom.GetObject(ID_SERVICES).EnumIDs()) {
114570
+ object oAlarm = dom.GetObject(sAID);
114571
+ if (oAlarm) {
114572
+ if (oAlarm.IsTypeOf(OT_ALARMDP)) {
114573
+ if (oAlarm.AlState() == asOncoming) {
114574
+ string sAddr = "";
114575
+ string sType = "";
114576
+ string sAck = "true";
114577
+ object oLast = dom.GetObject(oAlarm.LastTriggerID());
114578
+ if (oLast) {
114579
+ sType = oLast.HSSID();
114580
+ object oChn = dom.GetObject(oLast.Channel());
114581
+ if (oChn) {
114582
+ sAddr = oChn.Address();
114583
+ }
114584
+ }
114585
+ object oTrig = dom.GetObject(oAlarm.AlTriggerDP());
114586
+ if (oTrig) {
114587
+ if (!(oTrig.Operations() & OPERATION_WRITE)) {
114588
+ sAck = "false";
114589
+ }
114590
+ }
114591
+ Write(sSep);
114592
+ Write("{\\"id\\":");
114593
+ Write(oAlarm.ID());
114594
+ Write(",\\"name\\":\\"");
114595
+ Write(oAlarm.Name().UriEncode());
114596
+ Write("\\",\\"address\\":\\"");
114597
+ Write(sAddr);
114598
+ Write("\\",\\"type\\":\\"");
114599
+ Write(sType);
114600
+ Write("\\",\\"timestamp\\":");
114601
+ Write(oAlarm.AlOccurrenceTime().ToInteger());
114602
+ Write(",\\"acknowledgeable\\":");
114603
+ Write(sAck);
114604
+ Write("}");
114605
+ sSep = ",";
114606
+ }
114607
+ }
114608
+ }
114609
+ }
114610
+ Write("]");`;
114611
+ var ACKNOWLEDGE_SERVICE_MESSAGE = `object oAlarm = dom.GetObject(##id##);
114612
+ if (oAlarm) {
114613
+ oAlarm.AlReceipt();
114614
+ Write("{\\"ok\\":true}");
114615
+ } else {
114616
+ Write("{\\"ok\\":false}");
114617
+ }`;
114618
+ var GET_CCU_PLATFORM = `string sRelease;
114619
+ string sHost;
114620
+ string sErr;
114621
+ system.Exec("cat /VERSION", &sRelease, &sErr);
114622
+ system.Exec("hostname", &sHost, &sErr);
114623
+ Write("{\\"release\\":\\"");
114624
+ Write(sRelease.UriEncode());
114625
+ Write("\\",\\"host\\":\\"");
114626
+ Write(sHost.UriEncode());
114627
+ Write("\\"}");`;
114628
+ var GROUP_CREATE_PATH = "/pages/jpages/group/create";
114629
+ var GROUP_SAVE_PATH = "/pages/jpages/group/save";
114630
+ var GROUP_DELETE_PATH = "/pages/jpages/group/delete";
114631
+ var DRAFT_GROUP_ID = /self\.groupId\s*=\s*(\d+)/;
114632
+ var KNOWN_GROUP_TYPES = ["hmip.heating.group", "HomeMatic.heating"];
114633
+ var CHANNEL_ADDRESS = /^[0-9A-Za-z_-]+:\d+$/;
114634
+ var MAX_GROUP_NAME = 64;
114635
+ var DEFAULT_INSTALL_SECONDS = 60;
114636
+ var MAX_INSTALL_SECONDS = 3600;
114637
+ var SERVICE_MESSAGE_ID = /^\d+$/;
114638
+ function isRecord(value) {
114639
+ return value !== null && typeof value === "object" && !Array.isArray(value);
114640
+ }
114641
+ function asRecordArray(value) {
114642
+ return Array.isArray(value) ? value.filter(isRecord) : [];
114643
+ }
114644
+ function strOrNull(value) {
114645
+ if (typeof value === "string") return value === "" ? null : value;
114646
+ if (typeof value === "number" && Number.isFinite(value)) return String(value);
114647
+ return null;
114648
+ }
114649
+ function numOrNull(value) {
114650
+ if (value === null || value === void 0 || value === "") return null;
114651
+ const num = typeof value === "number" ? value : Number(value);
114652
+ return Number.isFinite(num) ? num : null;
114653
+ }
114654
+ var INTERFACES_BY_NAME = new Map(Object.values(Interface).map((iface) => [iface.toString(), iface]));
114655
+ function toInterface(name) {
114656
+ const match = INTERFACES_BY_NAME.get(name);
114657
+ if (match === void 0) throw new ValidationError(`Unknown interface "${name}".`);
114658
+ return match;
114659
+ }
114660
+ function toGateway(info) {
114661
+ return { ...info };
114662
+ }
114663
+ function decodedOrNull(value) {
114664
+ if (typeof value !== "string") return null;
114665
+ const text = decodeRegaName(value).trim();
114666
+ return text === "" ? null : text;
114667
+ }
114668
+ function parseKeyValueLines(text) {
114669
+ const out = /* @__PURE__ */ new Map();
114670
+ for (const line of text.split(/\r?\n/)) {
114671
+ const eq = line.indexOf("=");
114672
+ if (eq > 0) out.set(line.slice(0, eq).trim(), line.slice(eq + 1).trim());
114673
+ }
114674
+ return out;
114675
+ }
114676
+ var OPENCCU_PRODUCTS = /* @__PURE__ */ new Set([
114677
+ "raspberrymatic",
114678
+ "openccu",
114679
+ "ova"
114680
+ ]);
114681
+ function productFamily(raw) {
114682
+ if (raw === null) return "unknown";
114683
+ const key = raw.toLowerCase();
114684
+ if (key === "ccu3") return "ccu3";
114685
+ return OPENCCU_PRODUCTS.has(key) ? "openccu" : "unknown";
114686
+ }
114687
+ var CcuManagement = class {
114688
+ json;
114689
+ webUi;
114690
+ getSessionId;
114691
+ interfaceClient;
114692
+ configuredInterfaces;
114693
+ constructor(options) {
114694
+ this.json = options.json;
114695
+ this.webUi = options.webUi;
114696
+ this.getSessionId = options.getSessionId;
114697
+ this.interfaceClient = options.interfaceClient;
114698
+ this.configuredInterfaces = options.configuredInterfaces;
114699
+ }
114700
+ /**
114701
+ * Every interface the CCU offers (JSON-RPC `Interface.listInterfaces`), with
114702
+ * connection state, duty cycle and, for BidCos, the radio gateways. Without a
114703
+ * JSON-RPC client only the configured interfaces are listed and every probe
114704
+ * result is `null`.
114705
+ */
114706
+ async listInterfaces() {
114707
+ const offered = await this.offeredInterfaces();
114708
+ const gatewaysByName = /* @__PURE__ */ new Map();
114709
+ for (const entry of offered) {
114710
+ const iface = INTERFACES_BY_NAME.get(entry.name);
114711
+ const client = iface === void 0 ? void 0 : this.interfaceClient(iface);
114712
+ if (client === void 0 || iface !== "BidCos-RF" && iface !== "HmIP-RF") continue;
114713
+ const gateways = await this.tryOrNull(() => client.listBidcosInterfaces());
114714
+ if (gateways !== null) gatewaysByName.set(entry.name, gateways.map(toGateway));
114715
+ }
114716
+ const fallbackDuty = offered.some((e) => e.name === "BidCos-RF".toString() && (gatewaysByName.get(e.name) ?? []).every((g) => g.dutyCycle === null)) ? await this.ownRadioDutyCycle() : null;
114717
+ const result = [];
114718
+ for (const entry of offered) {
114719
+ const gateways = gatewaysByName.get(entry.name) ?? [];
114720
+ const primary = gateways.find((g) => g.isDefault) ?? gateways[0];
114721
+ const connected = primary?.connected ?? await this.isPresent(entry.name);
114722
+ const dutyCycle = primary?.dutyCycle ?? (entry.name === "BidCos-RF".toString() ? fallbackDuty : null);
114723
+ result.push({
114724
+ name: entry.name,
114725
+ port: entry.port,
114726
+ info: entry.info,
114727
+ connected,
114728
+ dutyCycle,
114729
+ firmware: primary?.firmware ?? null,
114730
+ type: primary?.type ?? null,
114731
+ gateways
114732
+ });
114733
+ }
114734
+ return result;
114735
+ }
114736
+ /** Open (default 60 s) or close the pairing window of a configured interface. */
114737
+ async setInstallMode(request) {
114738
+ const client = this.requireClient(request.interface);
114739
+ if (!request.on) {
114740
+ await client.setInstallMode({ on: false });
114741
+ return;
114742
+ }
114743
+ const seconds = request.seconds ?? DEFAULT_INSTALL_SECONDS;
114744
+ if (!Number.isInteger(seconds) || seconds < 1 || seconds > MAX_INSTALL_SECONDS) throw new ValidationError(`seconds must be an integer between 1 and ${MAX_INSTALL_SECONDS}, got ${String(seconds)}.`);
114745
+ const call = request.mode === void 0 ? {
114746
+ on: true,
114747
+ seconds
114748
+ } : {
114749
+ on: true,
114750
+ seconds,
114751
+ mode: request.mode === "secure" ? 2 : 1
114752
+ };
114753
+ await client.setInstallMode(call);
114754
+ }
114755
+ /** Seconds left of the pairing window; `null` when the CCU's answer was unusable. */
114756
+ async getInstallMode(interfaceName) {
114757
+ return this.requireClient(interfaceName).getInstallModeRemaining();
114758
+ }
114759
+ /** Every active service message (ReGa listing of `ID_SERVICES`). */
114760
+ async serviceMessages() {
114761
+ return asRecordArray(await this.rega("ReGa.runScript(serviceMessages)", GET_SERVICE_MESSAGES)).flatMap((entry) => {
114762
+ const id = strOrNull(entry["id"]);
114763
+ if (id === null) return [];
114764
+ const address = strOrNull(entry["address"]);
114765
+ const colon = address === null ? -1 : address.lastIndexOf(":");
114766
+ const device = address === null ? null : colon === -1 ? address : address.slice(0, colon);
114767
+ const channel = address === null || colon === -1 ? null : numOrNull(address.slice(colon + 1));
114768
+ const seconds = numOrNull(entry["timestamp"]);
114769
+ return [{
114770
+ id,
114771
+ name: decodedOrNull(entry["name"]),
114772
+ address: device,
114773
+ channel,
114774
+ type: strOrNull(entry["type"]),
114775
+ timestamp: seconds === null || seconds <= 0 ? null : seconds * 1e3,
114776
+ acknowledgeable: entry["acknowledgeable"] === true
114777
+ }];
114778
+ });
114779
+ }
114780
+ /** Acknowledge one service message by its id. */
114781
+ async acknowledgeServiceMessage(id) {
114782
+ if (!SERVICE_MESSAGE_ID.test(id)) throw new ValidationError(`Invalid service message id "${id}".`);
114783
+ const raw = await this.rega("ReGa.runScript(acknowledgeServiceMessage)", ACKNOWLEDGE_SERVICE_MESSAGE, { id });
114784
+ if (!isRecord(raw) || raw["ok"] !== true) throw new ValidationError(`Unknown service message "${id}".`);
114785
+ }
114786
+ /** Version, product, serial and hostname; each `null` when unanswered. */
114787
+ async ccuInfo() {
114788
+ const [version, serial, platform] = await Promise.allSettled([
114789
+ this.call(JsonRpcMethod.CCU_GET_VERSION),
114790
+ this.call(JsonRpcMethod.CCU_GET_SERIAL),
114791
+ this.rega("ReGa.runScript(ccuPlatform)", GET_CCU_PLATFORM)
114792
+ ]);
114793
+ if (version.status === "rejected" && serial.status === "rejected" && platform.status === "rejected") throw version.reason instanceof CcuManagementError ? version.reason : new CcuManagementError(JsonRpcMethod.CCU_GET_VERSION, version.reason);
114794
+ const release = platform.status === "fulfilled" && isRecord(platform.value) ? parseKeyValueLines(decodeRegaName(releaseText(platform.value))) : /* @__PURE__ */ new Map();
114795
+ const hostname = platform.status === "fulfilled" && isRecord(platform.value) ? decodedOrNull(platform.value["host"]) : null;
114796
+ const product = strOrNull(release.get("PRODUCT"));
114797
+ return {
114798
+ version: version.status === "fulfilled" ? strOrNull(version.value) : null,
114799
+ product,
114800
+ productFamily: productFamily(product),
114801
+ platform: strOrNull(release.get("PLATFORM")),
114802
+ serial: serial.status === "fulfilled" ? strOrNull(serial.value) : null,
114803
+ hostname
114804
+ };
114805
+ }
114806
+ /**
114807
+ * The heating groups of the CCU ("Gruppen"), read from `CCU.getHeatingGroupList`
114808
+ * (the HMServer's `/etc/config/groups.gson`). `[]` when the CCU has no groups
114809
+ * file. Writes (`createGroup` / `updateGroup` / `deleteGroup`) go through the
114810
+ * HMServer's WebUI pages instead, see the group-writes section below.
114811
+ */
114812
+ async groups() {
114813
+ const raw = await this.call(JsonRpcMethod.CCU_GET_HEATING_GROUP_LIST);
114814
+ if (typeof raw !== "string" || raw.trim() === "") return [];
114815
+ let parsed;
114816
+ try {
114817
+ parsed = JSON.parse(raw);
114818
+ } catch (err) {
114819
+ throw new CcuManagementError(JsonRpcMethod.CCU_GET_HEATING_GROUP_LIST, err);
114820
+ }
114821
+ if (!isRecord(parsed)) return [];
114822
+ return Object.keys(parsed).sort().flatMap((key) => asRecordArray(parsed[key])).flatMap((entry) => {
114823
+ const group = toGroup(entry);
114824
+ return group === null ? [] : [group];
114825
+ });
114826
+ }
114827
+ /** Create a group; resolves with the group as read back from the CCU. */
114828
+ async createGroup(input) {
114829
+ const name = validateGroupName(input.name);
114830
+ const members = validateMembers(input.members);
114831
+ const before = await this.groups();
114832
+ this.validateType(input.type, before);
114833
+ const { webUi, sid } = await this.requireWebUi("group/create");
114834
+ const page = checkWebUiResponse(GROUP_CREATE_PATH, await webUi.get(GROUP_CREATE_PATH, sid));
114835
+ const draft = DRAFT_GROUP_ID.exec(page);
114836
+ if (draft === null || draft[1] === void 0) throw new CcuManagementError(GROUP_CREATE_PATH, new ClientError("no group id in the page"));
114837
+ const draftId = Number(draft[1]);
114838
+ const id = numOrNull(await this.saveGroup(webUi, sid, {
114839
+ groupId: draftId,
114840
+ groupName: jsEscape(name),
114841
+ groupTypeId: input.type,
114842
+ forbidSingleOperation: false,
114843
+ assignedDevicesIds: members,
114844
+ isNewGroup: true,
114845
+ groupDeviceName: `${name} `
114846
+ })) ?? draftId;
114847
+ await this.flagMembers(members, "true");
114848
+ return this.verifyPresent(id, {
114849
+ name,
114850
+ type: input.type,
114851
+ members
114852
+ });
114853
+ }
114854
+ /** Change a group's name and/or member list; resolves with the group read back. */
114855
+ async updateGroup(id, patch) {
114856
+ if (patch.name === void 0 && patch.members === void 0) throw new ValidationError("updateGroup needs a name and/or members.");
114857
+ const name = patch.name === void 0 ? void 0 : validateGroupName(patch.name);
114858
+ const members = patch.members === void 0 ? void 0 : validateMembers(patch.members);
114859
+ const current = await this.requireGroup(id);
114860
+ const { webUi, sid } = await this.requireWebUi("group/save");
114861
+ const nextName = name ?? current.name;
114862
+ const nextMembers = members ?? current.members.map((m) => m.address);
114863
+ await this.saveGroup(webUi, sid, {
114864
+ groupId: id,
114865
+ groupName: jsEscape(nextName),
114866
+ groupTypeId: current.type,
114867
+ forbidSingleOperation: current.forbidSingleOperation,
114868
+ assignedDevicesIds: nextMembers,
114869
+ isNewGroup: false,
114870
+ groupDeviceName: current.deviceAddress === null ? nextName : `${nextName} ${virtualDeviceSerial(id)}`
114871
+ });
114872
+ await this.flagMembers(nextMembers, "true");
114873
+ const kept = new Set(nextMembers);
114874
+ await this.flagMembers(current.members.map((m) => m.address).filter((a) => !kept.has(a)), "false");
114875
+ return this.verifyPresent(id, {
114876
+ name: nextName,
114877
+ type: current.type,
114878
+ members: nextMembers
114879
+ });
114880
+ }
114881
+ /** Delete a group; verified by the group being gone from the read-back. */
114882
+ async deleteGroup(id) {
114883
+ const current = await this.requireGroup(id);
114884
+ const { webUi, sid } = await this.requireWebUi("group/delete");
114885
+ checkWebUiResponse(GROUP_DELETE_PATH, await webUi.post(GROUP_DELETE_PATH, sid, JSON.stringify({ groupId: id })));
114886
+ await this.flagMembers(current.members.map((m) => m.address), "false");
114887
+ if ((await this.groups()).some((g) => g.id === id)) throw new GroupWriteVerificationError(`Group ${id} is still listed after deleteGroup.`);
114888
+ }
114889
+ async requireGroup(id) {
114890
+ if (!Number.isInteger(id)) throw new ValidationError(`Invalid group id ${String(id)}.`);
114891
+ const found = (await this.groups()).find((g) => g.id === id);
114892
+ if (found === void 0) throw new ValidationError(`Unknown group ${id}.`);
114893
+ return found;
114894
+ }
114895
+ validateType(type, existing) {
114896
+ const known = /* @__PURE__ */ new Set([...KNOWN_GROUP_TYPES, ...existing.map((g) => g.type)]);
114897
+ if (!known.has(type)) throw new ValidationError(`Unknown group type "${type}" (known: ${[...known].join(", ")}).`);
114898
+ }
114899
+ async requireWebUi(label) {
114900
+ if (this.webUi === void 0) throw new ValidationError(`${label} needs WebUI credentials (HMServer pages); none are configured.`);
114901
+ const sid = await this.getSessionId();
114902
+ if (sid === void 0) throw new ValidationError(`${label} needs a WebUI session.`);
114903
+ return {
114904
+ webUi: this.webUi,
114905
+ sid
114906
+ };
114907
+ }
114908
+ /** POST `group/save`; returns the response `content` (the group id as text). */
114909
+ async saveGroup(webUi, sid, payload) {
114910
+ return checkWebUiResponse(GROUP_SAVE_PATH, await webUi.post(GROUP_SAVE_PATH, sid, JSON.stringify(payload)));
114911
+ }
114912
+ /**
114913
+ * The WebUI marks every device it puts in / takes out of a heating group with
114914
+ * `Interface.setMetadata inHeatingGroup` (its pages use the flag to hide
114915
+ * grouped devices). Best effort: the hint is cosmetic and the group itself is
114916
+ * verified separately.
114917
+ */
114918
+ async flagMembers(addresses, value) {
114919
+ const devices = [...new Set(addresses.map((a) => a.slice(0, a.lastIndexOf(":"))))];
114920
+ for (const address of devices) try {
114921
+ const objectId = await this.call(JsonRpcMethod.DEVICE_GET_REGA_ID_BY_ADDRESS, { address });
114922
+ if (typeof objectId !== "string" || objectId === "" || objectId === "noDeviceFound") continue;
114923
+ await this.call(JsonRpcMethod.INTERFACE_SET_METADATA, {
114924
+ objectId,
114925
+ dataId: "inHeatingGroup",
114926
+ value
114927
+ });
114928
+ } catch {}
114929
+ }
114930
+ async verifyPresent(id, want) {
114931
+ const found = (await this.groups()).find((g) => g.id === id);
114932
+ if (found === void 0) throw new GroupWriteVerificationError(`Group ${id} is not listed after the write.`);
114933
+ const have = found.members.map((m) => m.address).sort();
114934
+ const expected = [...want.members].sort();
114935
+ const sameMembers = have.length === expected.length && have.every((a, i) => a === expected[i]);
114936
+ if (found.name !== want.name || found.type !== want.type || !sameMembers) throw new GroupWriteVerificationError(`Group ${id} reads back as "${found.name}" (${found.type}, ${have.length} members), expected "${want.name}" (${want.type}, ${expected.length} members).`);
114937
+ return found;
114938
+ }
114939
+ requireClient(interfaceName) {
114940
+ const iface = toInterface(interfaceName);
114941
+ const client = this.interfaceClient(iface);
114942
+ if (client === void 0) throw new ValidationError(`Interface "${interfaceName}" is not configured.`);
114943
+ return client;
114944
+ }
114945
+ requireJson(method) {
114946
+ if (this.json === void 0) throw new ValidationError(`${method} needs WebUI credentials (JSON-RPC); none are configured.`);
114947
+ return this.json;
114948
+ }
114949
+ /** A session-bound JSON-RPC call whose failure names the method. */
114950
+ async call(method, params) {
114951
+ const json = this.requireJson(method);
114952
+ try {
114953
+ const sessionId = await this.getSessionId();
114954
+ return await json.post(method, params, sessionId !== void 0 ? { sessionId } : void 0);
114955
+ } catch (err) {
114956
+ throw err instanceof ValidationError ? err : new CcuManagementError(method, err);
114957
+ }
114958
+ }
114959
+ async rega(label, script, params) {
114960
+ const json = this.requireJson(label);
114961
+ try {
114962
+ return await runScript(json, await this.getSessionId(), script, params);
114963
+ } catch (err) {
114964
+ throw err instanceof ValidationError ? err : new CcuManagementError(label, err);
114965
+ }
114966
+ }
114967
+ async tryOrNull(fn) {
114968
+ try {
114969
+ return await fn();
114970
+ } catch {
114971
+ return null;
114972
+ }
114973
+ }
114974
+ async offeredInterfaces() {
114975
+ if (this.json === void 0) return this.configuredInterfaces().map((iface) => ({
114976
+ name: iface,
114977
+ port: null,
114978
+ info: null
114979
+ }));
114980
+ return asRecordArray(await this.call(JsonRpcMethod.INTERFACE_LIST_INTERFACES)).flatMap((entry) => {
114981
+ const name = strOrNull(entry["name"]);
114982
+ return name === null ? [] : [{
114983
+ name,
114984
+ port: numOrNull(entry["port"]),
114985
+ info: strOrNull(entry["info"])
114986
+ }];
114987
+ });
114988
+ }
114989
+ async isPresent(name) {
114990
+ if (this.json === void 0) return null;
114991
+ const answer = await this.tryOrNull(() => this.call(JsonRpcMethod.INTERFACE_IS_PRESENT, { interface: name }));
114992
+ if (typeof answer === "boolean") return answer;
114993
+ if (answer === "true") return true;
114994
+ if (answer === "false") return false;
114995
+ return null;
114996
+ }
114997
+ /**
114998
+ * Fallback when `listBidcosInterfaces` gave no answer: `Interface.getDutyCycle`
114999
+ * (RaspberryMatic / OpenCCU) reports the CCU's own radio module as ONE entry
115000
+ * with string numbers (`"7"`). It cannot be attributed to HmIP, so it only
115001
+ * ever stands in for BidCos-RF; non-numeric or absent is `null`.
115002
+ */
115003
+ async ownRadioDutyCycle() {
115004
+ if (this.json === void 0) return null;
115005
+ const entries = asRecordArray(await this.tryOrNull(() => this.call(JsonRpcMethod.INTERFACE_GET_DUTY_CYCLE)));
115006
+ return entries.length === 1 ? numOrNull(entries[0]?.["dutyCycle"]) : null;
115007
+ }
115008
+ };
115009
+ function releaseText(value) {
115010
+ const release = value["release"];
115011
+ return typeof release === "string" ? release : "";
115012
+ }
115013
+ var DEVICE_ADDRESS_SUFFIX = /\b(INT\d{7})\s*$/;
115014
+ function toGroup(entry) {
115015
+ const id = numOrNull(entry["id"]);
115016
+ if (id === null) return null;
115017
+ const props = isRecord(entry["groupProperties"]) ? entry["groupProperties"] : {};
115018
+ const groupType = isRecord(entry["groupType"]) ? entry["groupType"] : {};
115019
+ const deviceName = strOrNull(props["GROUP_DEVICE_NAME"]);
115020
+ const deviceMatch = deviceName === null ? null : DEVICE_ADDRESS_SUFFIX.exec(deviceName);
115021
+ const members = asRecordArray(entry["groupMembers"]).flatMap((m) => {
115022
+ const address = strOrNull(m["id"]);
115023
+ if (address === null) return [];
115024
+ return [{
115025
+ address,
115026
+ type: (isRecord(m["memberType"]) ? strOrNull(m["memberType"]["id"]) : null) ?? ""
115027
+ }];
115028
+ });
115029
+ return {
115030
+ id,
115031
+ name: (strOrNull(props["NAME"]) ?? "").trim(),
115032
+ type: strOrNull(groupType["id"]) ?? "",
115033
+ typeLabel: strOrNull(groupType["label"]),
115034
+ deviceAddress: deviceMatch === null ? null : deviceMatch[1] ?? null,
115035
+ forbidSingleOperation: props["FORBID_SINGLE_OPERATION"] === true,
115036
+ members
115037
+ };
115038
+ }
115039
+ function virtualDeviceSerial(id) {
115040
+ return `INT${String(id).padStart(7, "0")}`;
115041
+ }
115042
+ function validateGroupName(raw) {
115043
+ const name = raw.replace(/"/g, "'").trim();
115044
+ if (name === "" || name.length > MAX_GROUP_NAME) throw new ValidationError(`Group name must be 1..${MAX_GROUP_NAME} characters.`);
115045
+ return name;
115046
+ }
115047
+ function validateMembers(members) {
115048
+ for (const address of members) if (!CHANNEL_ADDRESS.test(address)) throw new ValidationError(`Invalid member channel address "${address}".`);
115049
+ return [...new Set(members)];
115050
+ }
115051
+ function checkWebUiResponse(path, text) {
115052
+ let parsed;
115053
+ try {
115054
+ parsed = JSON.parse(text);
115055
+ } catch {
115056
+ throw new CcuManagementError(path, new ClientError("response was not JSON"));
115057
+ }
115058
+ if (!isRecord(parsed) || parsed["isSuccessful"] !== true) {
115059
+ const code = isRecord(parsed) ? strOrNull(parsed["errorCode"]) : null;
115060
+ throw new CcuManagementError(path, new ClientError(code === "42" ? "session expired (errorCode 42)" : `refused (errorCode ${code ?? "none"})`));
115061
+ }
115062
+ const content = parsed["content"];
115063
+ return typeof content === "string" || typeof content === "number" ? String(content) : "";
115064
+ }
114268
115065
  var FAULT_METHOD_NOT_FOUND = -32601;
114269
115066
  var FAULT_INTERNAL_ERROR = -32603;
114270
115067
  var MethodNotFoundError = class extends BaseHomematicError {};
@@ -115172,128 +115969,6 @@ function asString(value) {
115172
115969
  if (typeof value === "string" && value !== "") return value;
115173
115970
  if (typeof value === "number") return String(value);
115174
115971
  }
115175
- function escapeRegaString(s) {
115176
- return s.replace(/\\/g, "\\\\").replace(/"/g, "\\\"");
115177
- }
115178
- var CONTROL_CHARS = /[\u0000-\u001F]/g;
115179
- function sanitizeJsonControlChars(s) {
115180
- return s.replace(CONTROL_CHARS, "");
115181
- }
115182
- function decodeRegaName(encoded) {
115183
- const bytes = [];
115184
- for (let i = 0; i < encoded.length; i += 1) {
115185
- const ch = encoded[i];
115186
- if (ch === "%" && i + 2 < encoded.length) {
115187
- const hex = encoded.slice(i + 1, i + 3);
115188
- const byte = Number.parseInt(hex, 16);
115189
- if (!Number.isNaN(byte) && /^[0-9a-fA-F]{2}$/.test(hex)) {
115190
- bytes.push(byte);
115191
- i += 2;
115192
- continue;
115193
- }
115194
- }
115195
- if (ch === "+") {
115196
- bytes.push(32);
115197
- continue;
115198
- }
115199
- bytes.push(ch.charCodeAt(0) & 255);
115200
- }
115201
- return Buffer.from(bytes).toString("latin1");
115202
- }
115203
- function substitute(body, params) {
115204
- let out = body;
115205
- for (const [key, value] of Object.entries(params)) {
115206
- const escaped = escapeRegaString(String(value));
115207
- out = out.split(`##${key}##`).join(escaped);
115208
- }
115209
- return out;
115210
- }
115211
- async function runScript(client, sessionId, body, params) {
115212
- const script = params ? substitute(body, params) : body;
115213
- const result = await client.post(JsonRpcMethod.REGA_RUN_SCRIPT, { script }, sessionId !== void 0 ? { sessionId } : void 0);
115214
- if (result === void 0 || result === null) throw new ClientError("ReGa.runScript returned no result");
115215
- if (typeof result === "string") return JSON.parse(sanitizeJsonControlChars(result));
115216
- return result;
115217
- }
115218
- var SET_SYSTEM_VARIABLE = `object sv = dom.GetObject("##name##");
115219
- if (sv) {
115220
- sv.State("##value##");
115221
- }`;
115222
- var SET_PROGRAM_STATE = `object prog = dom.GetObject(##id##);
115223
- if (prog) {
115224
- prog.Active(##state##);
115225
- }`;
115226
- var SYSVAR_DESCRIPTIONS = `string sSysVarId;
115227
- string sSep = "";
115228
- WriteLine("[");
115229
- foreach(sSysVarId, dom.GetObject(ID_SYSTEM_VARIABLES).EnumUsedIDs()) {
115230
- object oSysVar = dom.GetObject(sSysVarId);
115231
- Write(sSep);
115232
- Write("{");
115233
- Write("\\"id\\":");
115234
- Write(oSysVar.ID());
115235
- Write(",\\"description\\":\\"");
115236
- Write(oSysVar.DPInfo().UriEncode());
115237
- Write("\\"}");
115238
- sSep = ",";
115239
- }
115240
- WriteLine("]");`;
115241
- var GET_ROOMS_FUNCTIONS = `string sChnId;
115242
- string sRoomId;
115243
- string sFuncId;
115244
- string sChnSepR = "";
115245
- string sChnSepF = "";
115246
- Write("{\\"rooms\\":{");
115247
- foreach(sChnId, dom.GetObject(ID_CHANNELS).EnumUsedIDs()) {
115248
- object oChn = dom.GetObject(sChnId);
115249
- if (oChn) {
115250
- string sAddr = oChn.Address();
115251
- object oRooms = oChn.ChnRoom();
115252
- if (oRooms && oRooms.Count() > 0) {
115253
- Write(sChnSepR);
115254
- Write("\\"");
115255
- Write(sAddr);
115256
- Write("\\":[");
115257
- string sRoomSep = "";
115258
- foreach(sRoomId, oRooms) {
115259
- object oRoom = dom.GetObject(sRoomId);
115260
- Write(sRoomSep);
115261
- Write("\\"");
115262
- Write(oRoom.Name().UriEncode());
115263
- Write("\\"");
115264
- sRoomSep = ",";
115265
- }
115266
- Write("]");
115267
- sChnSepR = ",";
115268
- }
115269
- }
115270
- }
115271
- Write("},\\"functions\\":{");
115272
- foreach(sChnId, dom.GetObject(ID_CHANNELS).EnumUsedIDs()) {
115273
- object oChn = dom.GetObject(sChnId);
115274
- if (oChn) {
115275
- string sAddr = oChn.Address();
115276
- object oFuncs = oChn.ChnFunction();
115277
- if (oFuncs && oFuncs.Count() > 0) {
115278
- Write(sChnSepF);
115279
- Write("\\"");
115280
- Write(sAddr);
115281
- Write("\\":[");
115282
- string sFuncSep = "";
115283
- foreach(sFuncId, oFuncs) {
115284
- object oFunc = dom.GetObject(sFuncId);
115285
- Write(sFuncSep);
115286
- Write("\\"");
115287
- Write(oFunc.Name().UriEncode());
115288
- Write("\\"");
115289
- sFuncSep = ",";
115290
- }
115291
- Write("]");
115292
- sChnSepF = ",";
115293
- }
115294
- }
115295
- }
115296
- Write("}}");`;
115297
115972
  var HubValueType = /* @__PURE__ */ ((HubValueType2) => {
115298
115973
  HubValueType2["ALARM"] = "ALARM";
115299
115974
  HubValueType2["FLOAT"] = "FLOAT";
@@ -115332,7 +116007,7 @@ function parseSysVarValue(type, raw) {
115332
116007
  }
115333
116008
  }
115334
116009
  var WRITABLE_MARKER = "HAHM";
115335
- function isRecord(value) {
116010
+ function isRecord2(value) {
115336
116011
  return value !== null && typeof value === "object";
115337
116012
  }
115338
116013
  function asString2(value) {
@@ -115351,9 +116026,9 @@ function asOptionalNumber(value) {
115351
116026
  const num = Number(value);
115352
116027
  return Number.isFinite(num) ? num : void 0;
115353
116028
  }
115354
- function asRecordArray(value) {
116029
+ function asRecordArray2(value) {
115355
116030
  if (!Array.isArray(value)) return [];
115356
- return value.filter(isRecord);
116031
+ return value.filter(isRecord2);
115357
116032
  }
115358
116033
  var HubFetcher = class {
115359
116034
  client;
@@ -115372,7 +116047,7 @@ var HubFetcher = class {
115372
116047
  */
115373
116048
  async fetchSystemVariables() {
115374
116049
  const sid = this.sid();
115375
- const entries = asRecordArray(await this.client.post(JsonRpcMethod.SYSVAR_GET_ALL, void 0, sidOpts(sid)));
116050
+ const entries = asRecordArray2(await this.client.post(JsonRpcMethod.SYSVAR_GET_ALL, void 0, sidOpts(sid)));
115376
116051
  const descriptions = await this.fetchSysVarDescriptions();
115377
116052
  return entries.map((entry) => this.toSystemVariable(entry, descriptions));
115378
116053
  }
@@ -115414,7 +116089,7 @@ var HubFetcher = class {
115414
116089
  /** Fetch all programs, coercing flags to booleans. */
115415
116090
  async fetchPrograms() {
115416
116091
  const sid = this.sid();
115417
- return asRecordArray(await this.client.post(JsonRpcMethod.PROGRAM_GET_ALL, void 0, sidOpts(sid))).map((entry) => {
116092
+ return asRecordArray2(await this.client.post(JsonRpcMethod.PROGRAM_GET_ALL, void 0, sidOpts(sid))).map((entry) => {
115418
116093
  const lastExecuteTime = entry.lastExecuteTime;
115419
116094
  return {
115420
116095
  id: asString2(entry.id),
@@ -115446,8 +116121,8 @@ var HubFetcher = class {
115446
116121
  const sid = this.sid();
115447
116122
  const parsed = await runScript(this.client, sid, GET_ROOMS_FUNCTIONS);
115448
116123
  return {
115449
- rooms: toDecodedMap(isRecord(parsed) ? parsed.rooms : void 0),
115450
- functions: toDecodedMap(isRecord(parsed) ? parsed.functions : void 0)
116124
+ rooms: toDecodedMap(isRecord2(parsed) ? parsed.rooms : void 0),
116125
+ functions: toDecodedMap(isRecord2(parsed) ? parsed.functions : void 0)
115451
116126
  };
115452
116127
  }
115453
116128
  /** Build the `SYSVAR_DESCRIPTIONS` map: sysvar id → description text. */
@@ -115456,7 +116131,7 @@ var HubFetcher = class {
115456
116131
  const out = /* @__PURE__ */ new Map();
115457
116132
  try {
115458
116133
  const parsed = await runScript(this.client, sid, SYSVAR_DESCRIPTIONS);
115459
- for (const entry of asRecordArray(parsed)) {
116134
+ for (const entry of asRecordArray2(parsed)) {
115460
116135
  const id = asString2(entry.id);
115461
116136
  if (id !== "") out.set(id, asString2(entry.description));
115462
116137
  }
@@ -115493,7 +116168,7 @@ function sidOpts(sid) {
115493
116168
  }
115494
116169
  function toDecodedMap(value) {
115495
116170
  const map = /* @__PURE__ */ new Map();
115496
- if (!isRecord(value)) return map;
116171
+ if (!isRecord2(value)) return map;
115497
116172
  for (const [addr, names] of Object.entries(value)) if (Array.isArray(names)) map.set(addr, names.filter((n) => typeof n === "string").map((n) => decodeRegaName(n)));
115498
116173
  return map;
115499
116174
  }
@@ -116022,6 +116697,7 @@ var CentralUnit = class {
116022
116697
  ifaceById = /* @__PURE__ */ new Map();
116023
116698
  jsonClient;
116024
116699
  session;
116700
+ webUi;
116025
116701
  callbackServer;
116026
116702
  router;
116027
116703
  recovery;
@@ -116089,6 +116765,30 @@ var CentralUnit = class {
116089
116765
  });
116090
116766
  }
116091
116767
  /**
116768
+ * Build the {@link CcuManagement} bound to this central's interface clients and
116769
+ * (when credentialed) its JSON-RPC client. The session id is ensured per call
116770
+ * through the {@link SessionManager}, so renews apply. INTERNAL: the facade
116771
+ * exposes it; it is not part of the published surface.
116772
+ */
116773
+ getManagement() {
116774
+ return new CcuManagement({
116775
+ json: this.jsonClient,
116776
+ webUi: this.webUi,
116777
+ getSessionId: () => this.session !== void 0 ? this.session.ensureSession() : Promise.resolve(void 0),
116778
+ interfaceClient: (iface) => {
116779
+ for (const runtime of this.runtimes.values()) if (runtime.iface === iface) return runtime.client;
116780
+ },
116781
+ configuredInterfaces: () => this.interfaces
116782
+ });
116783
+ }
116784
+ /**
116785
+ * Remove a device from the interface owning it, routing by `interfaceId`.
116786
+ * Throws if the interface is unknown.
116787
+ */
116788
+ async deleteDevice(interfaceId2, address, flags) {
116789
+ await this.clientFor(interfaceId2).deleteDevice(address, flags);
116790
+ }
116791
+ /**
116092
116792
  * Read the discovered paramset DESCRIPTION (the spec — types, ranges, flags)
116093
116793
  * for a channel + paramset key from the in-memory {@link ParamsetDescriptionCache}.
116094
116794
  * Returns `undefined` if the paramset has not been discovered. This is the
@@ -116220,10 +116920,14 @@ var CentralUnit = class {
116220
116920
  }
116221
116921
  buildJsonRpc() {
116222
116922
  if (this.credentials === void 0) return;
116223
- if (this.options.jsonClient !== void 0) this.jsonClient = this.options.jsonClient;
116224
- else {
116225
- const client = new JsonRpcClient({ url: `${this.tls ? "https" : "http"}://${this.host}` });
116923
+ if (this.options.jsonClient !== void 0) {
116924
+ this.jsonClient = this.options.jsonClient;
116925
+ this.webUi = this.options.webUiClient;
116926
+ } else {
116927
+ const scheme = this.tls ? "https" : "http";
116928
+ const client = new JsonRpcClient({ url: `${scheme}://${this.host}` });
116226
116929
  this.jsonClient = client;
116930
+ this.webUi = this.options.webUiClient ?? new WebUiHttpClient({ url: `${scheme}://${this.host}` });
116227
116931
  this.session = new SessionManager({
116228
116932
  client,
116229
116933
  username: this.credentials.username,
@@ -117701,7 +118405,7 @@ var TypedEventEmitter = class {
117701
118405
  };
117702
118406
  var DEFAULT_CENTRAL_NAME = "nodehomematic";
117703
118407
  var pendingTestInjectables;
117704
- function toInterface(name) {
118408
+ function toInterface2(name) {
117705
118409
  const match = Object.values(Interface).includes(name) ? name : void 0;
117706
118410
  if (match === void 0) throw new ValidationError(`Unknown interface "${name}".`);
117707
118411
  return match;
@@ -117711,7 +118415,7 @@ function deviceAddressOf4(channelAddress2) {
117711
118415
  return colon === -1 ? channelAddress2 : channelAddress2.slice(0, colon);
117712
118416
  }
117713
118417
  function buildCentral(options, injectables) {
117714
- const interfaces = options.interfaces.map(toInterface);
118418
+ const interfaces = options.interfaces.map(toInterface2);
117715
118419
  if (interfaces.length === 0) throw new ValidationError("At least one interface is required.");
117716
118420
  if (injectables.central !== void 0) return injectables.central;
117717
118421
  return new CentralUnit({
@@ -117744,6 +118448,8 @@ var Homematic = class {
117744
118448
  #started = false;
117745
118449
  /** Bound hub fetcher, or undefined when no JSON-RPC client is available. */
117746
118450
  #hub;
118451
+ /** CCU-management service, built on first use, cleared at stop(). */
118452
+ #management;
117747
118453
  /** Snapshot of system variables, refreshed on start / refreshHub. */
117748
118454
  #sysvars = [];
117749
118455
  /** Snapshot of programs, refreshed on start / refreshHub. */
@@ -117801,6 +118507,7 @@ var Homematic = class {
117801
118507
  this.#customEntityList = [];
117802
118508
  this.#customEntitiesByKey.clear();
117803
118509
  this.#hub = void 0;
118510
+ this.#management = void 0;
117804
118511
  this.#sysvars = [];
117805
118512
  this.#programs = [];
117806
118513
  this.#roomsByDevice.clear();
@@ -117845,6 +118552,98 @@ var Homematic = class {
117845
118552
  await this.#central.installFirmware(device.interfaceId, deviceAddress);
117846
118553
  }
117847
118554
  /**
118555
+ * Every interface the CCU offers (BidCos-RF, HmIP-RF, VirtualDevices, ...)
118556
+ * with connection state, duty cycle, firmware and type where the CCU reports
118557
+ * them. A value the CCU did not answer is `null`, never `0`. Needs a started
118558
+ * facade.
118559
+ *
118560
+ * CCU methods: JSON-RPC `Interface.listInterfaces` / `Interface.isPresent`
118561
+ * (eq-3/occu `WebUI/www/api/methods/interface/`), XML-RPC
118562
+ * `listBidcosInterfaces` on BidCos-RF, JSON-RPC `Interface.getDutyCycle`
118563
+ * (RaspberryMatic / OpenCCU only) for the HmIP access point.
118564
+ */
118565
+ async listInterfaces() {
118566
+ return this.#requireManagement().listInterfaces();
118567
+ }
118568
+ /**
118569
+ * Open (default 60 s, 1..3600) or close the pairing window of a configured
118570
+ * interface. XML-RPC `setInstallMode`; `mode: 'secure'` (BidCos only) also
118571
+ * teaches the HomeMatic Secure key.
118572
+ */
118573
+ async setInstallMode(request) {
118574
+ await this.#requireManagement().setInstallMode(request);
118575
+ }
118576
+ /** Seconds left of an interface's pairing window (`null` when the CCU's answer was unusable). XML-RPC `getInstallMode`. */
118577
+ async getInstallMode(interfaceName) {
118578
+ return this.#requireManagement().getInstallMode(interfaceName);
118579
+ }
118580
+ /**
118581
+ * Remove a device from its interface (XML-RPC `deleteDevice`). `flags` is an OR
118582
+ * of {@link HM_DELETE_FLAGS}: `RESET` (0x01, factory reset), `FORCE` (0x02,
118583
+ * remove even when unreachable), `DEFER` (0x04, remove when next reachable);
118584
+ * `0` is a plain removal. The model drops the device once the CCU reports it
118585
+ * through the `deleteDevices` callback. Throws {@link ValidationError} for an
118586
+ * unknown device or invalid flags.
118587
+ */
118588
+ async deleteDevice(deviceAddress, flags = 0) {
118589
+ this.#requireManagement();
118590
+ const device = this.#devicesByAddress.get(deviceAddress);
118591
+ if (device === void 0) throw new ValidationError(`Unknown device "${deviceAddress}".`);
118592
+ if (!Number.isInteger(flags) || flags < 0 || flags > 7) throw new ValidationError(`Invalid delete flags ${String(flags)} (expected an integer 0..7).`);
118593
+ await this.#central.deleteDevice(device.interfaceId, deviceAddress, flags);
118594
+ }
118595
+ /**
118596
+ * The CCU's active service messages (UNREACH, LOWBAT, CONFIG_PENDING,
118597
+ * STICKY_UNREACH, ...). Needs WebUI credentials. ReGa script over
118598
+ * `ReGa.runScript` (eq-3/occu `WebUI/www/rega/esp/system.fn`, `ID_SERVICES`).
118599
+ */
118600
+ async serviceMessages() {
118601
+ return this.#requireManagement().serviceMessages();
118602
+ }
118603
+ /** Acknowledge a service message by its `id` (ReGa `AlReceipt`, as the WebUI does). Needs WebUI credentials. */
118604
+ async acknowledgeServiceMessage(id) {
118605
+ await this.#requireManagement().acknowledgeServiceMessage(id);
118606
+ }
118607
+ /**
118608
+ * Version, product (CCU3 / RaspberryMatic / OpenCCU), serial and hostname.
118609
+ * Needs WebUI credentials. JSON-RPC `CCU.getVersion`, `CCU.getSerial`
118610
+ * (eq-3/occu `WebUI/www/api/methods/ccu/`) plus a ReGa read of `/VERSION`.
118611
+ */
118612
+ async ccuInfo() {
118613
+ return this.#requireManagement().ccuInfo();
118614
+ }
118615
+ /**
118616
+ * The CCU's heating groups ("Gruppen"): HmIP heating groups and HomeMatic
118617
+ * heating groups with their member channels. Writes are separate and
118618
+ * undocumented: {@link Homematic.createGroup}, `updateGroup`, `deleteGroup`.
118619
+ * JSON-RPC `CCU.getHeatingGroupList` (eq-3/occu
118620
+ * `WebUI/www/api/methods/ccu/getheatinggrouplist.tcl`). Needs WebUI credentials.
118621
+ */
118622
+ async groups() {
118623
+ return this.#requireManagement().groups();
118624
+ }
118625
+ /**
118626
+ * Create a heating group (`type` e.g. `hmip.heating.group`, `members` channel
118627
+ * addresses). Resolves with the group as read back from the CCU; a write the
118628
+ * read-back does not show rejects with `GroupWriteVerificationError`.
118629
+ *
118630
+ * UNDOCUMENTED and firmware-dependent: no CCU API exists for this, so the call
118631
+ * reproduces the WebUI's own HMServer page requests (eq-3/occu
118632
+ * `HMserver/opt/HMServer/pages/GroupEditPage.ftl`, `GroupListPage.ftl`).
118633
+ * Needs WebUI credentials.
118634
+ */
118635
+ async createGroup(input) {
118636
+ return this.#requireManagement().createGroup(input);
118637
+ }
118638
+ /** Rename a group and/or replace its member list (same caveats as {@link Homematic.createGroup}). */
118639
+ async updateGroup(id, patch) {
118640
+ return this.#requireManagement().updateGroup(id, patch);
118641
+ }
118642
+ /** Delete a group, verified by the read-back (same caveats as {@link Homematic.createGroup}). */
118643
+ async deleteGroup(id) {
118644
+ await this.#requireManagement().deleteGroup(id);
118645
+ }
118646
+ /**
117848
118647
  * The MASTER configuration parameters of a channel, with the metadata needed
117849
118648
  * to render a form. Empty array when nothing is known for the channel.
117850
118649
  */
@@ -118232,6 +119031,12 @@ var Homematic = class {
118232
119031
  if (byName !== void 0) return byName.id;
118233
119032
  throw new ValidationError(`Unknown program "${idOrName}".`);
118234
119033
  }
119034
+ /** Return the management service (built on first use), or throw before start(). */
119035
+ #requireManagement() {
119036
+ if (!this.#started) throw new ValidationError("Homematic is not started; call start() first.");
119037
+ this.#management ??= this.#central.getManagement();
119038
+ return this.#management;
119039
+ }
118235
119040
  /** Return the bound hub fetcher, or throw if none (no credentials). */
118236
119041
  #requireHub() {
118237
119042
  if (this.#hub === void 0) throw new ValidationError("Hub is unavailable (no WebUI credentials configured).");