{"version":3,"sources":["../src/index.ts","../src/support/version.ts","../src/central/central-unit.ts","../src/support/constants.ts","../src/support/errors.ts","../src/support/dpk.ts","../src/transport/resilience/state-machine.ts","../src/transport/resilience/circuit-breaker.ts","../src/transport/xmlrpc/fault-codes.ts","../src/transport/resilience/retry.ts","../src/transport/resilience/coalescer.ts","../src/transport/xmlrpc/client.ts","../src/transport/xmlrpc/serialize.ts","../src/transport/xmlrpc/parse.ts","../src/transport/interface-client.ts","../src/transport/jsonrpc/client.ts","../src/transport/jsonrpc/methods.ts","../src/transport/jsonrpc/session.ts","../src/transport/webui/webui-http.ts","../src/central/rega/rega-runner.ts","../src/central/rega/scripts.ts","../src/central/management/ccu-topology.ts","../src/central/rega/key-event-program.ts","../src/central/management/ccu-key-programs.ts","../src/central/rega/key-diagnosis.ts","../src/central/management/ccu-key-diagnosis.ts","../src/central/management/ccu-management.ts","../src/transport/callback-server/server.ts","../src/transport/callback-server/handlers.ts","../src/central/events.ts","../src/central/event-bus.ts","../src/central/device-registry.ts","../src/central/store/description-cache.ts","../src/central/store/value-cache.ts","../src/central/store/storage-backend.ts","../src/central/graph.ts","../src/central/discovery.ts","../src/central/hub/sysvar.ts","../src/central/hub/hub-fetcher.ts","../src/central/connection/connection-state.ts","../src/central/connection/ping-pong.ts","../src/central/connection/recovery.ts","../src/central/connection/scheduler.ts","../src/central/callback-router.ts","../src/model/converter.ts","../src/model/data-point.ts","../src/model/channel.ts","../src/model/device.ts","../src/model/model-builder.ts","../src/api/central-link.ts","../src/api/key-event-diagnosis.ts","../src/api/link-profile.ts","../src/model/custom/registry.ts","../src/model/custom/profile.ts","../src/model/custom/base.ts","../src/model/custom/switch.ts","../src/model/custom/climate.ts","../src/model/custom/helpers.ts","../src/model/custom/light.ts","../src/model/custom/cover.ts","../src/model/custom/lock.ts","../src/model/custom/resolve.ts","../src/model/custom/index.ts","../src/api/emitter.ts","../src/api/homematic.ts","../src/api/types.ts"],"sourcesContent":["// Public API surface of nodehomematic.\n//\n// Only the facade + its public types are exported here; transport, central and\n// model internals stay private to keep the published surface small and stable.\n\nexport { LIBRARY_NAME } from './support/version.js';\n\nexport { Homematic } from './api/homematic.js';\nexport { BackendUnavailableError, LoginBackoffError } from './support/errors.js';\nexport type {\n  HomematicOptions,\n  HomematicCallback,\n  HomematicCredentials,\n  HomematicCache,\n} from './api/homematic.js';\n\nexport { HM_DELETE_FLAGS } from './api/types.js';\nexport type {\n  HmCcuInfo,\n  HmGroup,\n  HmGroupCreate,\n  HmGroupMember,\n  HmGroupUpdate,\n  HmInstallModeKind,\n  HmInstallModeRequest,\n  HmInterfaceInfo,\n  HmRadioGateway,\n  HmServiceMessage,\n  HmDevice,\n  HmChannel,\n  HmChannelLink,\n  HmChannelLinkState,\n  HmCustomLinkProfile,\n  HmDeviceRename,\n  HmLink,\n  HmLinkPressAction,\n  HmLinkProfile,\n  HmKeyEventParameter,\n  HmDiagnosisSection,\n  HmKeyCentralLink,\n  HmKeyChannelClientState,\n  HmKeyChannelDiagnosis,\n  HmKeyChannelXmlRpc,\n  HmKeyDeviceMaintenance,\n  HmKeyEventDiagnosis,\n  HmKeyInterfaceClientState,\n  HmKeyParameterClientState,\n  HmKeyRegaChannel,\n  HmKeyRegaDatapoint,\n  HmKeyRegaDiagnosis,\n  HmKeyProgramReference,\n  HmKeyRegaProgram,\n  HmKeyRegaState,\n  HmParamsetValues,\n  HmKeyEventProgram,\n  HmKeyEventProgramInput,\n  HmKeyEventProgramResult,\n  HmNamedObject,\n  HmRenameDeviceOptions,\n  HmRoom,\n  HmSwitchLinkActions,\n  HmSwitchLinkProfile,\n  HmDataPoint,\n  HmValue,\n  HmConfigParam,\n  HmChannelConfig,\n  DataPointRef,\n  HmCustomEntity,\n  HmClimate,\n  HmSwitch,\n  HmLight,\n  HmCover,\n  HmLock,\n  HmSysVar,\n  HmProgram,\n} from './api/types.js';\n\nexport type {\n  HomematicEventMap,\n  ValueChangedEvent,\n  DeviceEvent,\n  ConnectionEvent,\n} from './api/events.js';\n","export const LIBRARY_NAME = 'nodehomematic' as const;\n\nconst MIN_MAJOR = 20;\n\n/**\n * @internal\n * Internal helper used during bootstrap to validate the running Node.js version.\n * Not part of the public API surface; the public facade lands in Phase 3 and is\n * deliberately not re-exported from `src/index.ts`.\n */\nexport function isSupportedNodeVersion(version: string): boolean {\n  const match = /^v?(\\d+)\\./.exec(version);\n  if (match?.[1] === undefined) return false;\n  const major = Number.parseInt(match[1], 10);\n  return !Number.isNaN(major) && major >= MIN_MAJOR;\n}\n","/**\n * {@link CentralUnit} — the internal facade that orchestrates the Phase 1\n * transport (one {@link InterfaceClient} per interface + a shared\n * {@link CallbackServer} + JSON-RPC session) into a typed device graph and a\n * rock-solid reconnection loop.\n *\n * Responsibilities:\n *  - lifecycle: {@link CentralUnit.start} / {@link CentralUnit.stop};\n *  - cache loading + warm start (rebuild the graph from disk without RPC);\n *  - discovery (paramset descriptions + JSON-RPC name/room merge);\n *  - wiring CCU callbacks → value cache + typed {@link EventBus};\n *  - connection health: per-interface ping/pong, callback liveness, periodic\n *    connection-check, and staged {@link ConnectionRecovery} on loss;\n *  - the Phase 3 read surface: {@link CentralUnit.registry},\n *    {@link CentralUnit.eventBus}, {@link CentralUnit.getValue},\n *    {@link CentralUnit.setValue}, {@link CentralUnit.devices}.\n *\n * NO domain model lives here (that is Phase 3): the graph is raw typed data.\n */\n\nimport { connect, type Socket } from 'node:net';\nimport {\n  Interface,\n  INTERFACE_PORTS,\n  INTERFACE_REMOTE_PATH,\n  ParamsetKey,\n} from '../support/constants.js';\nimport type { ParameterData } from '../transport/xmlrpc/types.js';\nimport { makeDpk, type DataPointKey } from '../support/dpk.js';\nimport { ClientState } from '../transport/resilience/state-machine.js';\nimport { InterfaceClient } from '../transport/interface-client.js';\nimport { JsonRpcClient } from '../transport/jsonrpc/client.js';\nimport { SessionManager } from '../transport/jsonrpc/session.js';\nimport { WebUiHttpClient, type WebUiHttp } from '../transport/webui/webui-http.js';\nimport { CcuManagement } from './management/ccu-management.js';\nimport { CallbackServer } from '../transport/callback-server/server.js';\nimport type { RawCallbackEvent } from '../transport/callback-server/events.js';\nimport type { XmlRpcValue } from '../transport/xmlrpc/types.js';\nimport { EventBus } from './event-bus.js';\nimport { DeviceRegistry } from './device-registry.js';\nimport {\n  DeviceDescriptionCache,\n  ParamsetDescriptionCache,\n  type LoadResult,\n} from './store/description-cache.js';\nimport { ValueCache } from './store/value-cache.js';\nimport {\n  FileStorageBackend,\n  InMemoryStorageBackend,\n  type StorageBackend,\n} from './store/storage-backend.js';\nimport { discoverInterface, mergeDetails, warmStart, type DeviceDetails } from './discovery.js';\nimport { HubFetcher } from './hub/hub-fetcher.js';\nimport type { DeviceNode } from './graph.js';\nimport { ConnectionStateTracker } from './connection/connection-state.js';\nimport { PingPongTracker } from './connection/ping-pong.js';\nimport { ConnectionRecovery, type RecoveryHooks } from './connection/recovery.js';\nimport { Scheduler } from './connection/scheduler.js';\nimport { CallbackRouter } from './callback-router.js';\n\n/** Minimal JSON-RPC client surface the central depends on (injectable for tests). */\nexport interface JsonRpcClientLike {\n  post(\n    method: string,\n    params?: Record<string, unknown>,\n    opts?: { readonly sessionId?: string },\n  ): Promise<unknown>;\n  close(): Promise<void>;\n}\n\n/** WebUI credentials for JSON-RPC name/room metadata. */\nexport interface CentralCredentials {\n  readonly username: string;\n  readonly password: string;\n}\n\n/** Local callback server binding. */\nexport interface CallbackConfig {\n  readonly host: string;\n  readonly port: number;\n}\n\n/** Cache directory / toggle. */\nexport interface CacheConfig {\n  readonly dir?: string;\n  readonly enabled?: boolean;\n}\n\n/** Minimal logger used for the (best-effort) initial-seed debug summary. */\nexport interface CentralLogger {\n  debug(message: string): void;\n}\n\n/** Tunable scheduler/recovery intervals (defaults match the prod plan). */\nexport interface CentralTimings {\n  /** Connection-check cadence in ms (prod: 15000). */\n  readonly connectionCheckMs?: number;\n  /** Periodic value-refresh cadence in ms (prod: 15000). */\n  readonly valueRefreshMs?: number;\n}\n\n/** Construction options for {@link CentralUnit}. */\nexport interface CentralUnitOptions {\n  readonly centralName: string;\n  readonly host: string;\n  readonly interfaces: Interface[];\n  readonly credentials?: CentralCredentials;\n  readonly callback: CallbackConfig;\n  readonly cache?: CacheConfig;\n  readonly storageBackend?: StorageBackend;\n  readonly tls?: boolean;\n  readonly timings?: CentralTimings;\n  /**\n   * Seed each data point's value at start by reading the VALUES paramset of\n   * every discovered channel (best-effort). Mirrors aiohomematic: devices show\n   * values immediately, before the first CCU push. Defaults to `true`.\n   */\n  readonly fetchInitialValues?: boolean;\n  /** Optional logger for the initial-seed debug summary (defaults to no-op). */\n  readonly logger?: CentralLogger;\n  /**\n   * Override the TCP port per interface (some deployments expose the XML-RPC\n   * endpoint on a non-standard port). Falls back to {@link INTERFACE_PORTS}.\n   */\n  readonly interfacePorts?: Partial<Record<Interface, number>>;\n\n  // --- injectables (tests) ---\n  /** Build an {@link InterfaceClient} for an interface (defaults to a real one). */\n  readonly makeInterfaceClient?: (iface: Interface) => InterfaceClient;\n  /** Inject a JSON-RPC client (defaults to a real {@link JsonRpcClient}). */\n  readonly jsonClient?: JsonRpcClientLike;\n  /**\n   * Base URL of the JSON-RPC endpoint (defaults to `http(s)://<host>`). Tests\n   * point it at a fake CCU; the session is managed exactly as in production.\n   */\n  readonly jsonRpcUrl?: string;\n  /** Inject the WebUI HMServer-page transport used for group writes (tests). */\n  readonly webUiClient?: WebUiHttp;\n  /** Injectable clock. */\n  readonly now?: () => number;\n  /** Injectable recovery sleep (tests pass a near-immediate stub). */\n  readonly recoverySleep?: (ms: number) => Promise<void>;\n  /**\n   * Injectable TCP reachability probe for an interface id (defaults to opening a\n   * real socket to host:interfacePort). Tests inject one targeting the fake\n   * CCU's ephemeral port.\n   */\n  readonly tcpProbe?: (interfaceId: string) => Promise<boolean>;\n}\n\nconst DEFAULT_CONNECTION_CHECK_MS = 15_000;\nconst DEFAULT_VALUE_REFRESH_MS = 15_000;\nconst CONNECTION_CHECK_JOB = 'connection-check';\nconst VALUE_REFRESH_JOB = 'value-refresh';\nconst TCP_CHECK_TIMEOUT_MS = 2_000;\n/** Max concurrent getParamset(VALUES) calls during initial-value seeding. */\nconst SEED_CONCURRENCY = 8;\nconst NOOP_LOGGER: CentralLogger = {\n  debug: () => {\n    /* no-op */\n  },\n};\n\nconst DEVICE_CACHE_FILE = 'device_descriptions';\nconst PARAMSET_CACHE_FILE = 'paramset_descriptions';\n\n/** Per-interface runtime bundle the central wires together. */\ninterface InterfaceRuntime {\n  readonly iface: Interface;\n  readonly interfaceId: string;\n  readonly client: InterfaceClient;\n  readonly pingPong: PingPongTracker;\n  /** Monotonic counter producing unique ping tokens. */\n  pingSeq: number;\n}\n\n/** Snapshot of one interface's connection health. */\nexport interface ConnectionInfo {\n  readonly state: ClientState;\n  /** Epoch ms of the latest inbound event on the interface, or `null` when none yet. */\n  readonly lastEventAt: number | null;\n  readonly callbackAlive: boolean;\n}\n\nexport class CentralUnit {\n  private readonly centralName: string;\n  private readonly host: string;\n  private readonly interfaces: Interface[];\n  private readonly credentials: CentralCredentials | undefined;\n  private readonly callbackConfig: CallbackConfig;\n  private readonly cacheEnabled: boolean;\n  private readonly tls: boolean;\n  private readonly now: () => number;\n  private readonly connectionCheckMs: number;\n  private readonly valueRefreshMs: number;\n  private readonly recoverySleep: (ms: number) => Promise<void>;\n  private readonly tcpProbe: (interfaceId: string) => Promise<boolean>;\n  private readonly fetchInitialValues: boolean;\n  private readonly logger: CentralLogger;\n\n  private readonly makeInterfaceClientFn: (iface: Interface) => InterfaceClient;\n\n  private readonly storageBackend: StorageBackend;\n  private readonly deviceCache: DeviceDescriptionCache;\n  private readonly paramsetCache: ParamsetDescriptionCache;\n  private readonly valueCache = new ValueCache();\n  private readonly registryStore = new DeviceRegistry();\n  private readonly bus = new EventBus();\n  private readonly connectionState: ConnectionStateTracker;\n  private readonly scheduler = new Scheduler();\n\n  private readonly runtimes = new Map<string, InterfaceRuntime>();\n  private readonly ifaceById = new Map<string, Interface>();\n  private jsonClient: JsonRpcClientLike | undefined;\n  private session: SessionManager | undefined;\n  private webUi: WebUiHttp | undefined;\n  private callbackServer: CallbackServer | undefined;\n  private router: CallbackRouter | undefined;\n  private recovery: ConnectionRecovery | undefined;\n  private details: DeviceDetails | undefined;\n  private warmStarted = false;\n  private started = false;\n\n  public constructor(private readonly options: CentralUnitOptions) {\n    this.centralName = options.centralName;\n    this.host = options.host;\n    this.interfaces = [...options.interfaces];\n    this.credentials = options.credentials;\n    this.callbackConfig = options.callback;\n    this.cacheEnabled = options.cache?.enabled ?? true;\n    this.tls = options.tls ?? false;\n    this.now = options.now ?? Date.now;\n    this.connectionCheckMs = options.timings?.connectionCheckMs ?? DEFAULT_CONNECTION_CHECK_MS;\n    this.valueRefreshMs = options.timings?.valueRefreshMs ?? DEFAULT_VALUE_REFRESH_MS;\n    this.recoverySleep = options.recoverySleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));\n    this.tcpProbe = options.tcpProbe ?? ((id) => this.defaultTcpCheck(id));\n    this.fetchInitialValues = options.fetchInitialValues ?? true;\n    this.logger = options.logger ?? NOOP_LOGGER;\n    this.makeInterfaceClientFn =\n      options.makeInterfaceClient ?? ((iface) => this.buildRealInterfaceClient(iface));\n\n    this.storageBackend = options.storageBackend ?? this.buildDefaultStorageBackend();\n    this.deviceCache = new DeviceDescriptionCache(this.storageBackend, DEVICE_CACHE_FILE);\n    this.paramsetCache = new ParamsetDescriptionCache(this.storageBackend, PARAMSET_CACHE_FILE);\n    this.connectionState = new ConnectionStateTracker({ eventBus: this.bus, now: this.now });\n  }\n\n  // --- public read surface (Phase 3) ---------------------------------------\n\n  /** The immutable device registry. */\n  public get registry(): DeviceRegistry {\n    return this.registryStore;\n  }\n\n  /** The typed event bus. */\n  public get eventBus(): EventBus {\n    return this.bus;\n  }\n\n  /** A snapshot of all known devices. */\n  public devices(): DeviceNode[] {\n    return this.registryStore.getAll();\n  }\n\n  /** The bound callback-server port (0 until {@link start} binds it). */\n  public get callbackPort(): number {\n    return this.callbackServer?.port ?? this.callbackConfig.port;\n  }\n\n  /** Latest cached value for a data point, or `undefined`. */\n  public getValue(dpk: DataPointKey): unknown {\n    return this.valueCache.get(dpk)?.value;\n  }\n\n  /**\n   * Latest cached value + the time it was recorded, or `undefined` if the data\n   * point has no value yet. Lets the facade backfill data points it builds after\n   * start (e.g. seeded initial values published before the facade subscribed).\n   */\n  public getValueEntry(\n    dpk: DataPointKey,\n  ): { readonly value: unknown; readonly at: number } | undefined {\n    return this.valueCache.get(dpk);\n  }\n\n  /**\n   * Write a value back to the CCU. VALUES paramset routes to `setValue`; MASTER\n   * routes to a single-parameter `putParamset`. Throws if the dpk's interface is\n   * unknown.\n   */\n  public async setValue(dpk: DataPointKey, value: XmlRpcValue): Promise<void> {\n    const runtime = this.runtimes.get(dpk.interfaceId);\n    if (runtime === undefined) {\n      throw new Error(`setValue: unknown interface \"${dpk.interfaceId}\"`);\n    }\n    if (dpk.paramsetKey === (ParamsetKey.MASTER as string)) {\n      await runtime.client.putParamset(dpk.channelAddress, ParamsetKey.MASTER, {\n        [dpk.parameter]: value,\n      });\n      return;\n    }\n    await runtime.client.setValue(dpk.channelAddress, dpk.parameter, value);\n  }\n\n  // --- hub surface (Phase 5) ------------------------------------------------\n\n  /**\n   * Build a {@link HubFetcher} bound to the central's JSON-RPC client and a lazy\n   * session-id getter, or `undefined` when no JSON-RPC client is available (no\n   * credentials → no WebUI access). INTERNAL: the facade uses it to expose the\n   * hub (system variables, programs, rooms/functions); it is not part of the\n   * published surface. The session id is read lazily through the\n   * {@link SessionManager} so it tracks renews; with an injected `jsonClient`\n   * (tests) there is no SessionManager and the getter yields `undefined`, which\n   * is fine for clients that do not require a session.\n   */\n  public getHubFetcher(): HubFetcher | undefined {\n    if (this.jsonClient === undefined) return undefined;\n    const session = this.session;\n    if (session === undefined) {\n      return new HubFetcher({ client: this.jsonClient, getSessionId: () => undefined });\n    }\n    return new HubFetcher({\n      client: session.boundClient(),\n      getSessionId: () => session.ensureSession(),\n    });\n  }\n\n  // --- management surface -------------------------------------------------\n\n  /**\n   * Build the {@link CcuManagement} bound to this central's interface clients and\n   * (when credentialed) its JSON-RPC client. The session id is ensured per call\n   * through the {@link SessionManager}, so renews apply. INTERNAL: the facade\n   * exposes it; it is not part of the published surface.\n   */\n  public getManagement(): CcuManagement {\n    return new CcuManagement({\n      json: this.session !== undefined ? this.session.boundClient() : this.jsonClient,\n      webUi: this.webUi,\n      getSessionId: () =>\n        this.session !== undefined ? this.session.ensureSession() : Promise.resolve(undefined),\n      interfaceClient: (iface) => {\n        for (const runtime of this.runtimes.values()) {\n          if (runtime.iface === iface) return runtime.client;\n        }\n        return undefined;\n      },\n      configuredInterfaces: () => this.interfaces,\n    });\n  }\n\n  /**\n   * Remove a device from the interface owning it, routing by `interfaceId`.\n   * Throws if the interface is unknown.\n   */\n  public async deleteDevice(interfaceId: string, address: string, flags: number): Promise<void> {\n    await this.clientFor(interfaceId).deleteDevice(address, flags);\n  }\n\n  // --- config surface (Phase 3, Task 7) -------------------------------------\n\n  /**\n   * Read the discovered paramset DESCRIPTION (the spec — types, ranges, flags)\n   * for a channel + paramset key from the in-memory {@link ParamsetDescriptionCache}.\n   * Returns `undefined` if the paramset has not been discovered. This is the\n   * metadata used to render a device-configuration UI; it never touches the wire.\n   */\n  public getParamsetSpec(\n    interfaceId: string,\n    channelAddress: string,\n    paramsetKey: ParamsetKey | string,\n  ): Record<string, ParameterData> | undefined {\n    return this.paramsetCache.getParamset(interfaceId, channelAddress, String(paramsetKey));\n  }\n\n  /**\n   * Read the live VALUES of a paramset from the CCU, routing to the right\n   * {@link InterfaceClient} by `interfaceId`. Throws if the interface is unknown.\n   */\n  public async readParamset(\n    interfaceId: string,\n    channelAddress: string,\n    paramsetKey: ParamsetKey | string,\n  ): Promise<Record<string, unknown>> {\n    const client = this.clientFor(interfaceId);\n    return client.getParamset(channelAddress, paramsetKey);\n  }\n\n  /**\n   * Write a whole paramset to the CCU in one call, routing to the right\n   * {@link InterfaceClient} by `interfaceId`. Throws if the interface is unknown.\n   */\n  public async writeParamset(\n    interfaceId: string,\n    channelAddress: string,\n    paramsetKey: ParamsetKey | string,\n    values: Record<string, XmlRpcValue>,\n  ): Promise<void> {\n    const client = this.clientFor(interfaceId);\n    await client.putParamset(channelAddress, paramsetKey, values);\n  }\n\n  /**\n   * Trigger a firmware update for a device, routing to the right\n   * {@link InterfaceClient} by `interfaceId`. Throws if the interface is unknown.\n   */\n  public async installFirmware(interfaceId: string, deviceAddress: string): Promise<void> {\n    const client = this.clientFor(interfaceId);\n    await client.installFirmware(deviceAddress);\n  }\n\n  /**\n   * What the connection tracker knows about one interface: its state, the time\n   * of the latest inbound event of ANY kind (`ConnectionStateTracker.recordEvent`,\n   * called by the callback router for every event), and whether the callback\n   * channel is considered alive (`isCallbackAlive`: true until the silence\n   * exceeds the warn interval, or before the first event). Read only.\n   */\n  public getConnectionInfo(interfaceId: string): ConnectionInfo {\n    return {\n      state: this.connectionState.getState(interfaceId),\n      lastEventAt: this.connectionState.getLastEventAt(interfaceId) ?? null,\n      callbackAlive: this.connectionState.isCallbackAlive(interfaceId),\n    };\n  }\n\n  /** XML-RPC `getLinks(channelAddress, flags)`, routed by interface id. */\n  public async getLinks(\n    interfaceId: string,\n    channelAddress: string,\n    flags: number,\n  ): Promise<XmlRpcValue> {\n    return this.clientFor(interfaceId).getLinks(channelAddress, flags);\n  }\n\n  /** XML-RPC `getMetadata(address, dataId)`, routed by interface id. */\n  public async getMetadata(\n    interfaceId: string,\n    address: string,\n    dataId: string,\n  ): Promise<XmlRpcValue> {\n    return this.clientFor(interfaceId).getMetadata(address, dataId);\n  }\n\n  /**\n   * XML-RPC `reportValueUsage(channelAddress, valueId, refCounter)`, routed by\n   * interface id. `true` when the interface accepted the counter.\n   */\n  public async reportValueUsage(\n    interfaceId: string,\n    channelAddress: string,\n    valueId: string,\n    refCounter: number,\n  ): Promise<boolean> {\n    return this.clientFor(interfaceId).reportValueUsage(channelAddress, valueId, refCounter);\n  }\n\n  /** XML-RPC `addLink(sender, receiver, name, description)`, routed by interface id. */\n  public async addLink(\n    interfaceId: string,\n    sender: string,\n    receiver: string,\n    name: string,\n    description: string,\n  ): Promise<void> {\n    await this.clientFor(interfaceId).addLink(sender, receiver, name, description);\n  }\n\n  /** XML-RPC `removeLink(sender, receiver)`, routed by interface id. */\n  public async removeLink(interfaceId: string, sender: string, receiver: string): Promise<void> {\n    await this.clientFor(interfaceId).removeLink(sender, receiver);\n  }\n\n  /** Resolve the {@link InterfaceClient} bound to `interfaceId`, or throw. */\n  private clientFor(interfaceId: string): InterfaceClient {\n    const runtime = this.runtimes.get(interfaceId);\n    if (runtime === undefined) {\n      throw new Error(`unknown interface \"${interfaceId}\"`);\n    }\n    return runtime.client;\n  }\n\n  // --- lifecycle ------------------------------------------------------------\n\n  /** Start the central: load caches, init proxies, discover, schedule, ready. */\n  public async start(): Promise<void> {\n    if (this.started) return;\n    this.started = true;\n\n    const cacheLoaded = await this.loadCaches();\n    this.warmStarted = this.cacheEnabled && cacheLoaded;\n\n    this.buildRuntimes();\n    this.buildJsonRpc();\n    await this.startCallbackServer();\n    this.buildRecovery();\n    this.buildRouter();\n\n    for (const runtime of this.runtimes.values()) {\n      await runtime.client.initProxy();\n      this.connectionState.setState(runtime.interfaceId, ClientState.CONNECTED);\n    }\n\n    if (this.warmStarted) {\n      this.rebuildFromCache();\n    } else {\n      await this.runFullDiscovery();\n    }\n\n    if (this.fetchInitialValues) {\n      await this.seedInitialValues();\n    }\n\n    this.registerSchedulerJobs();\n    this.scheduler.start();\n\n    await this.bus.publish({ type: 'ready' });\n  }\n\n  /** Stop the central: persist caches, tear down transport + server + session. */\n  public async stop(): Promise<void> {\n    if (!this.started) return;\n    this.started = false;\n\n    this.scheduler.stop();\n    this.recovery?.stop();\n\n    await this.saveCaches();\n\n    for (const runtime of this.runtimes.values()) {\n      try {\n        await runtime.client.deinitProxy();\n      } catch {\n        // best-effort teardown\n      }\n      this.connectionState.setState(runtime.interfaceId, ClientState.DISCONNECTED);\n    }\n\n    if (this.session !== undefined) {\n      try {\n        await this.session.logout();\n      } catch {\n        // best-effort logout\n      }\n    }\n    if (this.jsonClient !== undefined) {\n      await this.jsonClient.close();\n    }\n    if (this.callbackServer !== undefined) {\n      await this.callbackServer.stop();\n    }\n    this.bus.clear();\n  }\n\n  // --- construction helpers -------------------------------------------------\n\n  private buildDefaultStorageBackend(): StorageBackend {\n    const dir = this.options.cache?.dir;\n    if (!this.cacheEnabled || dir === undefined) {\n      return new InMemoryStorageBackend();\n    }\n    return new FileStorageBackend({ dir, centralName: this.centralName });\n  }\n\n  /** Resolve the XML-RPC port for an interface (override → TLS/plain default). */\n  private portFor(iface: Interface): number {\n    const override = this.options.interfacePorts?.[iface];\n    if (override !== undefined) return override;\n    return this.tls ? INTERFACE_PORTS[iface].tls : INTERFACE_PORTS[iface].nonTls;\n  }\n\n  private buildRealInterfaceClient(iface: Interface): InterfaceClient {\n    const auth =\n      this.credentials === undefined\n        ? undefined\n        : { username: this.credentials.username, password: this.credentials.password };\n    const tls = this.tls;\n    const port = this.portFor(iface);\n    // VirtualDevices serves XML-RPC at the `/groups` path; others at root.\n    const path = INTERFACE_REMOTE_PATH[iface];\n    return new InterfaceClient({\n      centralName: this.centralName,\n      interface: iface,\n      host: this.host,\n      port,\n      tls,\n      ...(path !== undefined ? { path } : {}),\n      ...(auth !== undefined ? { auth } : {}),\n      callbackUrlProvider: () => this.callbackUrl(),\n    });\n  }\n\n  private callbackUrl(): string {\n    const port = this.callbackServer?.port ?? this.callbackConfig.port;\n    return `http://${this.callbackConfig.host}:${port}`;\n  }\n\n  private buildRuntimes(): void {\n    for (const iface of this.interfaces) {\n      const client = this.makeInterfaceClientFn(iface);\n      const interfaceId = client.interfaceId;\n      const pingPong = new PingPongTracker({ now: this.now });\n      this.runtimes.set(interfaceId, { iface, interfaceId, client, pingPong, pingSeq: 0 });\n      this.ifaceById.set(interfaceId, iface);\n    }\n  }\n\n  private buildJsonRpc(): void {\n    if (this.credentials === undefined) return;\n    if (this.options.jsonClient !== undefined) {\n      this.jsonClient = this.options.jsonClient;\n      this.webUi = this.options.webUiClient;\n    } else {\n      const scheme = this.tls ? 'https' : 'http';\n      const client = new JsonRpcClient({\n        url: this.options.jsonRpcUrl ?? `${scheme}://${this.host}`,\n      });\n      this.jsonClient = client;\n      this.webUi =\n        this.options.webUiClient ?? new WebUiHttpClient({ url: `${scheme}://${this.host}` });\n      this.session = new SessionManager({\n        client,\n        username: this.credentials.username,\n        password: this.credentials.password,\n        now: this.now,\n      });\n    }\n  }\n\n  private async startCallbackServer(): Promise<void> {\n    this.callbackServer = new CallbackServer({\n      host: this.callbackConfig.host,\n      port: this.callbackConfig.port,\n      onEvent: (event: RawCallbackEvent): void => {\n        // The HTTP handler is sync; routing is fire-and-forget with the bus's\n        // own error isolation handling any rejection downstream.\n        void this.routeEvent(event);\n      },\n    });\n    await this.callbackServer.start();\n  }\n\n  private buildRouter(): void {\n    this.router = new CallbackRouter({\n      eventBus: this.bus,\n      valueCache: this.valueCache,\n      registry: this.registryStore,\n      connectionState: this.connectionState,\n      pingPongFor: (id) => this.runtimes.get(id)?.pingPong,\n      now: this.now,\n      hooks: {\n        onNewDevices: (id, addresses) => this.discoverAddresses(id, addresses, true),\n        onUpdateDevice: (id, address) => this.reDiscoverDevice(id, address),\n        onReaddDevices: (id, addresses) => this.discoverAddresses(id, addresses, true),\n      },\n    });\n  }\n\n  private buildRecovery(): void {\n    const hooks: RecoveryHooks = {\n      tcpCheck: (id) => this.tcpCheck(id),\n      rpcCheck: (id) => this.rpcCheck(id),\n      doReconnect: (id) => this.doReconnect(id),\n      reloadData: (id) => this.reloadData(id),\n      hasExistingClient: (id) => this.runtimes.has(id),\n    };\n    this.recovery = new ConnectionRecovery({\n      eventBus: this.bus,\n      sleep: this.recoverySleep,\n      now: this.now,\n      hooks,\n    });\n  }\n\n  private async routeEvent(event: RawCallbackEvent): Promise<void> {\n    if (this.router === undefined) return;\n    try {\n      await this.router.route(event);\n    } catch {\n      // Router/discovery errors are isolated; a bad push must not crash the\n      // server. The connection-check loop will surface persistent problems.\n    }\n  }\n\n  // --- caches ---------------------------------------------------------------\n\n  /** Load both caches; returns true if a non-empty warm start is possible. */\n  private async loadCaches(): Promise<boolean> {\n    if (!this.cacheEnabled) return false;\n    const deviceResult = await this.deviceCache.load();\n    const paramsetResult = await this.paramsetCache.load();\n    return this.canWarmStart(deviceResult, paramsetResult);\n  }\n\n  private canWarmStart(deviceResult: LoadResult, paramsetResult: LoadResult): boolean {\n    if (deviceResult !== 'loaded' || paramsetResult !== 'loaded') return false;\n    // Non-empty: at least one interface has cached descriptions.\n    return this.deviceCache.getAllInterfaces().length > 0;\n  }\n\n  private async saveCaches(): Promise<void> {\n    if (!this.cacheEnabled) return;\n    await this.deviceCache.saveIfChanged();\n    await this.paramsetCache.saveIfChanged();\n  }\n\n  // --- discovery ------------------------------------------------------------\n\n  /** Warm path: rebuild devices from the loaded caches without any RPC. */\n  private rebuildFromCache(): void {\n    for (const runtime of this.runtimes.values()) {\n      const nodes = warmStart({\n        interfaceId: runtime.interfaceId,\n        deviceCache: this.deviceCache,\n        paramsetCache: this.paramsetCache,\n      });\n      this.upsertNodes(nodes);\n      void this.publishCreated(nodes);\n    }\n  }\n\n  /** Cold path: run full discovery (paramsets + JSON-RPC details) per interface. */\n  private async runFullDiscovery(): Promise<void> {\n    this.details = await this.fetchDetails();\n    for (const runtime of this.runtimes.values()) {\n      const nodes = await discoverInterface({\n        source: runtime.client,\n        deviceCache: this.deviceCache,\n        paramsetCache: this.paramsetCache,\n        ...(this.details !== undefined ? { details: this.details } : {}),\n      });\n      this.upsertNodes(nodes);\n      await this.publishCreated(nodes);\n    }\n  }\n\n  /**\n   * Best-effort: seed each data point's value at start by reading the VALUES\n   * paramset of every discovered channel that has at least one VALUES parameter.\n   * Updates the {@link ValueCache} and publishes a `valueReceived` central event\n   * per (parameter, value) so the value flows through the normal routing path\n   * (facade/data points update automatically). Per-channel failures are caught\n   * and skipped (a channel may not support getParamset VALUES); start() never\n   * throws because of seeding. Runs with bounded concurrency to avoid flooding\n   * the CCU with hundreds of simultaneous calls.\n   */\n  private async seedInitialValues(): Promise<void> {\n    const tasks: Array<() => Promise<number>> = [];\n    for (const runtime of this.runtimes.values()) {\n      for (const node of this.registryStore.getAll()) {\n        if (node.interfaceId !== runtime.interfaceId) continue;\n        for (const channel of node.channels) {\n          if (!this.channelHasValuesParams(channel)) continue;\n          tasks.push(() => this.seedChannel(runtime, channel.address));\n        }\n      }\n    }\n    const seeded = await runBounded(tasks, SEED_CONCURRENCY);\n    if (seeded > 0) {\n      this.logger.debug(`seeded ${seeded} initial value(s) from VALUES paramsets`);\n    }\n  }\n\n  /** True if the channel advertises at least one VALUES parameter. */\n  private channelHasValuesParams(channel: DeviceNode['channels'][number]): boolean {\n    for (const [, specs] of channel.parameters) {\n      if (specs.VALUES !== undefined) return true;\n    }\n    return false;\n  }\n\n  /**\n   * Read the VALUES paramset of one channel and route each (parameter, rawValue)\n   * pair through the value cache + a `valueReceived` event. Returns the number\n   * of values seeded (0 on any failure — best-effort, never throws).\n   */\n  private async seedChannel(runtime: InterfaceRuntime, channelAddress: string): Promise<number> {\n    let count = 0;\n    try {\n      const values = await runtime.client.getParamset(channelAddress, ParamsetKey.VALUES);\n      const receivedAt = this.now();\n      for (const [parameter, rawValue] of Object.entries(values)) {\n        const dpk = makeDpk(runtime.interfaceId, channelAddress, ParamsetKey.VALUES, parameter);\n        this.valueCache.add(dpk, rawValue, receivedAt);\n        await this.bus.publish({\n          type: 'valueReceived',\n          dpk,\n          value: rawValue,\n          receivedAt,\n          origin: 'seed',\n        });\n        count += 1;\n      }\n    } catch {\n      // A channel may not support getParamset(VALUES); skip it, do not abort.\n      return 0;\n    }\n    return count;\n  }\n\n  /** Fetch (and cache) the JSON-RPC name/room/function details, if credentialed. */\n  private async fetchDetails(): Promise<DeviceDetails | undefined> {\n    if (this.jsonClient === undefined) return undefined;\n    try {\n      if (this.session === undefined) return await mergeDetails(this.jsonClient);\n      const sessionId = await this.session.ensureSession();\n      return await mergeDetails(this.session.boundClient(), sessionId);\n    } catch {\n      // Details are best-effort metadata; discovery proceeds without them.\n      return undefined;\n    }\n  }\n\n  /**\n   * Re-read the WebUI names, rooms and functions and keep them for later\n   * discoveries. Resolves `undefined` (and keeps the previous snapshot) when\n   * there is no WebUI login or the read failed.\n   */\n  public async refreshDetails(): Promise<DeviceDetails | undefined> {\n    const fresh = await this.fetchDetails();\n    if (fresh !== undefined) this.details = fresh;\n    return fresh;\n  }\n\n  /**\n   * Incrementally (re-)discover a set of device addresses on an interface. Used\n   * by `newDevices` / `replaceDevice` / `readdedDevice`. Re-runs the full\n   * interface discovery (idempotent: the caches dedup) and re-emits the touched\n   * nodes.\n   */\n  private async discoverAddresses(\n    interfaceId: string,\n    addresses: readonly string[],\n    publish: boolean,\n  ): Promise<void> {\n    const runtime = this.runtimes.get(interfaceId);\n    if (runtime === undefined) return;\n    // The start-time snapshot predates a device that was just paired: re-read it.\n    if (publish) await this.refreshDetails();\n    const nodes = await discoverInterface({\n      source: runtime.client,\n      deviceCache: this.deviceCache,\n      paramsetCache: this.paramsetCache,\n      ...(this.details !== undefined ? { details: this.details } : {}),\n    });\n    const wanted = new Set(addresses.map((a) => deviceAddressOf(a)));\n    const touched = nodes.filter((node) => wanted.has(node.address));\n    this.upsertNodes(touched);\n    if (publish) {\n      for (const node of touched) {\n        await this.bus.publish({ type: 'deviceAdded', address: node.address });\n      }\n      await this.publishCreated(touched);\n    }\n  }\n\n  /** Re-discover a single device after an `updateDevice` hint. */\n  private async reDiscoverDevice(interfaceId: string, address: string): Promise<void> {\n    const deviceAddress = deviceAddressOf(address);\n    this.deviceCache.removeDevice(interfaceId, deviceAddress);\n    this.paramsetCache.removeDevice(interfaceId, deviceAddress);\n    await this.discoverAddresses(interfaceId, [deviceAddress], false);\n  }\n\n  private upsertNodes(nodes: readonly DeviceNode[]): void {\n    for (const node of nodes) {\n      this.registryStore.upsert(node);\n    }\n  }\n\n  private async publishCreated(nodes: readonly DeviceNode[]): Promise<void> {\n    if (nodes.length === 0) return;\n    await this.bus.publish({ type: 'devicesCreated', addresses: nodes.map((n) => n.address) });\n  }\n\n  // --- scheduler / health ---------------------------------------------------\n\n  private registerSchedulerJobs(): void {\n    this.scheduler.add({\n      name: CONNECTION_CHECK_JOB,\n      intervalMs: this.connectionCheckMs,\n      run: () => this.connectionCheck(),\n    });\n    this.scheduler.add({\n      name: VALUE_REFRESH_JOB,\n      intervalMs: this.valueRefreshMs,\n      run: () => Promise.resolve(),\n    });\n  }\n\n  /**\n   * One connection-check pass: ping each interface (recording the token) and\n   * verify callback liveness; on a detected loss, trigger recovery and suspend\n   * the other scheduler jobs until recovery completes.\n   */\n  public async connectionCheck(): Promise<void> {\n    for (const runtime of this.runtimes.values()) {\n      const lost = await this.probeInterface(runtime);\n      if (lost) {\n        await this.triggerRecovery(runtime.interfaceId);\n      }\n    }\n  }\n\n  /** Ping + liveness probe for one interface. Returns true on a detected loss. */\n  private async probeInterface(runtime: InterfaceRuntime): Promise<boolean> {\n    // The token MUST be the exact callerId sent to the CCU: the CCU echoes it\n    // back verbatim as the PONG event's value, which the router reconciles\n    // against the recorded token. Recording the bare seq while sending\n    // `${interfaceId}#${seq}` would make every pong \"unknown\" → a false loss.\n    const token = `${runtime.interfaceId}#${runtime.pingSeq++}`;\n    runtime.pingPong.handleSendPing(token);\n    let pingOk = false;\n    try {\n      pingOk = await runtime.client.ping(token);\n    } catch {\n      pingOk = false;\n    }\n    const callbackAlive = this.connectionState.isCallbackAlive(runtime.interfaceId);\n    return !pingOk || !callbackAlive || runtime.pingPong.isMismatch();\n  }\n\n  private async triggerRecovery(interfaceId: string): Promise<void> {\n    if (this.recovery === undefined) return;\n    this.scheduler.pauseAllExcept(CONNECTION_CHECK_JOB);\n    this.connectionState.setState(interfaceId, ClientState.RECONNECTING, 'loss detected');\n    const recovered = await this.recovery.recover(interfaceId);\n    if (recovered) {\n      this.connectionState.setState(interfaceId, ClientState.CONNECTED, 'recovered');\n      this.scheduler.resume();\n    } else {\n      this.connectionState.setState(interfaceId, ClientState.FAILED, 'recovery failed');\n    }\n  }\n\n  // --- recovery hooks -------------------------------------------------------\n\n  private tcpCheck(interfaceId: string): Promise<boolean> {\n    return this.tcpProbe(interfaceId);\n  }\n\n  private defaultTcpCheck(interfaceId: string): Promise<boolean> {\n    const iface = this.ifaceById.get(interfaceId);\n    if (iface === undefined) return Promise.resolve(false);\n    return this.openTcp(this.host, this.portFor(iface), TCP_CHECK_TIMEOUT_MS);\n  }\n\n  /** Open a TCP socket to host:port; resolves true on connect, false otherwise. */\n  private openTcp(host: string, port: number, timeoutMs: number): Promise<boolean> {\n    return new Promise<boolean>((resolve) => {\n      let settled = false;\n      const finish = (ok: boolean, socket?: Socket): void => {\n        if (settled) return;\n        settled = true;\n        socket?.destroy();\n        resolve(ok);\n      };\n      const socket = connect({ host, port }, () => finish(true, socket));\n      socket.setTimeout(timeoutMs, () => finish(false, socket));\n      socket.once('error', () => finish(false, socket));\n    });\n  }\n\n  private async rpcCheck(interfaceId: string): Promise<boolean> {\n    const runtime = this.runtimes.get(interfaceId);\n    if (runtime === undefined) return false;\n    try {\n      const methods = await runtime.client.listMethods();\n      return methods.length > 0;\n    } catch {\n      try {\n        await runtime.client.getVersion();\n        return true;\n      } catch {\n        return false;\n      }\n    }\n  }\n\n  private async doReconnect(interfaceId: string): Promise<void> {\n    const runtime = this.runtimes.get(interfaceId);\n    if (runtime === undefined) return;\n    try {\n      await runtime.client.deinitProxy();\n    } catch {\n      // ignore: deinit may fail if the CCU forgot us; init below re-establishes.\n    }\n    await runtime.client.initProxy();\n    runtime.pingPong.reset();\n    // The CCU answers again (it may have rebooted and wiped every session): the\n    // next JSON-RPC call logs in at once instead of waiting out the backoff, and\n    // re-validates the session it holds before reusing it.\n    this.session?.resetBackoff();\n    this.session?.markStale();\n  }\n\n  private async reloadData(interfaceId: string): Promise<void> {\n    // Re-sync values only (descriptions stay in cache). Best-effort: re-fetch\n    // the latest value for each known data point on this interface so the value\n    // cache is fresh after a reconnect.\n    const runtime = this.runtimes.get(interfaceId);\n    if (runtime === undefined) return;\n    for (const node of this.registryStore.getAll()) {\n      if (node.interfaceId !== interfaceId) continue;\n      for (const channel of node.channels) {\n        const valuesParams = channel.parameters;\n        for (const [parameter, specs] of valuesParams) {\n          if (specs.VALUES === undefined || !specs.VALUES.readable) continue;\n          try {\n            const value = (await runtime.client.getValue(\n              channel.address,\n              parameter,\n            )) as XmlRpcValue;\n            const dpk = makeDpkValues(interfaceId, channel.address, parameter);\n            this.valueCache.add(dpk, value, this.now());\n          } catch {\n            // skip unreadable / transient failures during re-sync\n          }\n        }\n      }\n    }\n  }\n}\n\n/** Address of the device owning a channel address (`DEV:idx` → `DEV`). */\nfunction deviceAddressOf(channelAddress: string): string {\n  const colon = channelAddress.lastIndexOf(':');\n  return colon === -1 ? channelAddress : channelAddress.slice(0, colon);\n}\n\n/** Build a VALUES dpk (used during value re-sync). */\nfunction makeDpkValues(\n  interfaceId: string,\n  channelAddress: string,\n  parameter: string,\n): DataPointKey {\n  return { interfaceId, channelAddress, paramsetKey: ParamsetKey.VALUES, parameter };\n}\n\n/**\n * Run `tasks` with at most `limit` in flight at once, summing their numeric\n * results. A tiny bounded-parallel map: `limit` workers pull from a shared\n * index until the queue drains. Individual tasks are assumed to handle their\n * own errors (return a count); this never rejects.\n */\nasync function runBounded(\n  tasks: ReadonlyArray<() => Promise<number>>,\n  limit: number,\n): Promise<number> {\n  let next = 0;\n  let total = 0;\n  const worker = async (): Promise<void> => {\n    while (next < tasks.length) {\n      const index = next++;\n      total += await tasks[index]!();\n    }\n  };\n  const workers = Array.from({ length: Math.min(limit, tasks.length) }, () => worker());\n  await Promise.all(workers);\n  return total;\n}\n","/**\n * Protocol constants for talking to a CCU3 / RaspberryMatic, mirroring the\n * authoritative values from aiohomematic's `const.py`.\n */\n\n/** Known CCU interfaces (string values are the on-the-wire interface names). */\nexport enum Interface {\n  BIDCOS_RF = 'BidCos-RF',\n  HMIP_RF = 'HmIP-RF',\n  BIDCOS_WIRED = 'BidCos-Wired',\n  VIRTUAL_DEVICES = 'VirtualDevices',\n}\n\n/** TCP ports for each interface, both plain and TLS. */\nexport interface InterfacePorts {\n  readonly nonTls: number;\n  readonly tls: number;\n}\n\n/** Per-interface port mapping. */\nexport const INTERFACE_PORTS: Readonly<Record<Interface, InterfacePorts>> = {\n  [Interface.BIDCOS_RF]: { nonTls: 2001, tls: 42001 },\n  [Interface.HMIP_RF]: { nonTls: 2010, tls: 42010 },\n  [Interface.BIDCOS_WIRED]: { nonTls: 2000, tls: 42000 },\n  [Interface.VIRTUAL_DEVICES]: { nonTls: 9292, tls: 49292 },\n};\n\n/**\n * Per-interface XML-RPC remote URL path (aiohomematic `remote_path`). Most\n * interfaces expose their XML-RPC endpoint at the server root (`/`) and have NO\n * entry here; only {@link Interface.VIRTUAL_DEVICES} (heating/virtual groups)\n * answers at the `/groups` path on port 9292. The path is appended to\n * `{scheme}://{host}:{port}` when building the proxy URL.\n */\nexport const INTERFACE_REMOTE_PATH: Partial<Record<Interface, string>> = {\n  [Interface.VIRTUAL_DEVICES]: '/groups',\n};\n\n/** JSON-RPC ports for the CCU WebUI. */\nexport const JSON_RPC_PORT = 80;\nexport const JSON_RPC_PORT_TLS = 443;\n\n/** HTTP path of the CCU JSON-RPC endpoint. */\nexport const JSON_RPC_PATH = '/api/homematic.cgi';\n\n/** Outbound XML-RPC payloads are encoded as ISO-8859-1 (latin1). */\nexport const ENCODING_OUT = 'iso-8859-1';\n\n/**\n * Encoding used ONLY to decode the request bodies received by the local\n * callback HTTP server (the CCU POSTs its event/system notifications to us).\n *\n * This is NOT the encoding of XML-RPC RESPONSES we receive from the CCU: those\n * are ISO-8859-1 as declared in their XML prolog and are decoded by the\n * parser's declaration-sniffing (see `decodeInput` in `parse.ts`), NOT by this\n * constant. Do not reuse this value to decode CCU responses.\n */\nexport const ENCODING_IN = 'utf-8';\n\n/** Default timeouts (milliseconds) for the various RPC operations. */\nexport const TIMEOUTS = {\n  /** Generic RPC call timeout. */\n  rpc: 60000,\n  /** Ping timeout. */\n  ping: 10000,\n  /** Connect timeout. */\n  connect: 30000,\n} as const;\n\n/** Build the interface id used to register a callback proxy: `{centralName}-{interface}`. */\nexport function interfaceId(centralName: string, iface: Interface): string {\n  return `${centralName}-${iface}`;\n}\n\n/**\n * Parameter operations bitmask (CCU `OPERATIONS` field). A parameter can be any\n * combination of readable, writable and event-emitting.\n */\nexport enum Operations {\n  NONE = 0,\n  READ = 1,\n  WRITE = 2,\n  EVENT = 4,\n}\n\n/** True if the parameter can be read (`OPERATIONS & READ`). */\nexport function isReadable(op: number): boolean {\n  return (op & Operations.READ) !== 0;\n}\n\n/** True if the parameter can be written (`OPERATIONS & WRITE`). */\nexport function isWritable(op: number): boolean {\n  return (op & Operations.WRITE) !== 0;\n}\n\n/** True if the parameter emits events (`OPERATIONS & EVENT`). */\nexport function hasEvents(op: number): boolean {\n  return (op & Operations.EVENT) !== 0;\n}\n\n/** Parameter flags bitmask (CCU `FLAGS` field). */\nexport enum Flag {\n  VISIBLE = 1,\n  INTERNAL = 2,\n  TRANSFORM = 4,\n  SERVICE = 8,\n  STICKY = 0x10,\n}\n\n/** True if the parameter is visible to the user (`FLAGS & VISIBLE`). */\nexport function isVisible(flags: number): boolean {\n  return (flags & Flag.VISIBLE) !== 0;\n}\n\n/** True if the parameter is a service flag (`FLAGS & SERVICE`). */\nexport function isService(flags: number): boolean {\n  return (flags & Flag.SERVICE) !== 0;\n}\n\n/** Parameter value type (CCU `TYPE` field). `EMPTY` is the empty-string variant. */\nexport enum ParameterType {\n  ACTION = 'ACTION',\n  BOOL = 'BOOL',\n  ENUM = 'ENUM',\n  FLOAT = 'FLOAT',\n  INTEGER = 'INTEGER',\n  STRING = 'STRING',\n  DUMMY = 'DUMMY',\n  EMPTY = '',\n}\n\n/** Paramset identifier. Discovery fetches VALUES + MASTER and skips LINK. */\nexport enum ParamsetKey {\n  MASTER = 'MASTER',\n  VALUES = 'VALUES',\n  LINK = 'LINK',\n  SERVICE = 'SERVICE',\n  CALCULATED = 'CALCULATED',\n  COMBINED = 'COMBINED',\n  DUMMY = 'DUMMY',\n}\n\n/** Device receive-mode bitmask (CCU `RX_MODE` field). */\nexport enum RxMode {\n  UNDEFINED = 0,\n  ALWAYS = 1,\n  BURST = 2,\n  CONFIG = 4,\n  WAKEUP = 8,\n  LAZY_CONFIG = 16,\n}\n\n/** Firmware update lifecycle states reported by the CCU (`FIRMWARE_UPDATE_STATE`). */\nexport enum DeviceFirmwareState {\n  UNKNOWN = 'UNKNOWN',\n  UP_TO_DATE = 'UP_TO_DATE',\n  LIVE_UP_TO_DATE = 'LIVE_UP_TO_DATE',\n  NEW_FIRMWARE_AVAILABLE = 'NEW_FIRMWARE_AVAILABLE',\n  LIVE_NEW_FIRMWARE_AVAILABLE = 'LIVE_NEW_FIRMWARE_AVAILABLE',\n  DELIVER_FIRMWARE_IMAGE = 'DELIVER_FIRMWARE_IMAGE',\n  LIVE_DELIVER_FIRMWARE_IMAGE = 'LIVE_DELIVER_FIRMWARE_IMAGE',\n  READY_FOR_UPDATE = 'READY_FOR_UPDATE',\n  DO_UPDATE_PENDING = 'DO_UPDATE_PENDING',\n  PERFORMING_UPDATE = 'PERFORMING_UPDATE',\n  BACKGROUND_UPDATE_NOT_SUPPORTED = 'BACKGROUND_UPDATE_NOT_SUPPORTED',\n}\n\n/** Per-value status reported alongside a value event. */\nexport enum ParameterStatus {\n  NORMAL = 'NORMAL',\n  UNKNOWN = 'UNKNOWN',\n  OVERFLOW = 'OVERFLOW',\n  UNDERFLOW = 'UNDERFLOW',\n  ERROR = 'ERROR',\n  INVALID = 'INVALID',\n  UNUSED = 'UNUSED',\n  EXTERNAL = 'EXTERNAL',\n}\n","/**\n * Error taxonomy for the transport layer, ported from aiohomematic's exception\n * hierarchy. All errors extend {@link BaseHomematicError}. Mapping helpers turn\n * raw XML-RPC faults, JSON-RPC errors and low-level transport failures into the\n * appropriate typed error.\n */\n\n/** Root of the library error hierarchy. */\nexport class BaseHomematicError extends Error {\n  public constructor(message?: string) {\n    super(message);\n    // Preserve the concrete class name (and a correct prototype chain under\n    // transpilation targets that down-level `extends`).\n    this.name = new.target.name;\n    Object.setPrototypeOf(this, new.target.prototype);\n  }\n}\n\n/** Generic client-side / backend error with no more specific classification. */\nexport class ClientError extends BaseHomematicError {}\n\n/** Operation not supported by the backend or interface. */\nexport class UnsupportedError extends BaseHomematicError {}\n\n/** Input or argument validation failure (caught before hitting the wire). */\nexport class ValidationError extends BaseHomematicError {}\n\n/** No usable network connection to the CCU. */\nexport class NoConnectionError extends BaseHomematicError {}\n\n/** A protected call was rejected because the circuit breaker is OPEN. */\nexport class CircuitBreakerOpenError extends BaseHomematicError {}\n\n/** No interface clients are available to serve a request. */\nexport class NoClientsError extends BaseHomematicError {}\n\n/**\n * A login was not sent because the previous ones failed and the backoff window\n * is still open. Nothing reached the CCU. `retryAt` (epoch ms, on the session\n * manager's clock) is when the next real attempt may go out.\n */\nexport class LoginBackoffError extends BaseHomematicError {\n  /** When the next real login attempt may go out (epoch ms). */\n  public readonly retryAt: number;\n  /** Consecutive failed logins so far. */\n  public readonly failures: number;\n\n  public constructor(retryAt: number, failures: number) {\n    super(\n      `login backing off after ${failures} consecutive failure(s); next attempt at ${new Date(retryAt).toISOString()}`,\n    );\n    this.retryAt = retryAt;\n    this.failures = failures;\n  }\n}\n\n/**\n * The CCU answered with an HTTP 5xx (typically 503 while it is still booting).\n * Transient: the call may succeed once the CCU is up.\n */\nexport class BackendUnavailableError extends BaseHomematicError {\n  /** The HTTP status code the CCU answered. */\n  public readonly status: number;\n\n  public constructor(status: number, message: string) {\n    super(message);\n    this.status = status;\n  }\n}\n\n/** Authentication/authorization against the CCU failed. */\nexport class AuthFailureError extends BaseHomematicError {}\n\n/** The backend reported an internal error. */\nexport class InternalBackendError extends BaseHomematicError {}\n\n/** A newer command superseded this one before it completed. */\nexport class CommandSupersededError extends BaseHomematicError {}\n\n/**\n * A CCU-management call failed. Carries the CCU method that failed (e.g.\n * `deleteDevice`, `Interface.getDutyCycle`) and the original typed error, whose\n * text (fault code and message) is part of this error's message. Never holds\n * credentials or session ids.\n */\nexport class CcuManagementError extends BaseHomematicError {\n  /** The XML-RPC / JSON-RPC method that failed. */\n  public readonly method: string;\n  /** The underlying typed error (or whatever was thrown). */\n  public readonly original: unknown;\n\n  public constructor(method: string, original: unknown) {\n    const detail = original instanceof Error ? original.message : String(original);\n    super(`${method} failed: ${detail}`);\n    this.method = method;\n    this.original = original;\n  }\n}\n\n/**\n * A group write was accepted by the CCU but the read-back (`groups()`) does not\n * show the intended result (or still shows a deleted group).\n */\nexport class GroupWriteVerificationError extends BaseHomematicError {}\n\n/** A requested device/paramset description could not be found. */\nexport class DescriptionNotFoundError extends BaseHomematicError {}\n\n/** An illegal connection state-machine transition was attempted. */\nexport class InvalidStateTransitionError extends BaseHomematicError {}\n\n/** A request exceeded its allotted time budget. */\nexport class TimeoutError extends BaseHomematicError {}\n\n/** Coarse failure classification used by reconnect/health logic. */\nexport enum FailureReason {\n  AUTH = 'AUTH',\n  NETWORK = 'NETWORK',\n  INTERNAL = 'INTERNAL',\n  CIRCUIT_BREAKER = 'CIRCUIT_BREAKER',\n  TIMEOUT = 'TIMEOUT',\n  UNKNOWN = 'UNKNOWN',\n}\n\n/**\n * Map an XML-RPC `<fault>` to a typed error. Classification is by the\n * fault STRING (aiohomematic does the same), not by the numeric code:\n * - contains \"unauthorized\" → {@link AuthFailureError}\n * - contains \"internal\" → {@link InternalBackendError}\n * - otherwise → {@link ClientError}\n */\nexport function mapXmlRpcFault(faultCode: number, faultString: string): BaseHomematicError {\n  const lower = faultString.toLowerCase();\n  const detail = `XML-RPC fault ${faultCode}: ${faultString}`;\n  if (lower.includes('unauthorized')) return new AuthFailureError(detail);\n  if (lower.includes('internal')) return new InternalBackendError(detail);\n  return new ClientError(detail);\n}\n\n/** Shape of a JSON-RPC error object as returned by the CCU WebUI. */\nexport interface JsonRpcErrorLike {\n  readonly code?: number;\n  readonly message?: string;\n}\n\nconst AUTH_CODES = new Set<number>([401, -32001]);\nconst INTERNAL_CODES = new Set<number>([-32603, 500]);\n\n/**\n * Map a JSON-RPC error to a typed error. Classification is by message content\n * first, then by numeric code:\n * - message startsWith \"access denied\" OR code ∈ {401, -32001} → {@link AuthFailureError}\n * - message includes \"internal error\" OR code ∈ {-32603, 500} → {@link InternalBackendError}\n * - otherwise → {@link ClientError}\n */\nexport function mapJsonRpcError(error: JsonRpcErrorLike): BaseHomematicError {\n  const message = error.message ?? '';\n  const lower = message.toLowerCase();\n  const code = error.code;\n  const detail = `JSON-RPC error${code !== undefined ? ` ${code}` : ''}: ${message}`;\n\n  if (lower.startsWith('access denied') || (code !== undefined && AUTH_CODES.has(code))) {\n    return new AuthFailureError(detail);\n  }\n  if (lower.includes('internal error') || (code !== undefined && INTERNAL_CODES.has(code))) {\n    return new InternalBackendError(detail);\n  }\n  return new ClientError(detail);\n}\n\nconst NETWORK_ERROR_CODES = new Set<string>([\n  'ECONNREFUSED',\n  'ECONNRESET',\n  'EHOSTUNREACH',\n  'ENETUNREACH',\n  'ENOTFOUND',\n  'EAI_AGAIN',\n  'EPIPE',\n  'ETIMEDOUT',\n  'UND_ERR_CONNECT_TIMEOUT',\n  'UND_ERR_SOCKET',\n]);\n\nconst NETWORK_ERROR_NAMES = new Set<string>(['AbortError', 'TimeoutError', 'ConnectTimeoutError']);\n\n/**\n * Map a low-level transport failure to a typed error. OS/socket-level failures\n * (and aborts/timeouts) become {@link NoConnectionError}; anything else becomes\n * a {@link ClientError}.\n */\nexport function mapTransportError(err: unknown): BaseHomematicError {\n  if (err instanceof Error) {\n    // fetch/undici wraps the real socket error in `.cause`; inspect both levels.\n    if (isNetworkError(err)) {\n      return new NoConnectionError(err.message);\n    }\n    const cause = (err as { cause?: unknown }).cause;\n    if (cause instanceof Error && isNetworkError(cause)) {\n      return new NoConnectionError(cause.message);\n    }\n    return new ClientError(err.message);\n  }\n  return new ClientError(String(err));\n}\n\nfunction isNetworkError(err: Error): boolean {\n  const code = (err as { code?: unknown }).code;\n  if (typeof code === 'string' && NETWORK_ERROR_CODES.has(code)) return true;\n  return NETWORK_ERROR_NAMES.has(err.name);\n}\n\n/** Reduce a thrown error to a coarse {@link FailureReason}. */\nexport function exceptionToFailureReason(err: unknown): FailureReason {\n  if (err instanceof AuthFailureError) return FailureReason.AUTH;\n  if (err instanceof NoConnectionError) return FailureReason.NETWORK;\n  if (err instanceof InternalBackendError) return FailureReason.INTERNAL;\n  if (err instanceof CircuitBreakerOpenError) return FailureReason.CIRCUIT_BREAKER;\n  if (err instanceof TimeoutError) return FailureReason.TIMEOUT;\n  return FailureReason.UNKNOWN;\n}\n","/**\n * DataPointKey (dpk) — the identity of a single value point on the CCU.\n *\n * A dpk uniquely addresses one parameter inside one paramset of one channel on\n * one interface. It is the routing key used to dispatch `event(...)` callbacks\n * to the right data point and to index the value cache.\n */\n\nimport { ValidationError } from './errors.js';\n\n/** Identity of a single value point. */\nexport interface DataPointKey {\n  /** Interface id, e.g. `MyCCU-HmIP-RF`. */\n  readonly interfaceId: string;\n  /** Channel address, e.g. `VCU0000001:1` (note: may itself contain a colon). */\n  readonly channelAddress: string;\n  /** Paramset key, e.g. `VALUES` / `MASTER`. */\n  readonly paramsetKey: string;\n  /** Parameter name, e.g. `STATE`. */\n  readonly parameter: string;\n}\n\n/** Construct a {@link DataPointKey}. */\nexport function makeDpk(\n  interfaceId: string,\n  channelAddress: string,\n  paramsetKey: string,\n  parameter: string,\n): DataPointKey {\n  return { interfaceId, channelAddress, paramsetKey, parameter };\n}\n\nconst SEPARATOR = ':';\n\n/**\n * Derive the stable, lowercased `unique_id` string from a dpk.\n *\n * Encoding scheme: positional join with `:` —\n * `interfaceId:channelAddress:paramsetKey:parameter` (lowercased).\n *\n * `channelAddress` itself may contain a single colon (e.g. `VCU0000001:1`). The\n * round-trip is kept exact NOT by escaping but by relying on fixed anchors:\n * the FIRST segment is always `interfaceId`, the LAST is always `parameter` and\n * the SECOND-TO-LAST is always `paramsetKey`. Everything between the first and\n * those two trailing anchors is the `channelAddress` (re-joined with `:`).\n * Because `interfaceId`, `paramsetKey` and `parameter` never contain a colon on\n * the CCU, this positional scheme is unambiguous and reversible.\n */\nexport function dpkToUniqueId(dpk: DataPointKey): string {\n  return [dpk.interfaceId, dpk.channelAddress, dpk.paramsetKey, dpk.parameter]\n    .join(SEPARATOR)\n    .toLowerCase();\n}\n\n/**\n * Parse a `unique_id` back into a {@link DataPointKey}. Tolerant of a\n * `channelAddress` that contains colons (see {@link dpkToUniqueId} for the\n * scheme). Throws {@link ValidationError} if fewer than 4 segments are present.\n */\nexport function uniqueIdToDpk(uniqueId: string): DataPointKey {\n  const parts = uniqueId.split(SEPARATOR);\n  if (parts.length < 4) {\n    throw new ValidationError(\n      `Invalid dpk unique id (expected at least 4 ':'-separated segments): ${uniqueId}`,\n    );\n  }\n  // Anchors: first = interfaceId, last = parameter, last-1 = paramsetKey.\n  // The remainder (middle) is the channelAddress, which may contain colons.\n  const interfaceId = parts[0] as string;\n  const parameter = parts[parts.length - 1] as string;\n  const paramsetKey = parts[parts.length - 2] as string;\n  const channelAddress = parts.slice(1, parts.length - 2).join(SEPARATOR);\n  return { interfaceId, channelAddress, paramsetKey, parameter };\n}\n","/**\n * Connection lifecycle state machine for an interface client. Validates\n * transitions against the protocol table, notifies subscribers on change, and\n * computes the exponential reconnect backoff delay.\n */\n\nimport { InvalidStateTransitionError } from '../../support/errors.js';\n\n/** Lifecycle states of an interface client connection. */\nexport enum ClientState {\n  CREATED = 'CREATED',\n  INITIALIZING = 'INITIALIZING',\n  INITIALIZED = 'INITIALIZED',\n  CONNECTING = 'CONNECTING',\n  CONNECTED = 'CONNECTED',\n  DISCONNECTED = 'DISCONNECTED',\n  RECONNECTING = 'RECONNECTING',\n  STOPPING = 'STOPPING',\n  STOPPED = 'STOPPED',\n  FAILED = 'FAILED',\n}\n\n/** Allowed target states for each source state (protocol transition table). */\nexport const VALID_TRANSITIONS: Readonly<Record<ClientState, readonly ClientState[]>> = {\n  [ClientState.CREATED]: [ClientState.INITIALIZING],\n  [ClientState.INITIALIZING]: [ClientState.INITIALIZED, ClientState.FAILED],\n  [ClientState.INITIALIZED]: [ClientState.CONNECTING, ClientState.DISCONNECTED],\n  [ClientState.CONNECTING]: [ClientState.CONNECTED, ClientState.FAILED],\n  [ClientState.CONNECTED]: [\n    ClientState.DISCONNECTED,\n    ClientState.RECONNECTING,\n    ClientState.STOPPING,\n  ],\n  [ClientState.DISCONNECTED]: [\n    ClientState.CONNECTING,\n    ClientState.DISCONNECTED,\n    ClientState.RECONNECTING,\n    ClientState.STOPPING,\n  ],\n  [ClientState.RECONNECTING]: [\n    ClientState.CONNECTED,\n    ClientState.DISCONNECTED,\n    ClientState.FAILED,\n    ClientState.CONNECTING,\n  ],\n  [ClientState.STOPPING]: [ClientState.STOPPED],\n  [ClientState.STOPPED]: [],\n  [ClientState.FAILED]: [\n    ClientState.INITIALIZING,\n    ClientState.CONNECTING,\n    ClientState.RECONNECTING,\n    ClientState.DISCONNECTED,\n  ],\n};\n\n/** Payload delivered to {@link ConnectionStateMachine.onChange} subscribers. */\nexport interface StateChangeEvent {\n  readonly from: ClientState;\n  readonly to: ClientState;\n  readonly reason?: string;\n}\n\ntype ChangeListener = (event: StateChangeEvent) => void;\n\n/** Reconnect backoff tunables. */\nconst RECONNECT = {\n  initialDelayMs: 2000,\n  backoffFactor: 2,\n  maxDelayMs: 120000,\n} as const;\n\nexport class ConnectionStateMachine {\n  private currentState: ClientState;\n  private failure: string | undefined;\n  private readonly listeners = new Set<ChangeListener>();\n\n  public constructor(initial: ClientState = ClientState.CREATED) {\n    this.currentState = initial;\n  }\n\n  /** Current state. */\n  public get state(): ClientState {\n    return this.currentState;\n  }\n\n  /** Reason recorded when the machine last entered FAILED, if any. */\n  public get failureReason(): string | undefined {\n    return this.failure;\n  }\n\n  /**\n   * Transition to `target`. Throws {@link InvalidStateTransitionError} if the\n   * transition is not permitted, leaving the current state untouched.\n   */\n  public transitionTo(target: ClientState, reason?: string): void {\n    const allowed = VALID_TRANSITIONS[this.currentState];\n    if (!allowed.includes(target)) {\n      throw new InvalidStateTransitionError(\n        `Invalid transition ${this.currentState} → ${target}${reason ? ` (${reason})` : ''}`,\n      );\n    }\n    const from = this.currentState;\n    this.currentState = target;\n    if (target === ClientState.FAILED) {\n      this.failure = reason;\n    }\n    const event: StateChangeEvent =\n      reason === undefined ? { from, to: target } : { from, to: target, reason };\n    for (const listener of this.listeners) {\n      listener(event);\n    }\n  }\n\n  /** Subscribe to state changes; returns an unsubscribe function. */\n  public onChange(cb: ChangeListener): () => void {\n    this.listeners.add(cb);\n    return () => {\n      this.listeners.delete(cb);\n    };\n  }\n\n  /**\n   * Reconnect backoff for a given (zero-based) attempt:\n   * `min(initialDelay * factor^attempt, maxDelay)`.\n   */\n  public reconnectDelay(attempt: number): number {\n    const delay = RECONNECT.initialDelayMs * Math.pow(RECONNECT.backoffFactor, attempt);\n    return Math.min(delay, RECONNECT.maxDelayMs);\n  }\n}\n","/**\n * Circuit breaker guarding outbound CCU calls. Mirrors aiohomematic's breaker\n * semantics: CLOSED → OPEN after `failureThreshold` consecutive failures; OPEN\n * → HALF_OPEN once `recoveryTimeoutMs` has elapsed; HALF_OPEN → CLOSED after\n * `successThreshold` successes, or back to OPEN on any failure.\n *\n * The breaker only tracks state; deciding whether a given method bypasses it\n * (init/ping/getVersion/Session.*) is the caller's responsibility.\n */\n\n/** Lifecycle states of the breaker. */\nexport enum CircuitState {\n  CLOSED = 'CLOSED',\n  OPEN = 'OPEN',\n  HALF_OPEN = 'HALF_OPEN',\n}\n\n/** Tunables for {@link CircuitBreaker}. */\nexport interface CircuitBreakerConfig {\n  /** Consecutive failures in CLOSED that trip the breaker open. */\n  readonly failureThreshold?: number;\n  /** Milliseconds the breaker stays OPEN before probing (HALF_OPEN). */\n  readonly recoveryTimeoutMs?: number;\n  /** Successes in HALF_OPEN required to close the breaker. */\n  readonly successThreshold?: number;\n  /** Injectable clock (defaults to `Date.now`). */\n  readonly now?: () => number;\n}\n\nconst DEFAULTS = {\n  failureThreshold: 5,\n  recoveryTimeoutMs: 30000,\n  successThreshold: 2,\n} as const;\n\nexport class CircuitBreaker {\n  private readonly failureThreshold: number;\n  private readonly recoveryTimeoutMs: number;\n  private readonly successThreshold: number;\n  private readonly now: () => number;\n\n  private currentState: CircuitState = CircuitState.CLOSED;\n  private failureCount = 0;\n  private successCount = 0;\n  private openedAt = 0;\n  private rejectionCount = 0;\n\n  public constructor(config: CircuitBreakerConfig = {}) {\n    this.failureThreshold = config.failureThreshold ?? DEFAULTS.failureThreshold;\n    this.recoveryTimeoutMs = config.recoveryTimeoutMs ?? DEFAULTS.recoveryTimeoutMs;\n    this.successThreshold = config.successThreshold ?? DEFAULTS.successThreshold;\n    this.now = config.now ?? ((): number => Date.now());\n  }\n\n  /** Current breaker state. */\n  public get state(): CircuitState {\n    return this.currentState;\n  }\n\n  /**\n   * Whether a protected call may proceed. Has a side effect: an OPEN breaker\n   * whose recovery window has elapsed transitions to HALF_OPEN here.\n   */\n  public isAvailable(): boolean {\n    if (this.currentState === CircuitState.OPEN) {\n      if (this.now() - this.openedAt >= this.recoveryTimeoutMs) {\n        this.toHalfOpen();\n        return true;\n      }\n      return false;\n    }\n    // CLOSED and HALF_OPEN both permit calls.\n    return true;\n  }\n\n  /** Record a successful protected call. */\n  public recordSuccess(): void {\n    if (this.currentState === CircuitState.HALF_OPEN) {\n      this.successCount += 1;\n      if (this.successCount >= this.successThreshold) {\n        this.toClosed();\n      }\n      return;\n    }\n    // A success in CLOSED clears any accumulated failures.\n    this.failureCount = 0;\n  }\n\n  /** Record a failed protected call. */\n  public recordFailure(): void {\n    if (this.currentState === CircuitState.HALF_OPEN) {\n      this.toOpen();\n      return;\n    }\n    if (this.currentState === CircuitState.CLOSED) {\n      this.failureCount += 1;\n      if (this.failureCount >= this.failureThreshold) {\n        this.toOpen();\n      }\n    }\n  }\n\n  /**\n   * Hook invoked when a non-bypass call was rejected because the breaker was\n   * unavailable. Kept minimal (a counter) for observability.\n   */\n  public recordRejection(): void {\n    this.rejectionCount += 1;\n  }\n\n  /** Number of rejected calls (observability only). */\n  public get rejections(): number {\n    return this.rejectionCount;\n  }\n\n  private toOpen(): void {\n    this.currentState = CircuitState.OPEN;\n    this.openedAt = this.now();\n    this.failureCount = 0;\n    this.successCount = 0;\n  }\n\n  private toHalfOpen(): void {\n    this.currentState = CircuitState.HALF_OPEN;\n    this.successCount = 0;\n    this.failureCount = 0;\n  }\n\n  private toClosed(): void {\n    this.currentState = CircuitState.CLOSED;\n    this.failureCount = 0;\n    this.successCount = 0;\n  }\n}\n","/**\n * XML-RPC fault codes used by the Homematic CCU, mirroring aiohomematic's\n * `HmFaultCode` IntEnum, plus the set of codes considered retryable.\n */\n\nexport enum XmlRpcFaultCode {\n  GENERIC = -1,\n  UNKNOWN_DEVICE = -2,\n  UNKNOWN_PARAMSET = -3,\n  ADDRESS_EXPECTED = -4,\n  UNKNOWN_PARAMETER = -5,\n  OP_NOT_SUPPORTED = -6,\n  UPDATE_NOT_POSSIBLE = -7,\n  INSUFFICIENT_DUTYCYCLE = -8,\n  DEVICE_OUT_OF_RANGE = -9,\n  TRANSMISSION_PENDING = -10,\n}\n\n/** Fault codes for which a retry may succeed. */\nexport const RETRYABLE_FAULT_CODES: ReadonlySet<number> = new Set<number>([\n  XmlRpcFaultCode.GENERIC,\n  XmlRpcFaultCode.INSUFFICIENT_DUTYCYCLE,\n  XmlRpcFaultCode.DEVICE_OUT_OF_RANGE,\n  XmlRpcFaultCode.TRANSMISSION_PENDING,\n]);\n\n/** True if the given fault code is retryable. */\nexport function isRetryableFaultCode(code: number): boolean {\n  return RETRYABLE_FAULT_CODES.has(code);\n}\n","/**\n * Retry wrapper for write commands (setValue/putParamset). Classifies errors as\n * retryable or terminal, applies exponential backoff with jitter, and honours\n * the protocol-specific delays for INSUFFICIENT_DUTYCYCLE (-8) and\n * TRANSMISSION_PENDING (-10) faults.\n */\n\nimport {\n  AuthFailureError,\n  CircuitBreakerOpenError,\n  CommandSupersededError,\n  UnsupportedError,\n  ValidationError,\n  TimeoutError,\n  NoConnectionError,\n  InternalBackendError,\n} from '../../support/errors.js';\nimport { XmlRpcFaultCode, isRetryableFaultCode } from '../xmlrpc/fault-codes.js';\n\n/** Options for {@link withRetry}; every field has a protocol-default. */\nexport interface RetryOptions {\n  /** Maximum attempts (including the first). `<= 0` disables retries. */\n  readonly maxAttempts?: number;\n  /** Base backoff delay in ms. */\n  readonly baseDelayMs?: number;\n  /** Exponential growth factor per attempt. */\n  readonly backoffFactor?: number;\n  /** Upper bound for the computed backoff delay in ms. */\n  readonly maxDelayMs?: number;\n  /** Jitter fraction (±), e.g. 0.2 = ±20%. */\n  readonly jitter?: number;\n  /** Delay for fault -8 (INSUFFICIENT_DUTYCYCLE). */\n  readonly dutyCycleDelayMs?: number;\n  /** Delay for fault -10 (TRANSMISSION_PENDING). */\n  readonly transmissionPendingDelayMs?: number;\n  /** Override the retryable classification. */\n  readonly isRetryable?: (err: unknown) => boolean;\n  /** Override fault-code extraction. */\n  readonly getFaultCode?: (err: unknown) => number | undefined;\n  /** Injectable delay (defaults to a setTimeout-based promise). */\n  readonly sleep?: (ms: number) => Promise<void>;\n  /** Injectable randomness for jitter (defaults to `Math.random`). */\n  readonly random?: () => number;\n}\n\nconst DEFAULTS = {\n  maxAttempts: 3,\n  baseDelayMs: 2000,\n  backoffFactor: 2,\n  maxDelayMs: 30000,\n  jitter: 0.2,\n  dutyCycleDelayMs: 40000,\n  transmissionPendingDelayMs: 5000,\n} as const;\n\n/** Error types that are NEVER retried. */\nconst NON_RETRYABLE_TYPES = [\n  AuthFailureError,\n  CircuitBreakerOpenError,\n  CommandSupersededError,\n  UnsupportedError,\n  ValidationError,\n] as const;\n\n/** Error types that ARE retried (independent of any fault code). */\nconst RETRYABLE_TYPES = [TimeoutError, NoConnectionError, InternalBackendError] as const;\n\nconst defaultSleep = (ms: number): Promise<void> =>\n  new Promise((resolve) => setTimeout(resolve, ms));\n\n/**\n * Extract a numeric `faultCode` from an error, walking the `cause` chain.\n * Returns `undefined` when no numeric fault code is present.\n */\nexport function defaultGetFaultCode(err: unknown): number | undefined {\n  let current: unknown = err;\n  // Bound the walk to avoid pathological cyclic cause chains.\n  for (let depth = 0; depth < 16 && current != null; depth += 1) {\n    if (typeof current === 'object') {\n      const code = (current as { faultCode?: unknown }).faultCode;\n      if (typeof code === 'number') return code;\n      current = (current as { cause?: unknown }).cause;\n    } else {\n      break;\n    }\n  }\n  return undefined;\n}\n\n/** Default retryable classification per the protocol facts. */\nfunction defaultIsRetryable(\n  err: unknown,\n  getFaultCode: (e: unknown) => number | undefined,\n): boolean {\n  if (NON_RETRYABLE_TYPES.some((Ctor) => err instanceof Ctor)) return false;\n  if (RETRYABLE_TYPES.some((Ctor) => err instanceof Ctor)) return true;\n  const code = getFaultCode(err);\n  return code !== undefined && isRetryableFaultCode(code);\n}\n\n/** Run `fn`, retrying retryable failures with backoff. */\nexport async function withRetry<T>(fn: () => Promise<T>, opts: RetryOptions = {}): Promise<T> {\n  const maxAttempts = opts.maxAttempts ?? DEFAULTS.maxAttempts;\n  const baseDelayMs = opts.baseDelayMs ?? DEFAULTS.baseDelayMs;\n  const backoffFactor = opts.backoffFactor ?? DEFAULTS.backoffFactor;\n  const maxDelayMs = opts.maxDelayMs ?? DEFAULTS.maxDelayMs;\n  const jitter = opts.jitter ?? DEFAULTS.jitter;\n  const dutyCycleDelayMs = opts.dutyCycleDelayMs ?? DEFAULTS.dutyCycleDelayMs;\n  const transmissionPendingDelayMs =\n    opts.transmissionPendingDelayMs ?? DEFAULTS.transmissionPendingDelayMs;\n  const getFaultCode = opts.getFaultCode ?? defaultGetFaultCode;\n  const isRetryable =\n    opts.isRetryable ?? ((err: unknown): boolean => defaultIsRetryable(err, getFaultCode));\n  const sleep = opts.sleep ?? defaultSleep;\n  const random = opts.random ?? Math.random;\n\n  // `<= 0` means \"no retries\": invoke exactly once and let it throw.\n  const effectiveMaxAttempts = maxAttempts <= 0 ? 1 : maxAttempts;\n\n  let attempt = 0;\n  for (;;) {\n    attempt += 1;\n    try {\n      return await fn();\n    } catch (err) {\n      const lastAttempt = attempt >= effectiveMaxAttempts;\n      if (lastAttempt || !isRetryable(err)) {\n        throw err;\n      }\n      const delay = computeDelay({\n        attempt,\n        faultCode: getFaultCode(err),\n        baseDelayMs,\n        backoffFactor,\n        maxDelayMs,\n        jitter,\n        dutyCycleDelayMs,\n        transmissionPendingDelayMs,\n        random,\n      });\n      await sleep(delay);\n    }\n  }\n}\n\ninterface DelayParams {\n  readonly attempt: number;\n  readonly faultCode: number | undefined;\n  readonly baseDelayMs: number;\n  readonly backoffFactor: number;\n  readonly maxDelayMs: number;\n  readonly jitter: number;\n  readonly dutyCycleDelayMs: number;\n  readonly transmissionPendingDelayMs: number;\n  readonly random: () => number;\n}\n\nfunction computeDelay(p: DelayParams): number {\n  if (p.faultCode === XmlRpcFaultCode.INSUFFICIENT_DUTYCYCLE) return p.dutyCycleDelayMs;\n  if (p.faultCode === XmlRpcFaultCode.TRANSMISSION_PENDING) return p.transmissionPendingDelayMs;\n\n  const exponential = p.baseDelayMs * Math.pow(p.backoffFactor, p.attempt - 1);\n  const capped = Math.min(exponential, p.maxDelayMs);\n  if (p.jitter <= 0) return capped;\n  // Multiplier in [1 - jitter, 1 + jitter].\n  const multiplier = 1 - p.jitter + 2 * p.jitter * p.random();\n  return capped * multiplier;\n}\n","/**\n * Request coalescer: deduplicates concurrent identical async calls. The first\n * caller for a key registers a pending promise; concurrent callers with the\n * same key share it. The entry is removed once the promise settles (resolve or\n * reject), so a later call re-runs `fn`. There is no TTL.\n */\n\n/** Build a stable coalescing key from a method name and its positional args. */\nexport function makeKey(method: string, args: readonly unknown[]): string {\n  return method + ':' + args.map(stringifyArg).join(':');\n}\n\n/** Stringify a single arg; objects use deterministic, sorted-key JSON. */\nfunction stringifyArg(value: unknown): string {\n  if (value === null || value === undefined) return String(value);\n  switch (typeof value) {\n    case 'string':\n      return value;\n    case 'number':\n    case 'boolean':\n    case 'bigint':\n      return value.toString();\n    default:\n      // object, function, symbol → deterministic JSON.\n      return stableStringify(value);\n  }\n}\n\n/** JSON stringify with object keys sorted recursively for stability. */\nfunction stableStringify(value: unknown): string {\n  if (value === null || typeof value !== 'object') {\n    return JSON.stringify(value);\n  }\n  if (Array.isArray(value)) {\n    return '[' + value.map(stableStringify).join(',') + ']';\n  }\n  const obj = value as Record<string, unknown>;\n  const keys = Object.keys(obj).sort();\n  const members = keys.map((k) => JSON.stringify(k) + ':' + stableStringify(obj[k]));\n  return '{' + members.join(',') + '}';\n}\n\nexport class RequestCoalescer {\n  private readonly pending = new Map<string, Promise<unknown>>();\n\n  /**\n   * Run `fn` under `key`, sharing an in-flight promise with concurrent callers\n   * of the same key. Errors propagate to all awaiters.\n   */\n  public coalesce<T>(key: string, fn: () => Promise<T>): Promise<T> {\n    const existing = this.pending.get(key) as Promise<T> | undefined;\n    if (existing) return existing;\n\n    const promise = fn().finally(() => {\n      this.pending.delete(key);\n    });\n    this.pending.set(key, promise);\n    return promise;\n  }\n\n  /** Number of in-flight coalesced requests (observability/testing). */\n  public get size(): number {\n    return this.pending.size;\n  }\n}\n","/**\n * XML-RPC HTTP client for talking to a CCU interface. Serializes positional\n * method calls (ISO-8859-1), POSTs them with `Content-Type: text/xml`, parses\n * the response, and maps faults / transport failures to typed errors.\n */\nimport { Agent, fetch, type RequestInit } from 'undici';\nimport { ClientError, mapTransportError, mapXmlRpcFault } from '../../support/errors.js';\nimport { serializeMethodCall } from './serialize.js';\nimport { parseXmlRpc } from './parse.js';\nimport type { XmlRpcValue } from './types.js';\n\n/** HTTP Basic auth credentials. */\nexport interface BasicAuth {\n  readonly username: string;\n  readonly password: string;\n}\n\n/** TLS options for HTTPS endpoints (e.g. CCU self-signed certificates). */\nexport interface TlsOptions {\n  /** When false, accept self-signed / untrusted certificates. Defaults to true. */\n  readonly rejectUnauthorized?: boolean;\n}\n\n/** Configuration for {@link XmlRpcClient}. */\nexport interface XmlRpcClientOptions {\n  /** Full endpoint URL, e.g. `http://ccu:2010/`. */\n  readonly url: string;\n  /** Optional HTTP Basic auth. */\n  readonly auth?: BasicAuth;\n  /** Optional TLS settings for HTTPS endpoints. */\n  readonly tls?: TlsOptions;\n  /** Per-request timeout in milliseconds. */\n  readonly timeoutMs: number;\n}\n\nfunction basicAuthHeader(auth: BasicAuth): string {\n  const token = Buffer.from(`${auth.username}:${auth.password}`).toString('base64');\n  return `Basic ${token}`;\n}\n\n/**\n * Thin XML-RPC client. One instance targets a single endpoint URL. Stateless\n * apart from its config and an optional reusable TLS dispatcher.\n */\nexport class XmlRpcClient {\n  private readonly options: XmlRpcClientOptions;\n  private readonly dispatcher: Agent | undefined;\n\n  public constructor(options: XmlRpcClientOptions) {\n    this.options = options;\n    // A custom dispatcher is only needed to relax/control TLS verification.\n    if (options.tls?.rejectUnauthorized === false) {\n      this.dispatcher = new Agent({ connect: { rejectUnauthorized: false } });\n    } else {\n      this.dispatcher = undefined;\n    }\n  }\n\n  /**\n   * Invoke an XML-RPC method with positional params and return the parsed\n   * result. Throws a typed error on fault, empty body, or transport failure.\n   */\n  public async call(method: string, params: readonly XmlRpcValue[]): Promise<XmlRpcValue> {\n    const body = serializeMethodCall(method, params);\n\n    const headers: Record<string, string> = {\n      'Content-Type': 'text/xml; charset=iso-8859-1',\n      Accept: 'text/xml',\n    };\n    if (this.options.auth) {\n      headers['Authorization'] = basicAuthHeader(this.options.auth);\n    }\n\n    const controller = new AbortController();\n    const timer = setTimeout(() => controller.abort(), this.options.timeoutMs);\n\n    let raw: Buffer;\n    try {\n      const init: RequestInit = {\n        method: 'POST',\n        headers,\n        body,\n        signal: controller.signal,\n      };\n      if (this.dispatcher) init.dispatcher = this.dispatcher;\n\n      const response = await fetch(this.options.url, init);\n      const arrayBuffer = await response.arrayBuffer();\n      raw = Buffer.from(arrayBuffer);\n    } catch (err) {\n      // Network/connection/abort failures become NoConnectionError (via mapper).\n      throw mapTransportError(err);\n    } finally {\n      clearTimeout(timer);\n    }\n\n    if (raw.length === 0) {\n      throw new ClientError('XML-RPC response had an empty body');\n    }\n\n    // The empty-body case is already handled by the `raw.length === 0` guard\n    // above, so the parser can no longer throw EmptyBodyError here.\n    const parsed = parseXmlRpc(raw);\n\n    if (parsed.kind === 'fault') {\n      throw mapXmlRpcFault(parsed.fault.faultCode, parsed.fault.faultString);\n    }\n    if (parsed.kind === 'call') {\n      throw new ClientError('expected a methodResponse but received a methodCall');\n    }\n    return parsed.value;\n  }\n\n  /** Release the underlying TLS dispatcher, if any. */\n  public async close(): Promise<void> {\n    if (this.dispatcher) {\n      await this.dispatcher.close();\n    }\n  }\n}\n","/**\n * XML-RPC serializer producing ISO-8859-1 (latin1) encoded payloads, matching\n * the Homematic CCU wire format. The XML declaration advertises `iso-8859-1`\n * and the returned `Buffer` is latin1-encoded so accented characters travel as\n * single bytes.\n */\nimport { ValidationError } from '../../support/errors.js';\nimport type { XmlRpcValue } from './types.js';\n\nconst XML_DECLARATION = '<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>';\n\n/** Escape the five XML-significant characters within text content. */\nfunction escapeXml(text: string): string {\n  return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n}\n\n/** Format a `Date` as the XML-RPC `dateTime.iso8601` basic format (UTC). */\nfunction formatDateTime(date: Date): string {\n  const pad = (n: number): string => String(n).padStart(2, '0');\n  const yyyy = date.getUTCFullYear();\n  const mm = pad(date.getUTCMonth() + 1);\n  const dd = pad(date.getUTCDate());\n  const hh = pad(date.getUTCHours());\n  const mi = pad(date.getUTCMinutes());\n  const ss = pad(date.getUTCSeconds());\n  return `${yyyy}${mm}${dd}T${hh}:${mi}:${ss}`;\n}\n\n/**\n * Serialize a single value into its `<value>...</value>` XML representation.\n * Numbers: integers → `<i4>`, non-integers → `<double>`.\n */\nexport function serializeValue(value: XmlRpcValue): string {\n  if (value === null) return '<value><nil/></value>';\n\n  if (typeof value === 'boolean') {\n    return `<value><boolean>${value ? '1' : '0'}</boolean></value>`;\n  }\n\n  if (typeof value === 'number') {\n    if (!Number.isFinite(value)) {\n      throw new ValidationError(`Cannot serialize non-finite number: ${String(value)}`);\n    }\n    if (Number.isInteger(value)) return `<value><i4>${value}</i4></value>`;\n    return `<value><double>${value}</double></value>`;\n  }\n\n  if (typeof value === 'string') {\n    return `<value><string>${escapeXml(value)}</string></value>`;\n  }\n\n  if (value instanceof Date) {\n    return `<value><dateTime.iso8601>${formatDateTime(value)}</dateTime.iso8601></value>`;\n  }\n\n  if (value instanceof Uint8Array) {\n    return `<value><base64>${Buffer.from(value).toString('base64')}</base64></value>`;\n  }\n\n  if (Array.isArray(value)) {\n    const items = value.map((item) => serializeValue(item)).join('');\n    return `<value><array><data>${items}</data></array></value>`;\n  }\n\n  // Plain object → struct.\n  const members = Object.entries(value)\n    .map(\n      ([name, member]) =>\n        `<member><name>${escapeXml(name)}</name>${serializeValue(member)}</member>`,\n    )\n    .join('');\n  return `<value><struct>${members}</struct></value>`;\n}\n\nfunction paramsBlock(params: readonly XmlRpcValue[]): string {\n  if (params.length === 0) return '<params></params>';\n  const inner = params.map((p) => `<param>${serializeValue(p)}</param>`).join('');\n  return `<params>${inner}</params>`;\n}\n\n/** Encode an XML string to a latin1 (ISO-8859-1) buffer for the wire. */\nfunction toLatin1(xml: string): Buffer {\n  return Buffer.from(xml, 'latin1');\n}\n\n/** Serialize a `<methodCall>` with positional params. Returns a latin1 Buffer. */\nexport function serializeMethodCall(methodName: string, params: readonly XmlRpcValue[]): Buffer {\n  const xml =\n    `${XML_DECLARATION}<methodCall><methodName>${escapeXml(methodName)}</methodName>` +\n    `${paramsBlock(params)}</methodCall>`;\n  return toLatin1(xml);\n}\n\n/** Serialize a successful `<methodResponse>` wrapping a single value. */\nexport function serializeMethodResponse(value: XmlRpcValue): Buffer {\n  const xml =\n    `${XML_DECLARATION}<methodResponse><params><param>${serializeValue(value)}</param></params>` +\n    `</methodResponse>`;\n  return toLatin1(xml);\n}\n\n/** Serialize a `<fault>` response. */\nexport function serializeFault(faultCode: number, faultString: string): Buffer {\n  const fault = serializeValue({ faultCode, faultString });\n  const xml = `${XML_DECLARATION}<methodResponse><fault>${fault}</fault></methodResponse>`;\n  return toLatin1(xml);\n}\n","/**\n * XML-RPC parser. Accepts a string or Buffer (decoded as the document's\n * declared encoding, defaulting to latin1 for raw Buffers without an explicit\n * decode) and returns a discriminated {@link XmlRpcParsed}: a method response\n * value, a fault, or a method call.\n *\n * Homematic quirks handled:\n * - `<i4>`, `<i8>`, `<int>` → number; `<double>` → number.\n * - A `<value>` with no inner type tag defaults to a string.\n * - `<dateTime.iso8601>` → string (kept raw; the model layer decides).\n * - `<base64>` → Uint8Array.\n * - Empty HTTP body → {@link EmptyBodyError} (not a parse crash).\n */\nimport { XMLParser } from 'fast-xml-parser';\nimport { BaseHomematicError } from '../../support/errors.js';\nimport type { XmlRpcFault, XmlRpcMethodCall, XmlRpcParsed, XmlRpcValue } from './types.js';\n\n/** Thrown when an HTTP 200 carried no XML body to parse. */\nexport class EmptyBodyError extends BaseHomematicError {}\n\n/** Thrown when the document is well-formed XML but not a recognizable XML-RPC document. */\nexport class MalformedXmlRpcError extends BaseHomematicError {}\n\n// preserveOrder yields a predictable array-of-nodes structure, so we never rely\n// on fast-xml-parser's value coercion. Each node is `{ tagName: [...children], ':@'?: attrs }`\n// and text nodes are `{ '#text': string }`.\nconst parser = new XMLParser({\n  preserveOrder: true,\n  ignoreAttributes: true,\n  trimValues: false,\n  parseTagValue: false,\n  processEntities: true,\n  htmlEntities: false,\n});\n\ntype OrderedNode = Record<string, unknown>;\n\nfunction decodeInput(input: string | Buffer | Uint8Array): string {\n  if (typeof input === 'string') return input;\n  const buf = Buffer.isBuffer(input) ? input : Buffer.from(input);\n  // Detect declared encoding from the XML declaration prologue (first bytes are ASCII-safe).\n  const head = buf.subarray(0, 120).toString('latin1').toLowerCase();\n  const match = /encoding\\s*=\\s*[\"']([^\"']+)[\"']/.exec(head);\n  const enc = match?.[1] ?? 'iso-8859-1';\n  if (enc === 'utf-8' || enc === 'utf8') return buf.toString('utf-8');\n  // latin1 / iso-8859-1 (and any single-byte default).\n  return buf.toString('latin1');\n}\n\n/** Find the children array for a given tag inside an ordered-node list. */\nfunction childrenOf(nodes: OrderedNode[], tag: string): OrderedNode[] | undefined {\n  for (const node of nodes) {\n    if (Object.prototype.hasOwnProperty.call(node, tag)) {\n      return node[tag] as OrderedNode[];\n    }\n  }\n  return undefined;\n}\n\n/** Collect the concatenated text directly under a node list. */\nfunction textOf(nodes: OrderedNode[]): string {\n  let text = '';\n  for (const node of nodes) {\n    if (Object.prototype.hasOwnProperty.call(node, '#text')) {\n      text += String(node['#text']);\n    }\n  }\n  return text;\n}\n\n/** Return the first non-text element tag name present in the node list, if any. */\nfunction firstElementTag(nodes: OrderedNode[]): string | undefined {\n  for (const node of nodes) {\n    for (const key of Object.keys(node)) {\n      if (key !== '#text' && key !== ':@') return key;\n    }\n  }\n  return undefined;\n}\n\n/** Parse the children of a `<value>` element into a JS value. */\nfunction parseValue(valueChildren: OrderedNode[]): XmlRpcValue {\n  const tag = firstElementTag(valueChildren);\n  if (tag === undefined) {\n    // No type element → string content (Homematic default).\n    return textOf(valueChildren);\n  }\n\n  const inner = childrenOf(valueChildren, tag) ?? [];\n  switch (tag) {\n    case 'i4':\n    case 'i8':\n    case 'int':\n      return Number(textOf(inner).trim());\n    case 'double':\n      return Number(textOf(inner).trim());\n    case 'boolean':\n      return textOf(inner).trim() === '1';\n    case 'string':\n      return textOf(inner);\n    case 'dateTime.iso8601':\n      return textOf(inner).trim();\n    case 'base64':\n      return new Uint8Array(Buffer.from(textOf(inner).trim(), 'base64'));\n    case 'nil':\n      return null;\n    case 'array':\n      return parseArray(inner);\n    case 'struct':\n      return parseStruct(inner);\n    default:\n      // Unknown type tag → treat its text as a string.\n      return textOf(inner);\n  }\n}\n\nfunction parseArray(arrayChildren: OrderedNode[]): XmlRpcValue[] {\n  const data = childrenOf(arrayChildren, 'data') ?? [];\n  const result: XmlRpcValue[] = [];\n  for (const node of data) {\n    if (Object.prototype.hasOwnProperty.call(node, 'value')) {\n      result.push(parseValue(node['value'] as OrderedNode[]));\n    }\n  }\n  return result;\n}\n\nfunction parseStruct(structChildren: OrderedNode[]): { [key: string]: XmlRpcValue } {\n  const result: { [key: string]: XmlRpcValue } = {};\n  for (const node of structChildren) {\n    if (!Object.prototype.hasOwnProperty.call(node, 'member')) continue;\n    const member = node['member'] as OrderedNode[];\n    const nameNodes = childrenOf(member, 'name');\n    const valueNodes = childrenOf(member, 'value');\n    if (nameNodes === undefined || valueNodes === undefined) continue;\n    const name = textOf(nameNodes);\n    result[name] = parseValue(valueNodes);\n  }\n  return result;\n}\n\n/** Parse the `<params>` block into positional values. */\nfunction parseParams(paramsChildren: OrderedNode[]): XmlRpcValue[] {\n  const params: XmlRpcValue[] = [];\n  for (const node of paramsChildren) {\n    if (!Object.prototype.hasOwnProperty.call(node, 'param')) continue;\n    const param = node['param'] as OrderedNode[];\n    const valueNodes = childrenOf(param, 'value');\n    params.push(valueNodes === undefined ? '' : parseValue(valueNodes));\n  }\n  return params;\n}\n\nfunction parseFault(faultChildren: OrderedNode[]): XmlRpcFault {\n  const valueNodes = childrenOf(faultChildren, 'value');\n  const struct = valueNodes === undefined ? {} : parseValue(valueNodes);\n  const record =\n    typeof struct === 'object' && struct !== null && !Array.isArray(struct)\n      ? (struct as Record<string, XmlRpcValue>)\n      : {};\n  const rawCode = record['faultCode'];\n  const rawString = record['faultString'];\n  const faultCode = typeof rawCode === 'number' ? rawCode : Number(rawCode);\n  const faultString = typeof rawString === 'string' ? rawString : '';\n  return { faultCode, faultString };\n}\n\n/** Parse a complete XML-RPC document. */\nexport function parseXmlRpc(input: string | Buffer | Uint8Array): XmlRpcParsed {\n  const xml = decodeInput(input);\n  if (xml.trim().length === 0) {\n    throw new EmptyBodyError('XML-RPC response had an empty body');\n  }\n\n  let root: OrderedNode[];\n  try {\n    root = parser.parse(xml) as OrderedNode[];\n  } catch (err) {\n    throw new MalformedXmlRpcError(\n      `failed to parse XML-RPC document: ${err instanceof Error ? err.message : String(err)}`,\n    );\n  }\n\n  const responseChildren = childrenOf(root, 'methodResponse');\n  if (responseChildren !== undefined) {\n    const faultChildren = childrenOf(responseChildren, 'fault');\n    if (faultChildren !== undefined) {\n      return { kind: 'fault', fault: parseFault(faultChildren) };\n    }\n    const paramsChildren = childrenOf(responseChildren, 'params');\n    const params = paramsChildren === undefined ? [] : parseParams(paramsChildren);\n    return { kind: 'response', value: params[0] ?? null };\n  }\n\n  const callChildren = childrenOf(root, 'methodCall');\n  if (callChildren !== undefined) {\n    const nameNodes = childrenOf(callChildren, 'methodName');\n    const methodName = nameNodes === undefined ? '' : textOf(nameNodes).trim();\n    const paramsChildren = childrenOf(callChildren, 'params');\n    const params = paramsChildren === undefined ? [] : parseParams(paramsChildren);\n    const call: XmlRpcMethodCall = { methodName, params };\n    return { kind: 'call', call };\n  }\n\n  throw new MalformedXmlRpcError('document is neither a methodResponse nor a methodCall');\n}\n","/**\n * Composes the transport primitives for a SINGLE CCU interface (e.g. HmIP-RF):\n * an XML-RPC client, a circuit breaker, retry, request coalescing and the\n * connection state machine. It exposes the raw CCU methods with typed\n * signatures (positional argument order matters and mirrors the protocol).\n *\n * The transport layer carries NO domain logic — it speaks raw CCU methods and\n * returns the parsed values, casting them to the declared transport shapes at\n * the documented trust boundary.\n */\n\nimport {\n  BaseHomematicError,\n  CcuManagementError,\n  CircuitBreakerOpenError,\n  NoConnectionError,\n  TimeoutError,\n} from '../support/errors.js';\nimport {\n  Interface,\n  INTERFACE_PORTS,\n  interfaceId as buildInterfaceId,\n  TIMEOUTS,\n} from '../support/constants.js';\nimport { CircuitBreaker } from './resilience/circuit-breaker.js';\nimport { withRetry, defaultGetFaultCode, type RetryOptions } from './resilience/retry.js';\nimport { RequestCoalescer, makeKey } from './resilience/coalescer.js';\nimport {\n  ConnectionStateMachine,\n  ClientState,\n  type StateChangeEvent,\n} from './resilience/state-machine.js';\nimport { XmlRpcClient, type BasicAuth } from './xmlrpc/client.js';\nimport type { DeviceDescription, ParameterData, ParamsetKey, XmlRpcValue } from './xmlrpc/types.js';\n\n/**\n * A paramset key (`MASTER`, `VALUES`, …) or, for a link paramset, the peer\n * channel address (`getParamset(receiver, sender)`).\n */\ntype ParamsetTarget = ParamsetKey | (string & {});\n\n/**\n * Minimal contract the {@link InterfaceClient} needs from an XML-RPC client.\n * {@link XmlRpcClient} implements it; tests can inject a fake.\n */\nexport interface XmlRpcClientLike {\n  call(method: string, params: readonly XmlRpcValue[]): Promise<XmlRpcValue>;\n}\n\n/** Factory used to build the underlying XML-RPC client (overridable in tests). */\nexport type XmlRpcClientFactory = (\n  url: string,\n  auth: BasicAuth | undefined,\n  tls: boolean,\n) => XmlRpcClientLike;\n\n/** One radio gateway as `listBidcosInterfaces` reports it; unknowns are `null`. */\nexport interface RadioGatewayInfo {\n  readonly address: string;\n  readonly description: string | null;\n  /** Duty cycle in percent, or `null` when the CCU did not report one. */\n  readonly dutyCycle: number | null;\n  readonly connected: boolean | null;\n  readonly isDefault: boolean;\n  readonly firmware: string | null;\n  readonly type: string | null;\n}\n\n/** Arguments of {@link InterfaceClient.setInstallMode}. */\nexport interface InstallModeCall {\n  readonly on: boolean;\n  /** Length of the pairing window; omitted when switching off. */\n  readonly seconds?: number;\n  /** BidCos only: 1 normal, 2 with the HomeMatic Secure key. */\n  readonly mode?: 1 | 2;\n}\n\n/** Construction options for {@link InterfaceClient}. */\nexport interface InterfaceClientOptions {\n  /** Logical name of the central (used to build the interface id). */\n  readonly centralName: string;\n  /** Which CCU interface this client talks to. */\n  readonly interface: Interface;\n  /** CCU host name or IP. */\n  readonly host: string;\n  /** Override the port; defaults to the interface's plain/TLS port. */\n  readonly port?: number;\n  /**\n   * Optional XML-RPC remote URL path (e.g. `'/groups'` for VirtualDevices).\n   * Appended to `{scheme}://{host}:{port}`. Defaults to the server root (`/`)\n   * when omitted. The callback URL is unaffected by this.\n   */\n  readonly path?: string;\n  /** Use HTTPS for the XML-RPC endpoint. */\n  readonly tls?: boolean;\n  /** Optional HTTP Basic auth credentials. */\n  readonly auth?: BasicAuth;\n  /** Returns the `http://host:port` callback URL to (de)register. */\n  readonly callbackUrlProvider: () => string;\n  /** Shared/injected breaker; defaults to a fresh {@link CircuitBreaker}. */\n  readonly circuitBreaker?: CircuitBreaker;\n  /** Overrides for the write-command retry policy. */\n  readonly retryOptions?: Partial<RetryOptions>;\n  /** Per-request timeout in ms; defaults to {@link TIMEOUTS.rpc}. */\n  readonly timeoutMs?: number;\n  /** Injectable XML-RPC client factory (for tests). */\n  readonly makeClient?: XmlRpcClientFactory;\n}\n\n/**\n * Methods that bypass the circuit breaker entirely (mirrors aiohomematic): they\n * are lifecycle/probe calls and must work even when the breaker is OPEN. No\n * success/failure is recorded for them.\n */\nconst BYPASS_METHODS = new Set<string>([\n  'init',\n  'ping',\n  'system.listMethods',\n  'getVersion',\n  'clientServerInitialized',\n]);\n\ninterface CallGuardOptions {\n  readonly bypassBreaker?: boolean;\n}\n\n// `tls` is encoded in the URL scheme already, so the default factory ignores it.\nconst defaultMakeClient: XmlRpcClientFactory = (\n  url: string,\n  auth: BasicAuth | undefined,\n): XmlRpcClientLike => {\n  const options =\n    auth === undefined ? { url, timeoutMs: TIMEOUTS.rpc } : { url, auth, timeoutMs: TIMEOUTS.rpc };\n  return new XmlRpcClient(options);\n};\n\nexport class InterfaceClient {\n  private readonly centralName: string;\n  private readonly iface: Interface;\n  private readonly callbackUrlProvider: () => string;\n  private readonly breaker: CircuitBreaker;\n  private readonly retryOptions: Partial<RetryOptions>;\n  private readonly coalescer = new RequestCoalescer();\n  private readonly machine = new ConnectionStateMachine(ClientState.CREATED);\n  // Phase 1 simplification: aiohomematic uses two proxies (one for reads, one\n  // for writes) to avoid head-of-line blocking. A single client instance is\n  // acceptable here; the split can be introduced later behind this same API.\n  private readonly client: XmlRpcClientLike;\n\n  public constructor(options: InterfaceClientOptions) {\n    this.centralName = options.centralName;\n    this.iface = options.interface;\n    this.callbackUrlProvider = options.callbackUrlProvider;\n    this.breaker = options.circuitBreaker ?? new CircuitBreaker();\n    this.retryOptions = options.retryOptions ?? {};\n\n    const tls = options.tls ?? false;\n    const ports = INTERFACE_PORTS[options.interface];\n    const port = options.port ?? (tls ? ports.tls : ports.nonTls);\n    const scheme = tls ? 'https' : 'http';\n    // Most interfaces serve XML-RPC at the root; VirtualDevices uses `/groups`.\n    const path = options.path ?? '/';\n    const url = `${scheme}://${options.host}:${port}${path}`;\n    const makeClient = options.makeClient ?? defaultMakeClient;\n    this.client = makeClient(url, options.auth, tls);\n  }\n\n  /** Interface id used to register the callback proxy: `{centralName}-{interface}`. */\n  public get interfaceId(): string {\n    return buildInterfaceId(this.centralName, this.iface);\n  }\n\n  /** Current connection lifecycle state. */\n  public get state(): ClientState {\n    return this.machine.state;\n  }\n\n  /** Subscribe to state changes; returns an unsubscribe function. */\n  public onStateChange(cb: (event: StateChangeEvent) => void): () => void {\n    return this.machine.onChange(cb);\n  }\n\n  /**\n   * Register the callback proxy with the CCU: `init(callbackUrl, interfaceId)`.\n   * Drives the state machine through the valid path to CONNECTED, or to FAILED\n   * on error.\n   */\n  public async initProxy(): Promise<void> {\n    this.markInitializing();\n    this.machine.transitionTo(ClientState.CONNECTING, 'initProxy');\n    try {\n      await this.callGuarded('init', [this.callbackUrlProvider(), this.interfaceId], {\n        bypassBreaker: true,\n      });\n      this.machine.transitionTo(ClientState.CONNECTED, 'initProxy ok');\n    } catch (err) {\n      this.machine.transitionTo(ClientState.FAILED, 'initProxy failed');\n      throw err;\n    }\n  }\n\n  /**\n   * De-register the callback proxy: `init(callbackUrl)` (SINGLE argument).\n   * Drives the state machine toward DISCONNECTED.\n   */\n  public async deinitProxy(): Promise<void> {\n    try {\n      await this.callGuarded('init', [this.callbackUrlProvider()], { bypassBreaker: true });\n    } finally {\n      this.markDisconnected('deinitProxy');\n    }\n  }\n\n  /** Liveness probe: `ping(callerId)` → bool. */\n  public async ping(callerId?: string): Promise<boolean> {\n    const result = await this.callGuarded('ping', [callerId ?? this.interfaceId], {\n      bypassBreaker: true,\n    });\n    return result === true;\n  }\n\n  /** `listDevices()` → device descriptions. */\n  public async listDevices(): Promise<DeviceDescription[]> {\n    const result = await this.callGuarded('listDevices', []);\n    return asDeviceDescriptionArray(result);\n  }\n\n  /** `getDeviceDescription(address)` (coalesced). */\n  public async getDeviceDescription(address: string): Promise<DeviceDescription> {\n    const key = makeKey('getDeviceDescription', [address]);\n    return this.coalescer.coalesce(key, async () => {\n      const result = await this.callGuarded('getDeviceDescription', [address]);\n      return asDeviceDescription(result);\n    });\n  }\n\n  /** `getParamsetDescription(channelAddress, paramsetKey)` (coalesced). */\n  public async getParamsetDescription(\n    channelAddress: string,\n    paramsetKey: ParamsetKey,\n  ): Promise<Record<string, ParameterData>> {\n    const key = makeKey('getParamsetDescription', [channelAddress, paramsetKey]);\n    return this.coalescer.coalesce(key, async () => {\n      const result = await this.callGuarded('getParamsetDescription', [\n        channelAddress,\n        paramsetKey,\n      ]);\n      return asParamsetDescription(result);\n    });\n  }\n\n  /**\n   * `getParamset(channelAddress, paramsetKey)` → struct. For a link paramset\n   * the key is the peer address: `getParamset(receiver, sender)`.\n   */\n  public async getParamset(\n    channelAddress: string,\n    paramsetKey: ParamsetTarget,\n  ): Promise<Record<string, unknown>> {\n    const result = await this.callGuarded('getParamset', [channelAddress, paramsetKey]);\n    return asStruct(result);\n  }\n\n  /** `getValue(channelAddress, parameter)` → any. */\n  public async getValue(channelAddress: string, parameter: string): Promise<unknown> {\n    return this.callGuarded('getValue', [channelAddress, parameter]);\n  }\n\n  /**\n   * `getLinks(channelAddress, flags)` → array of `{SENDER, RECEIVER, NAME, ...}`.\n   *\n   * aiohomematic `CcuBackend.get_links` (`client/backends/ccu.py`) →\n   * `LinkCoordinator.get_device_links` passes `flags = 0`.\n   */\n  public async getLinks(channelAddress: string, flags: number): Promise<XmlRpcValue> {\n    return this.callGuarded('getLinks', [channelAddress, flags]);\n  }\n\n  /**\n   * `getMetadata(address, dataId)` → struct.\n   *\n   * aiohomematic `CcuBackend.get_metadata`. Central-link state uses\n   * `dataId = \"reportValueUsageData\"`.\n   */\n  public async getMetadata(address: string, dataId: string): Promise<XmlRpcValue> {\n    return this.callGuarded('getMetadata', [address, dataId]);\n  }\n\n  /**\n   * `reportValueUsage(channelAddress, valueId, refCounter)` → bool.\n   *\n   * aiohomematic `CcuBackend.report_value_usage`:\n   * `bool(proxy.reportValueUsage(channel_address, value_id, ref_counter))`.\n   * Central links pass `valueId = \"PRESS_SHORT\"`, `refCounter` `1` (create) or\n   * `0` (remove). A non-boolean truthy integer `1` is accepted the same way\n   * Python `bool(1)` would.\n   */\n  public async reportValueUsage(\n    channelAddress: string,\n    valueId: string,\n    refCounter: number,\n  ): Promise<boolean> {\n    const result = await this.callGuarded('reportValueUsage', [\n      channelAddress,\n      valueId,\n      refCounter,\n    ]);\n    return result === true || result === 1;\n  }\n\n  /**\n   * `addLink(sender, receiver, name, description)` — create a direct link.\n   * eq-3/occu `WebUI/www/api/methods/interface/addlink.tcl` forwards exactly\n   * these four strings. Not retried: a second attempt after a lost answer\n   * could race the first.\n   */\n  public async addLink(\n    sender: string,\n    receiver: string,\n    name: string,\n    description: string,\n  ): Promise<void> {\n    await this.callGuarded('addLink', [sender, receiver, name, description]);\n  }\n\n  /**\n   * `removeLink(sender, receiver)` — delete a direct link\n   * (eq-3/occu `WebUI/www/api/methods/interface/removelink.tcl`).\n   */\n  public async removeLink(sender: string, receiver: string): Promise<void> {\n    await this.callGuarded('removeLink', [sender, receiver]);\n  }\n\n  /** `setValue(channelAddress, parameter, value[, rxMode])` — wrapped in retry. */\n  public async setValue(\n    channelAddress: string,\n    parameter: string,\n    value: XmlRpcValue,\n    rxMode?: string,\n  ): Promise<void> {\n    const params: XmlRpcValue[] =\n      rxMode === undefined\n        ? [channelAddress, parameter, value]\n        : [channelAddress, parameter, value, rxMode];\n    await withRetry(() => this.callGuarded('setValue', params), {\n      getFaultCode: defaultGetFaultCode,\n      ...this.retryOptions,\n    });\n  }\n\n  /**\n   * `putParamset(channelAddress, paramsetKey, values[, rxMode])` — wrapped in\n   * retry. For a link paramset the key is the peer address.\n   */\n  public async putParamset(\n    channelAddress: string,\n    paramsetKey: ParamsetTarget,\n    values: Record<string, XmlRpcValue>,\n    rxMode?: string,\n  ): Promise<void> {\n    const params: XmlRpcValue[] =\n      rxMode === undefined\n        ? [channelAddress, paramsetKey, values]\n        : [channelAddress, paramsetKey, values, rxMode];\n    await withRetry(() => this.callGuarded('putParamset', params), {\n      getFaultCode: defaultGetFaultCode,\n      ...this.retryOptions,\n    });\n  }\n\n  /**\n   * `installFirmware(address)` — trigger a firmware update for a device.\n   *\n   * TRANSPORT CHOICE: this is dispatched as a standard XML-RPC interface method\n   * on the interface that owns the device (the same channel used by\n   * `listDevices`/`setValue`). The CCU's BidCos-RF and HmIP-RF XML-RPC servers\n   * expose `installFirmware` directly; aiohomematic drives device firmware\n   * updates through the very same per-interface XML-RPC proxy. We wrap it in the\n   * write-retry policy (it is an idempotent \"begin update\" command). If a given\n   * interface does not implement it, the CCU answers with a `<fault>` which the\n   * client surfaces as a typed {@link ClientError} so callers can present a\n   * \"not supported\" message.\n   */\n  public async installFirmware(address: string): Promise<void> {\n    await withRetry(() => this.callGuarded('installFirmware', [address]), {\n      getFaultCode: defaultGetFaultCode,\n      ...this.retryOptions,\n    });\n  }\n\n  /** `getInstallMode()` → seconds remaining. */\n  public async getInstallMode(): Promise<number> {\n    const result = await this.callGuarded('getInstallMode', []);\n    return typeof result === 'number' ? result : 0;\n  }\n\n  /**\n   * `listBidcosInterfaces()` → the radio gateways of a BidCos interface.\n   *\n   * Source: HomeMatic XML-RPC interface spec (rfd), as consumed by the WebUI in\n   * eq-3/occu `WebUI/www/api/methods/interface/listbidcosinterfaces.tcl`\n   * (fields ADDRESS, DESCRIPTION, DUTY_CYCLE, CONNECTED, DEFAULT,\n   * FIRMWARE_VERSION, TYPE). A field the CCU did not send is `null`, never 0.\n   */\n  public async listBidcosInterfaces(): Promise<RadioGatewayInfo[]> {\n    const result = await this.managementCall('listBidcosInterfaces', []);\n    if (!Array.isArray(result)) return [];\n    const gateways: RadioGatewayInfo[] = [];\n    for (const entry of result) {\n      if (isStruct(entry)) gateways.push(toRadioGateway(entry));\n    }\n    return gateways;\n  }\n\n  /**\n   * `setInstallMode(on[, seconds[, mode]])` — open or close the pairing window.\n   *\n   * Source: HomeMatic XML-RPC interface spec; the WebUI forwards the same call\n   * in eq-3/occu `WebUI/www/api/methods/interface/setinstallmode.tcl` and\n   * `setinstallmodehmip.tcl` (`setInstallMode(bool on, int time)`). `mode`\n   * (1 normal, 2 with the HomeMatic Secure key) is BidCos-only and is sent only\n   * when given.\n   */\n  public async setInstallMode(request: InstallModeCall): Promise<void> {\n    const params: XmlRpcValue[] = [request.on];\n    if (request.seconds !== undefined) params.push(request.seconds);\n    if (request.mode !== undefined) params.push(request.mode);\n    await this.managementCall('setInstallMode', params);\n  }\n\n  /**\n   * `getInstallMode()` → seconds left of the pairing window, or `null` when the\n   * CCU answered something that is not an integer (never a fake 0).\n   */\n  public async getInstallModeRemaining(): Promise<number | null> {\n    const result = await this.managementCall('getInstallMode', []);\n    return typeof result === 'number' && Number.isInteger(result) ? result : null;\n  }\n\n  /**\n   * `deleteDevice(address, flags)` — remove a device from the interface.\n   *\n   * Source: eq-3/occu `WebUI/www/api/methods/interface/deletedevice.tcl`:\n   * flags 0x01 reset to factory, 0x02 force (also when unreachable), 0x04 defer\n   * until the device is next reachable.\n   */\n  public async deleteDevice(address: string, flags: number): Promise<void> {\n    await this.managementCall('deleteDevice', [address, flags]);\n  }\n\n  /** `getVersion()` (bypass) → backend version string. */\n  public async getVersion(): Promise<string> {\n    const result = await this.callGuarded('getVersion', [], { bypassBreaker: true });\n    return scalarToString(result);\n  }\n\n  /** `system.listMethods()` (bypass) → supported method names. */\n  public async listMethods(): Promise<string[]> {\n    const result = await this.callGuarded('system.listMethods', [], { bypassBreaker: true });\n    return Array.isArray(result) ? result.map(scalarToString) : [];\n  }\n\n  /**\n   * A management call: guarded like any other, but a failure is rethrown as a\n   * {@link CcuManagementError} naming the method and keeping the CCU fault text.\n   */\n  private async managementCall(\n    method: string,\n    params: readonly XmlRpcValue[],\n  ): Promise<XmlRpcValue> {\n    try {\n      return await this.callGuarded(method, params);\n    } catch (err) {\n      if (err instanceof BaseHomematicError) throw new CcuManagementError(method, err);\n      throw err;\n    }\n  }\n\n  /**\n   * Invoke `method`, gating non-bypass calls behind the circuit breaker.\n   * Bypass methods skip the breaker entirely (no success/failure recorded).\n   */\n  private async callGuarded(\n    method: string,\n    params: readonly XmlRpcValue[],\n    options: CallGuardOptions = {},\n  ): Promise<XmlRpcValue> {\n    const bypass = options.bypassBreaker || BYPASS_METHODS.has(method);\n    if (bypass) {\n      return this.client.call(method, params);\n    }\n\n    if (!this.breaker.isAvailable()) {\n      this.breaker.recordRejection();\n      throw new CircuitBreakerOpenError(`circuit breaker open for ${this.interfaceId}`);\n    }\n\n    try {\n      const result = await this.client.call(method, params);\n      this.breaker.recordSuccess();\n      return result;\n    } catch (err) {\n      // Only connection-type failures count against the breaker; logical faults\n      // (unknown device/parameter, etc.) should not trip it open.\n      if (err instanceof NoConnectionError || err instanceof TimeoutError) {\n        this.breaker.recordFailure();\n      }\n      throw err;\n    }\n  }\n\n  /** Drive the machine to INITIALIZING from any valid predecessor. */\n  private markInitializing(): void {\n    const state = this.machine.state;\n    if (state === ClientState.CREATED || state === ClientState.FAILED) {\n      this.machine.transitionTo(ClientState.INITIALIZING, 'initProxy');\n      this.machine.transitionTo(ClientState.INITIALIZED, 'initProxy');\n    } else if (state === ClientState.INITIALIZING) {\n      this.machine.transitionTo(ClientState.INITIALIZED, 'initProxy');\n    }\n    // DISCONNECTED / INITIALIZED can go straight to CONNECTING.\n  }\n\n  /** Drive the machine toward DISCONNECTED from any valid predecessor. */\n  private markDisconnected(reason: string): void {\n    const state = this.machine.state;\n    const canDisconnect =\n      state === ClientState.CONNECTED ||\n      state === ClientState.INITIALIZED ||\n      state === ClientState.DISCONNECTED ||\n      state === ClientState.RECONNECTING;\n    if (canDisconnect) {\n      this.machine.transitionTo(ClientState.DISCONNECTED, reason);\n    }\n  }\n}\n\n/**\n * The functions below cross the transport trust boundary: the XML-RPC parser\n * returns structurally-typed `XmlRpcValue`s, which we narrow to the declared\n * Homematic shapes. We do a minimal runtime shape check and then trust the CCU\n * for the remaining permissive fields (the model layer refines them later).\n */\n\n/** Coerce a scalar XML-RPC value to a string, rejecting struct/array shapes. */\nfunction scalarToString(value: XmlRpcValue): string {\n  if (typeof value === 'string') return value;\n  if (typeof value === 'number' || typeof value === 'boolean') return value.toString();\n  throw new NoConnectionError('expected a scalar XML-RPC string value');\n}\n\nfunction isStruct(value: XmlRpcValue): value is { [key: string]: XmlRpcValue } {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    !Array.isArray(value) &&\n    !(value instanceof Date) &&\n    !(value instanceof Uint8Array)\n  );\n}\n\nfunction asStruct(value: XmlRpcValue): Record<string, XmlRpcValue> {\n  if (!isStruct(value)) {\n    throw new NoConnectionError('expected an XML-RPC struct response');\n  }\n  return value;\n}\n\nfunction asDeviceDescription(value: XmlRpcValue): DeviceDescription {\n  const struct = asStruct(value);\n  return struct as DeviceDescription;\n}\n\nfunction asDeviceDescriptionArray(value: XmlRpcValue): DeviceDescription[] {\n  if (!Array.isArray(value)) {\n    throw new NoConnectionError('expected an XML-RPC array of device descriptions');\n  }\n  return value.map(asDeviceDescription);\n}\n\nfunction asParamsetDescription(value: XmlRpcValue): Record<string, ParameterData> {\n  const struct = asStruct(value);\n  return struct as Record<string, ParameterData>;\n}\n\nfunction stringOrNull(value: XmlRpcValue | undefined): string | null {\n  return typeof value === 'string' && value !== '' ? value : null;\n}\n\nfunction numberOrNull(value: XmlRpcValue | undefined): number | null {\n  return typeof value === 'number' && Number.isFinite(value) ? value : null;\n}\n\n/** The CCU sends flags as booleans or as 0/1 integers. */\nfunction flagOrNull(value: XmlRpcValue | undefined): boolean | null {\n  if (typeof value === 'boolean') return value;\n  if (value === 1) return true;\n  if (value === 0) return false;\n  return null;\n}\n\nfunction toRadioGateway(entry: Record<string, XmlRpcValue>): RadioGatewayInfo {\n  const connected = flagOrNull(entry['CONNECTED']);\n  return {\n    address: stringOrNull(entry['ADDRESS']) ?? '',\n    description: stringOrNull(entry['DESCRIPTION']),\n    dutyCycle: numberOrNull(entry['DUTY_CYCLE']),\n    connected,\n    isDefault: flagOrNull(entry['DEFAULT']) === true,\n    firmware: stringOrNull(entry['FIRMWARE_VERSION']),\n    type: stringOrNull(entry['TYPE']),\n  };\n}\n","/**\n * JSON-RPC HTTP client for the CCU WebUI (`/api/homematic.cgi`). Builds the\n * Homematic JSON-RPC 1.1 envelope, coerces every param to a string (the CCU\n * expects all-string params), POSTs it, parses the `{result, error, id}`\n * response, and maps errors / transport failures to typed errors.\n *\n * A small semaphore caps the number of concurrent in-flight POSTs, mirroring\n * aiohomematic's `MAX_CONCURRENT_HTTP_SESSIONS`. An HTTP 5xx (a CCU still\n * booting answers 503) is a {@link BackendUnavailableError} and is retried\n * after each of `retryDelaysMs`, outside the semaphore so a waiting retry\n * holds no slot. `Session.*` calls are never retried here: the session\n * manager owns the login backoff.\n */\nimport { Agent, fetch, type RequestInit } from 'undici';\nimport {\n  BackendUnavailableError,\n  ClientError,\n  mapJsonRpcError,\n  mapTransportError,\n  type JsonRpcErrorLike,\n} from '../../support/errors.js';\nimport { JSON_RPC_PATH, TIMEOUTS } from '../../support/constants.js';\nimport { SESSION_BYPASS_METHODS, SESSION_ID_PARAM } from './methods.js';\n\n/** TLS options for HTTPS endpoints (e.g. CCU self-signed certificates). */\nexport interface JsonRpcTlsOptions {\n  /** When false, accept self-signed / untrusted certificates. Defaults to true. */\n  readonly rejectUnauthorized?: boolean;\n}\n\n/** Configuration for {@link JsonRpcClient}. */\nexport interface JsonRpcClientOptions {\n  /** Base device URL, e.g. `http://ccu` (the client appends {@link JSON_RPC_PATH}). */\n  readonly url: string;\n  /** Optional TLS settings for HTTPS endpoints. */\n  readonly tls?: JsonRpcTlsOptions;\n  /** Max concurrent in-flight POSTs. Defaults to 3. */\n  readonly maxConcurrent?: number;\n  /** Per-request timeout in milliseconds. Defaults to {@link TIMEOUTS.rpc}. */\n  readonly timeoutMs?: number;\n  /** Waits before each retry of an HTTP 5xx answer. Defaults to 0.5 s, 1 s, 2 s. */\n  readonly retryDelaysMs?: readonly number[];\n}\n\n/** Per-call options. */\nexport interface JsonRpcPostOptions {\n  /** When provided, injected into the params as `_session_id_`. */\n  readonly sessionId?: string;\n}\n\n/** Shape of a CCU JSON-RPC response envelope. */\ninterface JsonRpcResponse {\n  readonly result?: unknown;\n  readonly error?: JsonRpcErrorLike | null;\n  readonly id?: number;\n}\n\nconst DEFAULT_MAX_CONCURRENT = 3;\nconst DEFAULT_RETRY_DELAYS_MS: readonly number[] = [500, 1_000, 2_000];\n\n/** Resolve after `ms` on the global timer (patchable by fake timers). */\nfunction delay(ms: number): Promise<void> {\n  return new Promise<void>((resolve) => {\n    setTimeout(resolve, ms);\n  });\n}\n\n/**\n * Coerce every param value to a string. Booleans become \"true\"/\"false\",\n * numbers become their decimal string form. Non-null objects/arrays are\n * JSON.stringify-ed (so they do not collapse to \"[object Object]\"); for the\n * common case all values are primitives.\n */\nfunction stringifyParams(params: Record<string, unknown>): Record<string, string> {\n  const out: Record<string, string> = {};\n  for (const [key, value] of Object.entries(params)) {\n    if (value !== null && typeof value === 'object') {\n      out[key] = JSON.stringify(value);\n    } else {\n      out[key] = String(value);\n    }\n  }\n  return out;\n}\n\n/** A minimal FIFO semaphore limiting concurrent async sections. */\nclass Semaphore {\n  private available: number;\n  private readonly waiters: Array<() => void> = [];\n\n  public constructor(permits: number) {\n    this.available = Math.max(1, permits);\n  }\n\n  public async acquire(): Promise<void> {\n    if (this.available > 0) {\n      this.available -= 1;\n      return;\n    }\n    await new Promise<void>((resolve) => this.waiters.push(resolve));\n  }\n\n  public release(): void {\n    const next = this.waiters.shift();\n    if (next) {\n      // Permit is handed directly to the next waiter (count stays consumed).\n      next();\n    } else {\n      this.available += 1;\n    }\n  }\n}\n\n/**\n * JSON-RPC client. One instance targets a single base URL. Stateless apart from\n * its config, an optional reusable TLS dispatcher, and the concurrency\n * semaphore.\n */\nexport class JsonRpcClient {\n  private readonly endpoint: string;\n  private readonly timeoutMs: number;\n  private readonly dispatcher: Agent | undefined;\n  private readonly semaphore: Semaphore;\n  private readonly retryDelaysMs: readonly number[];\n\n  public constructor(options: JsonRpcClientOptions) {\n    // url is a base URL; append the JSON-RPC path (strip any trailing slash).\n    const base = options.url.replace(/\\/+$/, '');\n    this.endpoint = `${base}${JSON_RPC_PATH}`;\n    this.timeoutMs = options.timeoutMs ?? TIMEOUTS.rpc;\n    this.semaphore = new Semaphore(options.maxConcurrent ?? DEFAULT_MAX_CONCURRENT);\n    this.retryDelaysMs = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;\n    if (options.tls?.rejectUnauthorized === false) {\n      this.dispatcher = new Agent({ connect: { rejectUnauthorized: false } });\n    } else {\n      this.dispatcher = undefined;\n    }\n  }\n\n  /**\n   * Invoke a JSON-RPC method and return the parsed `result`. Throws a typed\n   * error on a truthy `error` field or on a transport failure.\n   */\n  public async post(\n    method: string,\n    params?: Record<string, unknown>,\n    opts?: JsonRpcPostOptions,\n  ): Promise<unknown> {\n    const merged: Record<string, unknown> = { ...(params ?? {}) };\n    if (opts?.sessionId !== undefined) {\n      merged[SESSION_ID_PARAM] = opts.sessionId;\n    }\n\n    const envelope = {\n      method,\n      params: stringifyParams(merged),\n      jsonrpc: '1.1',\n      id: 0,\n    };\n    const body = Buffer.from(JSON.stringify(envelope), 'utf-8');\n    const delays = SESSION_BYPASS_METHODS.has(method) ? [] : this.retryDelaysMs;\n\n    for (let attempt = 0; ; attempt += 1) {\n      try {\n        return await this.sendGuarded(body);\n      } catch (err) {\n        const wait = delays[attempt];\n        if (!(err instanceof BackendUnavailableError) || wait === undefined) throw err;\n        await delay(wait);\n      }\n    }\n  }\n\n  private async sendGuarded(body: Buffer): Promise<unknown> {\n    await this.semaphore.acquire();\n    try {\n      return await this.send(body);\n    } finally {\n      this.semaphore.release();\n    }\n  }\n\n  private async send(body: Buffer): Promise<unknown> {\n    const controller = new AbortController();\n    const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n\n    let raw: Buffer;\n    let status: number;\n    try {\n      const init: RequestInit = {\n        method: 'POST',\n        headers: {\n          'Content-Type': 'application/json',\n          Accept: 'application/json',\n        },\n        body,\n        signal: controller.signal,\n      };\n      if (this.dispatcher) init.dispatcher = this.dispatcher;\n\n      const response = await fetch(this.endpoint, init);\n      status = response.status;\n      const arrayBuffer = await response.arrayBuffer();\n      raw = Buffer.from(arrayBuffer);\n    } catch (err) {\n      // Network/connection/abort failures become NoConnectionError (via mapper).\n      throw mapTransportError(err);\n    } finally {\n      clearTimeout(timer);\n    }\n\n    if (status >= 500) {\n      throw new BackendUnavailableError(status, `JSON-RPC endpoint answered HTTP ${status}`);\n    }\n    if (raw.length === 0) {\n      throw new ClientError('JSON-RPC response had an empty body');\n    }\n\n    let parsed: JsonRpcResponse;\n    try {\n      parsed = JSON.parse(raw.toString('utf-8')) as JsonRpcResponse;\n    } catch {\n      throw new ClientError('JSON-RPC response was not valid JSON');\n    }\n\n    if (parsed.error) {\n      throw mapJsonRpcError(parsed.error);\n    }\n    return parsed.result;\n  }\n\n  /** Release the underlying TLS dispatcher, if any. */\n  public async close(): Promise<void> {\n    if (this.dispatcher) {\n      await this.dispatcher.close();\n    }\n  }\n}\n","/**\n * JSON-RPC method names and param keys used against the CCU WebUI\n * (`/api/homematic.cgi`), mirroring the authoritative names from aiohomematic.\n */\n\n/** The param key under which the session id is injected into requests. */\nexport const SESSION_ID_PARAM = '_session_id_' as const;\n\n/** Exact JSON-RPC method names accepted by the CCU WebUI. */\nexport const JsonRpcMethod = {\n  CCU_GET_AUTH_ENABLED: 'CCU.getAuthEnabled',\n  CCU_GET_HTTPS_REDIRECT_ENABLED: 'CCU.getHttpsRedirectEnabled',\n  CCU_GET_VERSION: 'CCU.getVersion',\n  CCU_GET_SERIAL: 'CCU.getSerial',\n  CCU_GET_HEATING_GROUP_LIST: 'CCU.getHeatingGroupList',\n  DEVICE_LIST_ALL_DETAIL: 'Device.listAllDetail',\n  DEVICE_GET_REGA_ID_BY_ADDRESS: 'Device.getReGaIDByAddress',\n  DEVICE_SET_NAME: 'Device.setName',\n  CHANNEL_SET_NAME: 'Channel.setName',\n  INTERFACE_LIST_INTERFACES: 'Interface.listInterfaces',\n  INTERFACE_LIST_DEVICES: 'Interface.listDevices',\n  INTERFACE_IS_PRESENT: 'Interface.isPresent',\n  INTERFACE_GET_DUTY_CYCLE: 'Interface.getDutyCycle',\n  INTERFACE_GET_INSTALL_MODE: 'Interface.getInstallMode',\n  INTERFACE_SET_INSTALL_MODE_HMIP: 'Interface.setInstallModeHMIP',\n  INTERFACE_SET_METADATA: 'Interface.setMetadata',\n  PROGRAM_GET_ALL: 'Program.getAll',\n  PROGRAM_EXECUTE: 'Program.execute',\n  SYSVAR_GET_ALL: 'SysVar.getAll',\n  SYSVAR_GET_VALUE_BY_NAME: 'SysVar.getValueByName',\n  SYSVAR_SET_BOOL: 'SysVar.setBool',\n  SYSVAR_SET_FLOAT: 'SysVar.setFloat',\n  ROOM_GET_ALL: 'Room.getAll',\n  SUBSECTION_GET_ALL: 'Subsection.getAll',\n  REGA_RUN_SCRIPT: 'ReGa.runScript',\n  SESSION_LOGIN: 'Session.login',\n  SESSION_LOGOUT: 'Session.logout',\n  SESSION_RENEW: 'Session.renew',\n  SYSTEM_LIST_METHODS: 'system.listMethods',\n} as const;\n\n/** Union of all exact JSON-RPC method name string literals. */\nexport type JsonRpcMethodName = (typeof JsonRpcMethod)[keyof typeof JsonRpcMethod];\n\n/**\n * The three `Session.*` methods that bypass the circuit breaker (they must be\n * usable even while the breaker is OPEN to recover a session).\n */\nexport const SESSION_BYPASS_METHODS: ReadonlySet<string> = new Set<string>([\n  JsonRpcMethod.SESSION_LOGIN,\n  JsonRpcMethod.SESSION_LOGOUT,\n  JsonRpcMethod.SESSION_RENEW,\n]);\n","/**\n * Session lifecycle manager for the JSON-RPC client. Owns the current session\n * id, performs login/renew/logout, applies a session-age guard to avoid\n * needless renews, and spaces failed logins with a capped exponential backoff.\n *\n * Recovery rules (a CCU reboot wipes every session):\n * - a failed login opens a backoff window of min(1 s · 2^(n-1), 5 min); a login\n *   asked for inside it fails fast with {@link LoginBackoffError} and sends\n *   nothing. There is no permanent lockout: once the window passes, the next\n *   call tries again. A success, or {@link SessionManager.resetBackoff} (the\n *   CCU answered again), closes the window.\n * - concurrent callers share one login and one renew, so a burst of N calls\n *   is one request to the CCU, one session, and one failure at most.\n * - a renew that does not answer `true` drops the session; a call refused as\n *   `access denied` through {@link SessionManager.boundClient} drops it, logs\n *   in again and retries once. A stale id is never reused.\n */\nimport { JsonRpcMethod } from './methods.js';\nimport { AuthFailureError, LoginBackoffError } from '../../support/errors.js';\n\n/** The JSON-RPC contract the session needs; {@link JsonRpcClient} satisfies it. */\nexport interface SessionPostClient {\n  post(\n    method: string,\n    params?: Record<string, unknown>,\n    opts?: { readonly sessionId?: string },\n  ): Promise<unknown>;\n}\n\n/** Configuration for {@link SessionManager}. */\nexport interface SessionManagerOptions {\n  readonly client: SessionPostClient;\n  readonly username: string;\n  readonly password: string;\n  /** Seconds before a session is considered stale and renew is attempted. Default 90. */\n  readonly sessionAgeSeconds?: number;\n  /** Injectable clock in ms (for testability). Default `Date.now`. */\n  readonly now?: () => number;\n}\n\nconst DEFAULT_SESSION_AGE_SECONDS = 90;\n\n/** Login backoff: 1 s, 2 s, 4 s … capped at 5 min. */\nconst INITIAL_BACKOFF_MS = 1_000;\nconst MAX_BACKOFF_MS = 300_000;\nconst BACKOFF_FACTOR = 2;\n\nexport class SessionManager {\n  private readonly client: SessionPostClient;\n  private readonly username: string;\n  private readonly password: string;\n  private readonly sessionAgeMs: number;\n  private readonly now: () => number;\n\n  private currentSessionId: string | undefined;\n  private lastRefresh = 0;\n  private consecutiveFailures = 0;\n  private nextAttemptAt = 0;\n  private inFlightLogin: Promise<string> | undefined;\n  private inFlightEnsure: Promise<string> | undefined;\n\n  public constructor(options: SessionManagerOptions) {\n    this.client = options.client;\n    this.username = options.username;\n    this.password = options.password;\n    this.sessionAgeMs = (options.sessionAgeSeconds ?? DEFAULT_SESSION_AGE_SECONDS) * 1000;\n    this.now = options.now ?? ((): number => Date.now());\n  }\n\n  /** The current session id, or `undefined` if not logged in. */\n  public get sessionId(): string | undefined {\n    return this.currentSessionId;\n  }\n\n  /**\n   * Log in with username/password (no session id), store the resulting session\n   * id, and return it. Inside an open backoff window it throws\n   * {@link LoginBackoffError} without contacting the CCU. Concurrent calls\n   * share one request.\n   */\n  public login(): Promise<string> {\n    if (this.inFlightLogin !== undefined) return this.inFlightLogin;\n    if (this.consecutiveFailures > 0 && this.now() < this.nextAttemptAt) {\n      return Promise.reject(new LoginBackoffError(this.nextAttemptAt, this.consecutiveFailures));\n    }\n    const attempt = this.sendLogin().finally(() => {\n      this.inFlightLogin = undefined;\n    });\n    this.inFlightLogin = attempt;\n    return attempt;\n  }\n\n  /** Close the backoff window: the next login goes out at once (the CCU answered again). */\n  public resetBackoff(): void {\n    this.consecutiveFailures = 0;\n    this.nextAttemptAt = 0;\n  }\n\n  /** Force a renew on the next {@link ensureSession} (the CCU may have restarted). */\n  public markStale(): void {\n    this.lastRefresh = Number.NEGATIVE_INFINITY;\n  }\n\n  /**\n   * Renew the current session if it is older than the session-age window. If it\n   * was refreshed recently this is a no-op. A renew that does not answer `true`\n   * or is refused drops the session and logs in again; a renew that fails for\n   * another reason (CCU unreachable) drops the session and rethrows, so the\n   * next call logs in instead of reusing an id the CCU may have forgotten.\n   */\n  public async renew(): Promise<void> {\n    const id = this.currentSessionId;\n    if (id === undefined) {\n      await this.login();\n      return;\n    }\n\n    if (this.now() - this.lastRefresh < this.sessionAgeMs) {\n      return;\n    }\n\n    let result: unknown;\n    try {\n      result = await this.client.post(JsonRpcMethod.SESSION_RENEW, undefined, { sessionId: id });\n    } catch (err) {\n      this.dropSession(id);\n      if (err instanceof AuthFailureError) {\n        // Best-effort: the CCU refused the id, a logout of it may fail too.\n        await this.client\n          .post(JsonRpcMethod.SESSION_LOGOUT, undefined, { sessionId: id })\n          .catch(() => undefined);\n        await this.login();\n        return;\n      }\n      throw err;\n    }\n    if (result === true) {\n      this.lastRefresh = this.now();\n      return;\n    }\n    this.dropSession(id);\n    await this.login();\n  }\n\n  /**\n   * Log out the current session (best-effort) and clear it. No-op if none. A\n   * login still in flight is awaited first, so its session is logged out too.\n   */\n  public async logout(): Promise<void> {\n    if (this.inFlightLogin !== undefined) {\n      await this.inFlightLogin.catch(() => undefined);\n    }\n    const id = this.currentSessionId;\n    if (id === undefined) return;\n    this.currentSessionId = undefined;\n    await this.client.post(JsonRpcMethod.SESSION_LOGOUT, undefined, { sessionId: id });\n  }\n\n  /** Ensure a usable session exists: login if none, else renew. Returns the id. Concurrent calls share one pass. */\n  public ensureSession(): Promise<string> {\n    if (this.inFlightEnsure !== undefined) return this.inFlightEnsure;\n    const pass = this.runEnsure().finally(() => {\n      this.inFlightEnsure = undefined;\n    });\n    this.inFlightEnsure = pass;\n    return pass;\n  }\n\n  /**\n   * A client that sends through this session: a call carrying a session id that\n   * the CCU refuses as `access denied` drops that session, logs in again and is\n   * retried once with the new id. Calls without a session id pass through.\n   */\n  public boundClient(): SessionPostClient {\n    return {\n      post: async (method, params, opts) => {\n        const sid = opts?.sessionId;\n        if (sid === undefined) return this.client.post(method, params, opts);\n        try {\n          return await this.client.post(method, params, opts);\n        } catch (err) {\n          if (!(err instanceof AuthFailureError)) throw err;\n          this.dropSession(sid);\n          const fresh = await this.ensureSession();\n          return this.client.post(method, params, { sessionId: fresh });\n        }\n      },\n    };\n  }\n\n  private async runEnsure(): Promise<string> {\n    if (this.currentSessionId === undefined) {\n      return this.login();\n    }\n    await this.renew();\n    if (this.currentSessionId === undefined) {\n      return this.login();\n    }\n    return this.currentSessionId;\n  }\n\n  private async sendLogin(): Promise<string> {\n    try {\n      const result = await this.client.post(JsonRpcMethod.SESSION_LOGIN, {\n        username: this.username,\n        password: this.password,\n      });\n      const id = String(result);\n      this.currentSessionId = id;\n      this.lastRefresh = this.now();\n      this.resetBackoff();\n      return id;\n    } catch (err) {\n      this.consecutiveFailures += 1;\n      this.nextAttemptAt = this.now() + this.backoffDelayMs();\n      throw err;\n    }\n  }\n\n  /** Forget `id` if it is still the current session (a newer one stays). */\n  private dropSession(id: string): void {\n    if (this.currentSessionId === id) this.currentSessionId = undefined;\n  }\n\n  private backoffDelayMs(): number {\n    const exp = INITIAL_BACKOFF_MS * BACKOFF_FACTOR ** (this.consecutiveFailures - 1);\n    return Math.min(exp, MAX_BACKOFF_MS);\n  }\n}\n","/**\n * Minimal HTTP transport for the CCU WebUI's HMServer pages\n * (`/pages/jpages/...`), which are NOT JSON-RPC: the WebUI's own JavaScript\n * calls them as `Ajax.Request('/pages/jpages/group/save?sid=<session>')` with a\n * raw JSON body (Prototype `postBody`) on the same origin as `/api/homematic.cgi`.\n *\n * The session id is the one the JSON-RPC {@link SessionManager} already owns; it\n * travels only in the query string and is NEVER placed in an error message.\n */\nimport { Agent, fetch as undiciFetch, type RequestInit } from 'undici';\nimport { CcuManagementError, ClientError, mapTransportError } from '../../support/errors.js';\nimport { TIMEOUTS } from '../../support/constants.js';\n\n/** What the group management needs from the WebUI HTTP layer. */\nexport interface WebUiHttp {\n  get(path: string, sessionId: string): Promise<string>;\n  post(path: string, sessionId: string, body: string): Promise<string>;\n}\n\n/** Injectable fetch (tests). */\nexport type WebUiFetch = (\n  url: string,\n  init: {\n    readonly method: 'GET' | 'POST';\n    readonly headers: Record<string, string>;\n    readonly body: string | undefined;\n    readonly signal: AbortSignal;\n  },\n) => Promise<{ readonly status: number; text(): Promise<string> }>;\n\n/** Options for {@link WebUiHttpClient}. */\nexport interface WebUiHttpClientOptions {\n  /** Base URL of the CCU, e.g. `http://ccu` (no port: the WebUI answers on 80/443). */\n  readonly url: string;\n  readonly rejectUnauthorized?: boolean;\n  readonly timeoutMs?: number;\n  readonly fetch?: WebUiFetch;\n}\n\nconst FORM_CONTENT_TYPE = 'application/x-www-form-urlencoded; charset=UTF-8';\nconst ESCAPE_SAFE = /[A-Za-z0-9@*_+\\-./]/;\n\n/**\n * JavaScript's legacy `escape()`: the WebUI sends the group name through it\n * (`data.groupName = escape(viewModel.groupName())`).\n */\nexport function jsEscape(text: string): string {\n  let out = '';\n  for (const ch of text) {\n    const unit = ch.charCodeAt(0);\n    if (ESCAPE_SAFE.test(ch)) out += ch;\n    else if (ch.length === 1 && unit < 256)\n      out += `%${unit.toString(16).toUpperCase().padStart(2, '0')}`;\n    else\n      for (let i = 0; i < ch.length; i += 1) {\n        out += `%u${ch.charCodeAt(i).toString(16).toUpperCase().padStart(4, '0')}`;\n      }\n  }\n  return out;\n}\n\nexport class WebUiHttpClient implements WebUiHttp {\n  private readonly base: string;\n  private readonly timeoutMs: number;\n  private readonly fetchFn: WebUiFetch;\n  private readonly dispatcher: Agent | undefined;\n\n  public constructor(options: WebUiHttpClientOptions) {\n    this.base = options.url.replace(/\\/+$/, '');\n    this.timeoutMs = options.timeoutMs ?? TIMEOUTS.rpc;\n    this.dispatcher =\n      options.rejectUnauthorized === false\n        ? new Agent({ connect: { rejectUnauthorized: false } })\n        : undefined;\n    this.fetchFn = options.fetch ?? this.defaultFetch.bind(this);\n  }\n\n  public get(path: string, sessionId: string): Promise<string> {\n    return this.request('GET', path, sessionId, undefined);\n  }\n\n  public post(path: string, sessionId: string, body: string): Promise<string> {\n    return this.request('POST', path, sessionId, body);\n  }\n\n  public async close(): Promise<void> {\n    await this.dispatcher?.close();\n  }\n\n  private async request(\n    method: 'GET' | 'POST',\n    path: string,\n    sessionId: string,\n    body: string | undefined,\n  ): Promise<string> {\n    const url = `${this.base}${path}?sid=${encodeURIComponent(sessionId)}`;\n    const controller = new AbortController();\n    const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n    try {\n      const response = await this.fetchFn(url, {\n        method,\n        headers: body === undefined ? {} : { 'Content-Type': FORM_CONTENT_TYPE },\n        body,\n        signal: controller.signal,\n      });\n      const text = await response.text();\n      if (response.status < 200 || response.status >= 300) {\n        throw new ClientError(`HTTP ${response.status}`);\n      }\n      return text;\n    } catch (err) {\n      // Never forward the raw error text: it may echo the URL, and the URL holds the sid.\n      const mapped = err instanceof ClientError ? err : mapTransportError(err);\n      throw new CcuManagementError(\n        `${method} ${path}`,\n        new Error(`${mapped.name}: ${mapped.message.split(sessionId).join('<sid>')}`),\n      );\n    } finally {\n      clearTimeout(timer);\n    }\n  }\n\n  private async defaultFetch(url: string, init: Parameters<WebUiFetch>[1]): ReturnType<WebUiFetch> {\n    const req: RequestInit = { method: init.method, headers: init.headers, signal: init.signal };\n    if (init.body !== undefined) req.body = init.body;\n    if (this.dispatcher) req.dispatcher = this.dispatcher;\n    return undiciFetch(url, req);\n  }\n}\n","/**\n * ReGa (Homematic scripting) runner over JSON-RPC.\n *\n * The CCU exposes a `ReGa.runScript` JSON-RPC method whose single `script`\n * param is the entire HomeMatic-Script body. We substitute `##key##`\n * placeholders, POST the body, and re-parse the textual `result`:\n *\n * - The CCU returns the script `WriteLine(...)` output as a JSON **string**,\n *   which we sanitize (strip raw control chars that would break `JSON.parse`)\n *   and parse.\n * - Names emitted by the CCU are `UriEncode`d over **latin1** (ISO-8859-1)\n *   bytes, so percent-decoding must reassemble the raw bytes and decode them as\n *   latin1 rather than UTF-8.\n *\n * This module is pure transport glue: it never owns a session, it is handed one.\n */\nimport { ClientError } from '../../support/errors.js';\nimport { JsonRpcMethod } from '../../transport/jsonrpc/methods.js';\n\n/**\n * The minimal client contract the runner needs: a JSON-RPC `post` returning the\n * raw `{ result }` envelope. {@link JsonRpcClient} satisfies this structurally.\n */\nexport interface RegaPostClient {\n  post(\n    method: string,\n    params?: Record<string, unknown>,\n    opts?: { sessionId?: string },\n  ): Promise<unknown>;\n}\n\n/**\n * Escape a string for safe interpolation into a double-quoted ReGa string\n * literal. Order matters: backslashes are doubled first, then quotes are\n * escaped (so an already-present `\\\"` is not mangled).\n */\nexport function escapeRegaString(s: string): string {\n  return s.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"');\n}\n\n/**\n * Strip raw ASCII control characters (U+0000–U+001F) from a string so that a\n * JSON document carrying them inside string literals becomes parseable. Valid\n * JSON escapes (`\\n`, `\\t`, …) are already backslash sequences and are left\n * intact; only *raw* control bytes are removed. Mirrors aiohomematic's intent\n * of tolerating malformed ReGa output.\n */\nconst CONTROL_CHARS = /[\\u0000-\\u001F]/g;\n\nexport function sanitizeJsonControlChars(s: string): string {\n  return s.replace(CONTROL_CHARS, '');\n}\n\n/**\n * Decode a CCU `UriEncode`d name. The CCU percent-encodes the latin1 byte\n * sequence of the name, so `%E8` is the single byte 0xE8 ('è' in latin1), not a\n * UTF-8 continuation. We therefore rebuild the raw bytes and decode them as\n * latin1; `decodeURIComponent` cannot be used because it assumes UTF-8.\n */\nexport function decodeRegaName(encoded: string): string {\n  const bytes: number[] = [];\n  for (let i = 0; i < encoded.length; i += 1) {\n    const ch = encoded[i] as string;\n    if (ch === '%' && i + 2 < encoded.length) {\n      const hex = encoded.slice(i + 1, i + 3);\n      const byte = Number.parseInt(hex, 16);\n      if (!Number.isNaN(byte) && /^[0-9a-fA-F]{2}$/.test(hex)) {\n        bytes.push(byte);\n        i += 2;\n        continue;\n      }\n    }\n    if (ch === '+') {\n      bytes.push(0x20);\n      continue;\n    }\n    bytes.push(ch.charCodeAt(0) & 0xff);\n  }\n  return Buffer.from(bytes).toString('latin1');\n}\n\n/**\n * Substitute every `##key##` placeholder in `body` with the ReGa-escaped string\n * form of its value (all occurrences, literal match — no regex meta in keys).\n */\nfunction substitute(body: string, params: Record<string, string | number>): string {\n  let out = body;\n  for (const [key, value] of Object.entries(params)) {\n    const escaped = escapeRegaString(String(value));\n    out = out.split(`##${key}##`).join(escaped);\n  }\n  return out;\n}\n\n/**\n * Run a ReGa script body. Placeholders are substituted, the script is POSTed via\n * `ReGa.runScript`, and the returned value is interpreted as the script result:\n * `JsonRpcClient.post` already unwraps the JSON-RPC envelope, so its return\n * value is the script's `WriteLine`/`Write` output. A string result is\n * sanitized (raw control chars stripped) and JSON-parsed; an already-structured\n * (object) result is returned unchanged.\n *\n * @throws {ClientError} when the response carries no usable result.\n */\nexport async function runScript(\n  client: RegaPostClient,\n  sessionId: string | undefined,\n  body: string,\n  params?: Record<string, string | number>,\n): Promise<unknown> {\n  const script = params ? substitute(body, params) : body;\n  const result = await client.post(\n    JsonRpcMethod.REGA_RUN_SCRIPT,\n    { script },\n    sessionId !== undefined ? { sessionId } : undefined,\n  );\n\n  if (result === undefined || result === null) {\n    throw new ClientError('ReGa.runScript returned no result');\n  }\n  if (typeof result === 'string') {\n    const parsed: unknown = JSON.parse(sanitizeJsonControlChars(result));\n    return parsed;\n  }\n  return result;\n}\n","/**\n * HomeMatic-Script (ReGa) bodies executed via `ReGa.runScript`.\n *\n * The four set/describe scripts are taken verbatim from aiohomematic's bundled\n * `.fn` scripts (authoritative against real CCU firmware). {@link GET_ROOMS_FUNCTIONS}\n * is a custom, channel-address-keyed script written against the same ReGa idioms\n * (`get_service_messages.fn`) to recover the rooms/functions mapping that the\n * JSON-RPC API does not expose by channel address.\n *\n * Placeholders use the `##key##` convention substituted by the ReGa runner.\n */\n\n/** Set a string system variable by name. Placeholders: `##name##`, `##value##`. */\nexport const SET_SYSTEM_VARIABLE = `object sv = dom.GetObject(\"##name##\");\nif (sv) {\n    sv.State(\"##value##\");\n}`;\n\n/** Enable/disable a program. Placeholders: `##id##`, `##state##` (1 active, 0 inactive). */\nexport const SET_PROGRAM_STATE = `object prog = dom.GetObject(##id##);\nif (prog) {\n    prog.Active(##state##);\n}`;\n\n/**\n * Emit `[{\"id\":..,\"description\":<UriEncoded>},...]` for every system variable.\n * Description carries the `HAHM` marker for extended (writable) sysvars.\n */\nexport const SYSVAR_DESCRIPTIONS = `string sSysVarId;\nstring sSep = \"\";\nWriteLine(\"[\");\nforeach(sSysVarId, dom.GetObject(ID_SYSTEM_VARIABLES).EnumUsedIDs()) {\n    object oSysVar = dom.GetObject(sSysVarId);\n    Write(sSep);\n    Write(\"{\");\n    Write(\"\\\\\"id\\\\\":\");\n    Write(oSysVar.ID());\n    Write(\",\\\\\"description\\\\\":\\\\\"\");\n    Write(oSysVar.DPInfo().UriEncode());\n    Write(\"\\\\\"}\");\n    sSep = \",\";\n}\nWriteLine(\"]\");`;\n\n/**\n * Emit `[{\"id\":..,\"description\":<UriEncoded>},...]` for every program, using\n * `PrgInfo()` as the description source.\n */\nexport const PROGRAM_DESCRIPTIONS = `string sPrgId;\nstring sSep = \"\";\nWriteLine(\"[\");\nforeach(sPrgId, dom.GetObject(ID_PROGRAMS).EnumUsedIDs()) {\n    object oPrg = dom.GetObject(sPrgId);\n    Write(sSep);\n    Write(\"{\");\n    Write(\"\\\\\"id\\\\\":\");\n    Write(oPrg.ID());\n    Write(\",\\\\\"description\\\\\":\\\\\"\");\n    Write(oPrg.PrgInfo().UriEncode());\n    Write(\"\\\\\"}\");\n    sSep = \",\";\n}\nWriteLine(\"]\");`;\n\n/**\n * CUSTOM script: build a single JSON object keyed by **channel address**:\n *\n *   {\"rooms\":{\"<addr>\":[\"<encName>\",...]},\"functions\":{\"<addr>\":[\"<encName>\",...]}}\n *\n * We enumerate every channel (`ID_CHANNELS`), read its `Address()`, then iterate\n * its `ChnRoom()` and `ChnFunction()` id lists, emitting each referenced object's\n * `Name().UriEncode()`. Comma handling is done with per-list / per-channel\n * separator variables so the output is valid JSON. Names are UriEncoded (latin1)\n * and decoded host-side by {@link decodeRegaName}.\n */\nexport const GET_ROOMS_FUNCTIONS = `string sChnId;\nstring sRoomId;\nstring sFuncId;\nstring sChnSepR = \"\";\nstring sChnSepF = \"\";\nWrite(\"{\\\\\"rooms\\\\\":{\");\nforeach(sChnId, dom.GetObject(ID_CHANNELS).EnumUsedIDs()) {\n    object oChn = dom.GetObject(sChnId);\n    if (oChn) {\n        string sAddr = oChn.Address();\n        object oRooms = oChn.ChnRoom();\n        if (oRooms && oRooms.Count() > 0) {\n            Write(sChnSepR);\n            Write(\"\\\\\"\");\n            Write(sAddr);\n            Write(\"\\\\\":[\");\n            string sRoomSep = \"\";\n            foreach(sRoomId, oRooms) {\n                object oRoom = dom.GetObject(sRoomId);\n                Write(sRoomSep);\n                Write(\"\\\\\"\");\n                Write(oRoom.Name().UriEncode());\n                Write(\"\\\\\"\");\n                sRoomSep = \",\";\n            }\n            Write(\"]\");\n            sChnSepR = \",\";\n        }\n    }\n}\nWrite(\"},\\\\\"functions\\\\\":{\");\nforeach(sChnId, dom.GetObject(ID_CHANNELS).EnumUsedIDs()) {\n    object oChn = dom.GetObject(sChnId);\n    if (oChn) {\n        string sAddr = oChn.Address();\n        object oFuncs = oChn.ChnFunction();\n        if (oFuncs && oFuncs.Count() > 0) {\n            Write(sChnSepF);\n            Write(\"\\\\\"\");\n            Write(sAddr);\n            Write(\"\\\\\":[\");\n            string sFuncSep = \"\";\n            foreach(sFuncId, oFuncs) {\n                object oFunc = dom.GetObject(sFuncId);\n                Write(sFuncSep);\n                Write(\"\\\\\"\");\n                Write(oFunc.Name().UriEncode());\n                Write(\"\\\\\"\");\n                sFuncSep = \",\";\n            }\n            Write(\"]\");\n            sChnSepF = \",\";\n        }\n    }\n}\nWrite(\"}}\");`;\n\n/**\n * Emit `[{\"id\",\"name\"(UriEncoded),\"address\"(\"DEV:ch\"),\"type\"(HSSID),\"timestamp\"\n * (epoch seconds),\"acknowledgeable\"},...]` for every ACTIVE service message.\n *\n * Source: the WebUI's own listing in eq-3/occu `WebUI/www/rega/esp/system.fn`\n * (`dom.GetObject(ID_SERVICES)`, `OT_ALARMDP`, `AlState() == asOncoming`,\n * `LastTriggerID()` for the message type and channel). A message is\n * acknowledgeable under the same rule the WebUI's `ReceiptAlarm` applies\n * (`WebUI/www/rega/esp/functions.fn`): there is no trigger data point, or the\n * trigger is writable (`STICKY_UNREACH` is; `UNREACH` / `LOWBAT` clear on their own).\n */\nexport const GET_SERVICE_MESSAGES = `string sAID;\nstring sSep = \"\";\nWrite(\"[\");\nforeach(sAID, dom.GetObject(ID_SERVICES).EnumIDs()) {\n    object oAlarm = dom.GetObject(sAID);\n    if (oAlarm) {\n        if (oAlarm.IsTypeOf(OT_ALARMDP)) {\n            if (oAlarm.AlState() == asOncoming) {\n                string sAddr = \"\";\n                string sType = \"\";\n                string sAck = \"true\";\n                object oLast = dom.GetObject(oAlarm.LastTriggerID());\n                if (oLast) {\n                    sType = oLast.HSSID();\n                    object oChn = dom.GetObject(oLast.Channel());\n                    if (oChn) {\n                        sAddr = oChn.Address();\n                    }\n                }\n                object oTrig = dom.GetObject(oAlarm.AlTriggerDP());\n                if (oTrig) {\n                    if (!(oTrig.Operations() & OPERATION_WRITE)) {\n                        sAck = \"false\";\n                    }\n                }\n                Write(sSep);\n                Write(\"{\\\\\"id\\\\\":\");\n                Write(oAlarm.ID());\n                Write(\",\\\\\"name\\\\\":\\\\\"\");\n                Write(oAlarm.Name().UriEncode());\n                Write(\"\\\\\",\\\\\"address\\\\\":\\\\\"\");\n                Write(sAddr);\n                Write(\"\\\\\",\\\\\"type\\\\\":\\\\\"\");\n                Write(sType);\n                Write(\"\\\\\",\\\\\"timestamp\\\\\":\");\n                Write(oAlarm.AlOccurrenceTime().ToInteger());\n                Write(\",\\\\\"acknowledgeable\\\\\":\");\n                Write(sAck);\n                Write(\"}\");\n                sSep = \",\";\n            }\n        }\n    }\n}\nWrite(\"]\");`;\n\n/**\n * Acknowledge (\"quittieren\") one service message by ReGa object id. Mirrors the\n * WebUI's `ReceiptAlarm` (`oAlarm.AlReceipt()`). Placeholder: `##id##` (digits\n * only, validated by the caller). Emits `{\"ok\":true}` when the object existed.\n */\nexport const ACKNOWLEDGE_SERVICE_MESSAGE = `object oAlarm = dom.GetObject(##id##);\nif (oAlarm) {\n    oAlarm.AlReceipt();\n    Write(\"{\\\\\"ok\\\\\":true}\");\n} else {\n    Write(\"{\\\\\"ok\\\\\":false}\");\n}`;\n\n/**\n * Emit `{\"release\":<UriEncoded /VERSION>,\"host\":<UriEncoded hostname>}`. The\n * `/VERSION` file carries `VERSION=` and `PRODUCT=` (CCU3, RaspberryMatic,\n * OpenCCU); no JSON-RPC method exposes the product (`CCU.getVersion` reads only\n * the `VERSION=` line, see eq-3/occu `WebUI/www/api/methods/ccu/getversion.tcl`).\n */\nexport const GET_CCU_PLATFORM = `string sRelease;\nstring sHost;\nstring sErr;\nsystem.Exec(\"cat /VERSION\", &sRelease, &sErr);\nsystem.Exec(\"hostname\", &sHost, &sErr);\nWrite(\"{\\\\\"release\\\\\":\\\\\"\");\nWrite(sRelease.UriEncode());\nWrite(\"\\\\\",\\\\\"host\\\\\":\\\\\"\");\nWrite(sHost.UriEncode());\nWrite(\"\\\\\"}\");`;\n\n// --- names and rooms ---------------------------------------------------------\n//\n// Each script below starts with a `! nodehomematic:<op>` comment line (a ReGa\n// comment) naming the operation, and declares its inputs as `string sX =\n// \"##x##\";` lines so the substituted values are plain, escaped string literals.\n// Names are written back `UriEncode`d (latin1) and decoded by `decodeRegaName`.\n\n/**\n * Rename a device and, when `##channels##` is `1`, every channel of it to\n * `<name>:<channel number>`. The lookup by address is Device.getReGaIDByAddress\n * (eq-3/occu `WebUI/www/api/methods/device/getregaidbyaddress.tcl`); the write\n * is `Name()` as in `device/setname.tcl` and `channel/setname.tcl`, which also\n * read the name back because the CCU keeps names unique.\n *\n * Emits `{\"ok\":false}` for an unknown address, else\n * `{\"ok\":true,\"name\":<enc>,\"channels\":[{\"address\",\"name\":<enc>},...]}`.\n */\nexport const RENAME_DEVICE = `! nodehomematic:renameDevice\nstring sAddress = \"##address##\";\nstring sName = \"##name##\";\nstring sChannels = \"##channels##\";\nstring sId;\nstring sDevId = \"\";\nstring sSep = \"\";\nforeach(sId, root.Devices().EnumIDs()) {\n    object oTmp = dom.GetObject(sId);\n    if (oTmp) {\n        if (oTmp.Address() == sAddress) {\n            sDevId = sId;\n        }\n    }\n}\nif (sDevId == \"\") {\n    Write(\"{\\\\\"ok\\\\\":false}\");\n} else {\n    object oDev = dom.GetObject(sDevId);\n    oDev.Name(sName);\n    Write(\"{\\\\\"ok\\\\\":true,\\\\\"name\\\\\":\\\\\"\");\n    Write(oDev.Name().UriEncode());\n    Write(\"\\\\\",\\\\\"channels\\\\\":[\");\n    if (sChannels == \"1\") {\n        foreach(sId, oDev.Channels().EnumUsedIDs()) {\n            object oChn = dom.GetObject(sId);\n            if (oChn) {\n                oChn.Name(sName # \":\" # oChn.ChnNumber());\n                Write(sSep);\n                Write(\"{\\\\\"address\\\\\":\\\\\"\");\n                Write(oChn.Address());\n                Write(\"\\\\\",\\\\\"name\\\\\":\\\\\"\");\n                Write(oChn.Name().UriEncode());\n                Write(\"\\\\\"}\");\n                sSep = \",\";\n            }\n        }\n    }\n    Write(\"]}\");\n}`;\n\n/**\n * Rename one channel (eq-3/occu `WebUI/www/api/methods/channel/setname.tcl`),\n * found by address among `ID_CHANNELS`. Emits `{\"ok\":false}` or\n * `{\"ok\":true,\"name\":<enc>}`.\n */\nexport const RENAME_CHANNEL = `! nodehomematic:renameChannel\nstring sAddress = \"##address##\";\nstring sName = \"##name##\";\nstring sId;\nstring sChnId = \"\";\nforeach(sId, dom.GetObject(ID_CHANNELS).EnumUsedIDs()) {\n    object oTmp = dom.GetObject(sId);\n    if (oTmp) {\n        if (oTmp.Address() == sAddress) {\n            sChnId = sId;\n        }\n    }\n}\nif (sChnId == \"\") {\n    Write(\"{\\\\\"ok\\\\\":false}\");\n} else {\n    object oChn = dom.GetObject(sChnId);\n    oChn.Name(sName);\n    Write(\"{\\\\\"ok\\\\\":true,\\\\\"name\\\\\":\\\\\"\");\n    Write(oChn.Name().UriEncode());\n    Write(\"\\\\\"}\");\n}`;\n\n/**\n * Every room with its member channels by ADDRESS:\n * `[{\"id\":\"<id>\",\"name\":<enc>,\"channels\":[\"DEV:1\",...]},...]`. Same walk as\n * Room.getAll (eq-3/occu `WebUI/www/api/methods/room/getall.tcl`:\n * `ID_ROOMS` → `EnumUsedIDs()`), which answers ReGa ids instead of addresses.\n */\nexport const LIST_ROOMS = `! nodehomematic:listRooms\nstring sRoomId;\nstring sChnId;\nstring sRoomSep = \"\";\nstring sChnSep = \"\";\nWrite(\"[\");\nforeach(sRoomId, dom.GetObject(ID_ROOMS).EnumUsedIDs()) {\n    object oRoom = dom.GetObject(sRoomId);\n    if (oRoom) {\n        Write(sRoomSep);\n        Write(\"{\\\\\"id\\\\\":\\\\\"\");\n        Write(oRoom.ID());\n        Write(\"\\\\\",\\\\\"name\\\\\":\\\\\"\");\n        Write(oRoom.Name().UriEncode());\n        Write(\"\\\\\",\\\\\"channels\\\\\":[\");\n        sChnSep = \"\";\n        foreach(sChnId, oRoom.EnumUsedIDs()) {\n            object oChn = dom.GetObject(sChnId);\n            if (oChn) {\n                if (oChn.IsTypeOf(OT_CHANNEL)) {\n                    Write(sChnSep);\n                    Write(\"\\\\\"\");\n                    Write(oChn.Address());\n                    Write(\"\\\\\"\");\n                    sChnSep = \",\";\n                }\n            }\n        }\n        Write(\"]}\");\n        sRoomSep = \",\";\n    }\n}\nWrite(\"]\");`;\n\n/**\n * Create a room: eq-3/occu `WebUI/www/rega/esp/rooms.fn` `::createRoomRetId`\n * (`dom.CreateObject(OT_ENUM, name)`, `EnumType(etRoom)`, add to `ID_ROOMS`,\n * delete the object again when the add fails). A room of the same name is\n * refused first. Emits `{\"id\":\"<id>\",\"name\":<enc>}`, `{\"error\":\"exists\"}` or\n * `{\"error\":\"failed\"}`.\n */\nexport const CREATE_ROOM = `! nodehomematic:createRoom\nstring sName = \"##name##\";\nstring sId;\nboolean bExists = false;\nforeach(sId, dom.GetObject(ID_ROOMS).EnumUsedIDs()) {\n    object oTmp = dom.GetObject(sId);\n    if (oTmp) {\n        if (oTmp.Name() == sName) {\n            bExists = true;\n        }\n    }\n}\nif (bExists) {\n    Write(\"{\\\\\"error\\\\\":\\\\\"exists\\\\\"}\");\n} else {\n    object oRoom = dom.CreateObject(OT_ENUM, sName);\n    if (oRoom) {\n        oRoom.EnumType(etRoom);\n        boolean bAdded = dom.GetObject(ID_ROOMS).Add(oRoom);\n        if (bAdded) {\n            Write(\"{\\\\\"id\\\\\":\\\\\"\");\n            Write(oRoom.ID());\n            Write(\"\\\\\",\\\\\"name\\\\\":\\\\\"\");\n            Write(oRoom.Name().UriEncode());\n            Write(\"\\\\\"}\");\n        } else {\n            dom.DeleteObject(oRoom.ID());\n            Write(\"{\\\\\"error\\\\\":\\\\\"failed\\\\\"}\");\n        }\n    } else {\n        Write(\"{\\\\\"error\\\\\":\\\\\"failed\\\\\"}\");\n    }\n}`;\n\n/**\n * Rename a room (eq-3/occu `WebUI/www/rega/esp/rooms.fn` `::changeRoomName`),\n * only when `##id##` is a member of `ID_ROOMS`. Emits `{\"ok\":true|false}`.\n */\nexport const RENAME_ROOM = `! nodehomematic:renameRoom\nstring sRoomId = \"##id##\";\nstring sName = \"##name##\";\nstring sId;\nboolean bFound = false;\nforeach(sId, dom.GetObject(ID_ROOMS).EnumUsedIDs()) {\n    if (sId == sRoomId) {\n        bFound = true;\n    }\n}\nif (bFound) {\n    object oRoom = dom.GetObject(sRoomId);\n    oRoom.Name(sName);\n    Write(\"{\\\\\"ok\\\\\":true}\");\n} else {\n    Write(\"{\\\\\"ok\\\\\":false}\");\n}`;\n\n/**\n * Delete a room: the WebUI's generic delete (eq-3/occu\n * `WebUI/www/rega/esp/system.fn` `::DeleteObject`, refused for an\n * `Unerasable()` object), only when `##id##` is a member of `ID_ROOMS`.\n * Emits `{\"ok\":true}` or `{\"ok\":false,\"reason\":\"room\"|\"unerasable\"}`.\n */\nexport const DELETE_ROOM = `! nodehomematic:deleteRoom\nstring sRoomId = \"##id##\";\nstring sId;\nboolean bFound = false;\nforeach(sId, dom.GetObject(ID_ROOMS).EnumUsedIDs()) {\n    if (sId == sRoomId) {\n        bFound = true;\n    }\n}\nif (bFound) {\n    object oRoom = dom.GetObject(sRoomId);\n    if (oRoom.Unerasable()) {\n        Write(\"{\\\\\"ok\\\\\":false,\\\\\"reason\\\\\":\\\\\"unerasable\\\\\"}\");\n    } else {\n        dom.DeleteObject(oRoom.ID());\n        Write(\"{\\\\\"ok\\\\\":true}\");\n    }\n} else {\n    Write(\"{\\\\\"ok\\\\\":false,\\\\\"reason\\\\\":\\\\\"room\\\\\"}\");\n}`;\n\n/**\n * Add (`##op##` = `add`) or remove (`remove`) a channel, by address, to/from a\n * room: Room.addChannel / Room.removeChannel (eq-3/occu\n * `WebUI/www/api/methods/room/addchannel.tcl`, `removechannel.tcl`:\n * `room.Add(channelId)` / `room.Remove(channelId)`). Emits `{\"ok\":true}` or\n * `{\"ok\":false,\"reason\":\"room\"|\"channel\"}`.\n */\nexport const ROOM_CHANNEL = `! nodehomematic:roomChannel\nstring sRoomId = \"##id##\";\nstring sAddress = \"##address##\";\nstring sOp = \"##op##\";\nstring sId;\nstring sChnId = \"\";\nboolean bFound = false;\nforeach(sId, dom.GetObject(ID_ROOMS).EnumUsedIDs()) {\n    if (sId == sRoomId) {\n        bFound = true;\n    }\n}\nforeach(sId, dom.GetObject(ID_CHANNELS).EnumUsedIDs()) {\n    object oTmp = dom.GetObject(sId);\n    if (oTmp) {\n        if (oTmp.Address() == sAddress) {\n            sChnId = sId;\n        }\n    }\n}\nif (!bFound) {\n    Write(\"{\\\\\"ok\\\\\":false,\\\\\"reason\\\\\":\\\\\"room\\\\\"}\");\n} else {\n    if (sChnId == \"\") {\n        Write(\"{\\\\\"ok\\\\\":false,\\\\\"reason\\\\\":\\\\\"channel\\\\\"}\");\n    } else {\n        object oRoom = dom.GetObject(sRoomId);\n        if (sOp == \"add\") {\n            oRoom.Add(sChnId);\n        } else {\n            oRoom.Remove(sChnId);\n        }\n        Write(\"{\\\\\"ok\\\\\":true}\");\n    }\n}`;\n","/**\n * Names and rooms of the CCU's ReGa object model, read and written through\n * `ReGa.runScript` (the scripts and their eq-3/occu sources are in\n * `../rega/scripts.ts`). Every input is validated before a script runs; every\n * answer arrives as `unknown` and is narrowed here.\n */\nimport type { HmDeviceRename, HmNamedObject, HmRoom } from '../../api/types.js';\nimport { ClientError, ValidationError } from '../../support/errors.js';\nimport { decodeRegaName } from '../rega/rega-runner.js';\nimport {\n  CREATE_ROOM,\n  DELETE_ROOM,\n  LIST_ROOMS,\n  RENAME_CHANNEL,\n  RENAME_DEVICE,\n  RENAME_ROOM,\n  ROOM_CHANNEL,\n} from '../rega/scripts.js';\n\n/** Runs one ReGa script with `##key##` params; failures name `label`. */\nexport type RegaScriptRunner = (\n  label: string,\n  script: string,\n  params?: Record<string, string | number>,\n) => Promise<unknown>;\n\nconst ROOM_ID = /^\\d+$/;\nconst DEVICE_ADDRESS = /^[0-9A-Za-z_-]+$/;\nconst CHANNEL_ADDRESS = /^[0-9A-Za-z_-]+:\\d+$/;\nconst CONTROL_CHARS = /[\\u0000-\\u001F\\u007F]/;\n/** Longest name accepted; the WebUI's own name fields stop well below this. */\nconst MAX_NAME = 128;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction validName(raw: string, what: string): string {\n  const name = raw.trim();\n  if (name === '' || name.length > MAX_NAME || CONTROL_CHARS.test(name)) {\n    throw new ValidationError(\n      `${what} name must be 1..${MAX_NAME} characters without control characters.`,\n    );\n  }\n  return name;\n}\n\nfunction validRoomId(id: string): string {\n  if (!ROOM_ID.test(id)) throw new ValidationError(`Invalid room id \"${id}\".`);\n  return id;\n}\n\nfunction validChannelAddress(address: string): string {\n  if (!CHANNEL_ADDRESS.test(address)) {\n    throw new ValidationError(`Invalid channel address \"${address}\".`);\n  }\n  return address;\n}\n\nfunction decodedName(value: unknown): string {\n  return typeof value === 'string' ? decodeRegaName(value) : '';\n}\n\nfunction okOf(raw: unknown, label: string): Record<string, unknown> {\n  if (!isRecord(raw)) throw new ClientError(`${label}: unexpected answer from the CCU.`);\n  return raw;\n}\n\nfunction toRoom(entry: Record<string, unknown>): HmRoom | null {\n  const id = entry['id'];\n  if (typeof id !== 'string' && typeof id !== 'number') return null;\n  const channels = Array.isArray(entry['channels'])\n    ? entry['channels'].filter((c): c is string => typeof c === 'string' && c !== '')\n    : [];\n  return { id: String(id), name: decodedName(entry['name']), channels };\n}\n\nexport class CcuTopology {\n  readonly #rega: RegaScriptRunner;\n\n  public constructor(rega: RegaScriptRunner) {\n    this.#rega = rega;\n  }\n\n  /** Rename a device, and with `renameChannels` every channel to `<name>:<index>`. */\n  public async renameDevice(\n    address: string,\n    rawName: string,\n    renameChannels: boolean,\n  ): Promise<HmDeviceRename> {\n    if (!DEVICE_ADDRESS.test(address)) {\n      throw new ValidationError(`Invalid device address \"${address}\".`);\n    }\n    const name = validName(rawName, 'Device');\n    const label = 'ReGa.runScript(renameDevice)';\n    const answer = okOf(\n      await this.#rega(label, RENAME_DEVICE, {\n        address,\n        name,\n        channels: renameChannels ? '1' : '0',\n      }),\n      label,\n    );\n    if (answer['ok'] !== true) throw new ValidationError(`Unknown device \"${address}\".`);\n    const channels: HmNamedObject[] = Array.isArray(answer['channels'])\n      ? answer['channels'].filter(isRecord).flatMap((entry) => {\n          const channelAddress = entry['address'];\n          return typeof channelAddress === 'string' && channelAddress !== ''\n            ? [{ address: channelAddress, name: decodedName(entry['name']) }]\n            : [];\n        })\n      : [];\n    return { device: { address, name: decodedName(answer['name']) }, channels };\n  }\n\n  /** Rename one channel; resolves with the name the CCU stored. */\n  public async renameChannel(address: string, rawName: string): Promise<HmNamedObject> {\n    validChannelAddress(address);\n    const name = validName(rawName, 'Channel');\n    const label = 'ReGa.runScript(renameChannel)';\n    const answer = okOf(await this.#rega(label, RENAME_CHANNEL, { address, name }), label);\n    if (answer['ok'] !== true) throw new ValidationError(`Unknown channel \"${address}\".`);\n    return { address, name: decodedName(answer['name']) };\n  }\n\n  /** Every room with its member channel addresses. */\n  public async rooms(): Promise<HmRoom[]> {\n    const raw = await this.#rega('ReGa.runScript(listRooms)', LIST_ROOMS);\n    if (!Array.isArray(raw)) return [];\n    return raw.filter(isRecord).flatMap((entry) => {\n      const room = toRoom(entry);\n      return room === null ? [] : [room];\n    });\n  }\n\n  /** Create an empty room; a room of the same name is a {@link ValidationError}. */\n  public async createRoom(rawName: string): Promise<HmRoom> {\n    const name = validName(rawName, 'Room');\n    const label = 'ReGa.runScript(createRoom)';\n    const answer = okOf(await this.#rega(label, CREATE_ROOM, { name }), label);\n    if (answer['error'] === 'exists') {\n      throw new ValidationError(`A room named \"${name}\" already exists.`);\n    }\n    const room = toRoom({ ...answer, channels: [] });\n    if (room === null) throw new ClientError(`${label}: the CCU did not create the room.`);\n    return room;\n  }\n\n  /** Rename a room by id. */\n  public async renameRoom(id: string, rawName: string): Promise<void> {\n    const name = validName(rawName, 'Room');\n    const label = 'ReGa.runScript(renameRoom)';\n    const answer = okOf(await this.#rega(label, RENAME_ROOM, { id: validRoomId(id), name }), label);\n    if (answer['ok'] !== true) throw new ValidationError(`Unknown room \"${id}\".`);\n  }\n\n  /** Delete a room by id; an unerasable room is a {@link ValidationError}. */\n  public async deleteRoom(id: string): Promise<void> {\n    const label = 'ReGa.runScript(deleteRoom)';\n    const answer = okOf(await this.#rega(label, DELETE_ROOM, { id: validRoomId(id) }), label);\n    if (answer['ok'] === true) return;\n    throw new ValidationError(\n      answer['reason'] === 'unerasable'\n        ? `Room \"${id}\" cannot be deleted (the CCU marks it unerasable).`\n        : `Unknown room \"${id}\".`,\n    );\n  }\n\n  /** Add a channel (by address) to a room. */\n  public async addChannelToRoom(id: string, channelAddress: string): Promise<void> {\n    await this.#roomChannel(id, channelAddress, 'add');\n  }\n\n  /** Remove a channel (by address) from a room. */\n  public async removeChannelFromRoom(id: string, channelAddress: string): Promise<void> {\n    await this.#roomChannel(id, channelAddress, 'remove');\n  }\n\n  async #roomChannel(id: string, channelAddress: string, op: 'add' | 'remove'): Promise<void> {\n    const label = `ReGa.runScript(roomChannel ${op})`;\n    const answer = okOf(\n      await this.#rega(label, ROOM_CHANNEL, {\n        id: validRoomId(id),\n        address: validChannelAddress(channelAddress),\n        op,\n      }),\n      label,\n    );\n    if (answer['ok'] === true) return;\n    throw new ValidationError(\n      answer['reason'] === 'channel'\n        ? `Unknown channel \"${channelAddress}\".`\n        : `Unknown room \"${id}\".`,\n    );\n  }\n}\n","/**\n * ReGa scripts for the CCU program that makes a device send key presses.\n *\n * A HmIP device sends `PRESS_SHORT` / `PRESS_LONG` to the access point only\n * while the CCU USES the key: a program whose condition references the key's\n * data point. A central link (`reportValueUsage`) alone is not enough. The\n * program built here has one rule, one condition (OR) and one single condition\n * per `<interface>.<channel>.<PARAM>` data point, triggered on update, with no\n * destination.\n *\n * Sources for every call below:\n * - eq-3/occu `WebUI/bin/hm_autoconf` (programs built from script):\n *   `dom.CreateObject(OT_PROGRAM)`, `ID_PROGRAMS.Add(id)`, `prg.Rule()`,\n *   `rule.RuleOperatorType(2)`, `rule.RuleAddCondition()`,\n *   `cond.CndOperatorType(2)`, `cond.CndAddSingle()`, `OperatorType(1)`,\n *   `ConditionType2(13)` (the WebUI's DP_VALUE_CHECK_UPDATE, `rega/esp/sico.fn`\n *   `SetConditionType2`), `LeftValType(ivtObjectId)`, `LeftVal(dpId)`,\n *   `ConditionChannel(chId)`, `prg.Internal(..)`, `prg.Active(true)`,\n *   `dom.RTUpdate(0)`.\n * - eq-3/occu `WebUI/www/rega/esp/sico.fn` `SetChannel`: a channel condition is\n *   `LeftValType(ivtObjectId)`, `LeftVal(dp)`, `ConditionChannel(ch)`,\n *   `ConditionType(1)`.\n * - eq-3/occu `WebUI/www/rega/esp/programs.fn`: `DeleteCondition` /\n *   `DeleteSingleCondition` (`RuleDelCondition(condId)`), `RuleCondition(0)`,\n *   `CndSingleCount()`, `CndSingleCondition(i)`, `DeleteProgram`\n *   (`dom.DeleteObject(id)`), `AddCondition` (operator pairing).\n *\n * The scripts are built, not constants, because the data point list varies;\n * every data point name is validated against {@link DATAPOINT_NAME} first, so\n * nothing but `[0-9A-Za-z_:.-]` reaches the script text. The program name goes\n * through the runner's `##name##` placeholder (escaped there). A program id\n * passed to {@link buildDeleteProgram} is digits only, checked before it is\n * inlined.\n *\n * Name lookup counts every program with that name (`ID_PROGRAMS.EnumUsedIDs()`,\n * the enumeration the WebUI uses to list programs). One match or none behaves\n * as before. More than one match writes nothing and answers\n * `{\"error\":\"duplicate\",\"ids\":[\"<id>\",...]}`.\n */\nimport { ValidationError } from '../../support/errors.js';\n\n/** `<interface>.<device>:<channel>.<PARAM>`, the ReGa name of a key data point. */\nexport const DATAPOINT_NAME = /^[0-9A-Za-z_-]+\\.[0-9A-Za-z_-]+:\\d+\\.PRESS_(?:SHORT|LONG)$/;\n\nfunction checkedDatapoints(datapoints: readonly string[]): readonly string[] {\n  if (datapoints.length === 0) {\n    throw new ValidationError('A key event program needs at least one data point.');\n  }\n  for (const name of datapoints) {\n    if (!DATAPOINT_NAME.test(name)) {\n      throw new ValidationError(`Invalid key data point \"${name}\".`);\n    }\n  }\n  return datapoints;\n}\n\n/**\n * Find every program named `##name##`. `iMatches` is the count, `sIds` a JSON\n * array of those ids, and `oProg` the single match (unset when there is none).\n * A duplicate still assigns `oProg`, but callers must not use it when\n * `iMatches` is greater than 1.\n */\nconst FIND_PROGRAM = `string sName = \"##name##\";\nobject oPrograms = dom.GetObject(ID_PROGRAMS);\nobject oProg;\nstring sPid;\nstring sIds = \"\";\nstring sIdSep = \"\";\ninteger iMatches = 0;\nforeach(sPid, oPrograms.EnumUsedIDs()) {\n    object oCand = dom.GetObject(sPid);\n    if (oCand) {\n        if (oCand.Name() == sName) {\n            oProg = oCand;\n            sIds = sIds # sIdSep # \"\\\\\"\" # sPid # \"\\\\\"\";\n            sIdSep = \",\";\n            iMatches = iMatches + 1;\n        }\n    }\n}`;\n\n/** Answer a duplicate name and skip the caller's body. The body is the `else`. */\nconst UNLESS_DUPLICATE = `if (iMatches > 1) {\n    Write(\"{\\\\\"error\\\\\":\\\\\"duplicate\\\\\",\\\\\"ids\\\\\":[\" # sIds # \"]}\");\n} else {`;\n\n/**\n * Create or rewrite the program `##name##` so its conditions are exactly the\n * given data points. Emits `{\"programId\":\"<id>\",\"created\":true|false}`,\n * `{\"error\":\"datapoint\",\"missing\":[\"<dp>\",...]}` or\n * `{\"error\":\"duplicate\",\"ids\":[...]}`. A duplicate or a missing data point\n * writes nothing.\n */\nexport function buildEnsureKeyEventProgram(datapoints: readonly string[]): string {\n  const dps = checkedDatapoints(datapoints);\n  const lookups = dps\n    .map(\n      (dp, i) => `object oDp${i} = dom.GetObject(\"${dp}\");\nif (!oDp${i}) {\n    sMissing = sMissing # sMissSep # \"\\\\\"${dp}\\\\\"\";\n    sMissSep = \",\";\n}`,\n    )\n    .join('\\n');\n  const singles = dps\n    .map(\n      (_dp, i) => `oSc = oCnd.CndAddSingle();\noSc.OperatorType(1);\noSc.ConditionType(1);\noSc.ConditionType2(13);\noSc.LeftValType(ivtObjectId);\noSc.LeftVal(oDp${i}.ID());\noSc.ConditionChannel(oDp${i}.Channel());`,\n    )\n    .join('\\n');\n  return `! nodehomematic:ensureKeyEventProgram\n${FIND_PROGRAM}\n${UNLESS_DUPLICATE}\nstring sMissing = \"\";\nstring sMissSep = \"\";\n${lookups}\nif (sMissing != \"\") {\n    Write(\"{\\\\\"error\\\\\":\\\\\"datapoint\\\\\",\\\\\"missing\\\\\":[\" # sMissing # \"]}\");\n} else {\n    boolean bCreated = false;\n    if (!oProg) {\n        oProg = dom.CreateObject(OT_PROGRAM);\n        oProg.Name(sName);\n        oPrograms.Add(oProg.ID());\n        bCreated = true;\n    }\n    object oRule = oProg.Rule();\n    oRule.RuleOperatorType(2);\n    integer iCnt = oRule.RuleConditions().Count();\n    while (iCnt > 0) {\n        object oOld = oRule.RuleCondition(0);\n        oRule.RuleDelCondition(oOld.ID());\n        iCnt = iCnt - 1;\n    }\n    object oCnd = oRule.RuleAddCondition();\n    oCnd.CndOperatorType(2);\n    object oSc;\n${singles}\n    oProg.Internal(false);\n    oProg.Active(true);\n    dom.RTUpdate(0);\n    Write(\"{\\\\\"programId\\\\\":\\\\\"\");\n    Write(oProg.ID());\n    Write(\"\\\\\",\\\\\"created\\\\\":\");\n    if (bCreated) {\n        Write(\"true\");\n    } else {\n        Write(\"false\");\n    }\n    Write(\"}\");\n}\n}`;\n}\n\n/**\n * Delete the program `##name##`. Emits `{\"removed\":true|false}`; `false` when\n * no such program exists. A duplicate name emits\n * `{\"error\":\"duplicate\",\"ids\":[...]}` and deletes nothing. `dom.DeleteObject`\n * is the WebUI's own delete (`programs.fn` `DeleteProgram`).\n */\nexport const REMOVE_KEY_EVENT_PROGRAM = `! nodehomematic:removeKeyEventProgram\n${FIND_PROGRAM}\n${UNLESS_DUPLICATE}\n    if (oProg) {\n        dom.DeleteObject(oProg.ID());\n        Write(\"{\\\\\"removed\\\\\":true}\");\n    } else {\n        Write(\"{\\\\\"removed\\\\\":false}\");\n    }\n}`;\n\n/**\n * Read the program `##name##`: `{\"found\":false}` or\n * `{\"found\":true,\"programId\":\"<id>\",\"datapoints\":[\"<dp name>\",...]}` from the\n * first condition's single conditions (`LeftVal` data point names). A duplicate\n * name answers `{\"error\":\"duplicate\",\"ids\":[...]}` and reads no conditions.\n */\nexport const GET_KEY_EVENT_PROGRAM = `! nodehomematic:getKeyEventProgram\n${FIND_PROGRAM}\n${UNLESS_DUPLICATE}\nif (!oProg) {\n    Write(\"{\\\\\"found\\\\\":false}\");\n} else {\n    Write(\"{\\\\\"found\\\\\":true,\\\\\"programId\\\\\":\\\\\"\");\n    Write(oProg.ID());\n    Write(\"\\\\\",\\\\\"datapoints\\\\\":[\");\n    object oCnd = oProg.Rule().RuleCondition(0);\n    if (oCnd) {\n        integer iN = oCnd.CndSingleCount();\n        integer iI = 0;\n        string sSep = \"\";\n        while (iI < iN) {\n            object oSc = oCnd.CndSingleCondition(iI);\n            object oDp = dom.GetObject(oSc.LeftVal());\n            if (oDp) {\n                Write(sSep);\n                Write(\"\\\\\"\");\n                Write(oDp.Name());\n                Write(\"\\\\\"\");\n                sSep = \",\";\n            }\n            iI = iI + 1;\n        }\n    }\n    Write(\"]}\");\n}\n}`;\n\n/** Digits only: a program id is inlined into the script, so nothing else may reach it. */\nconst PROGRAM_ID = /^\\d+$/;\n\n/**\n * Delete the program `programId`. Emits `{\"removed\":true}` only when the id is\n * a member of `ID_PROGRAMS` (`EnumUsedIDs()`, the same enumeration the WebUI\n * uses to list programs — a channel, a room or any other object is not in that\n * set, so it is never deleted). `dom.GetObject` then `dom.DeleteObject` is\n * eq-3/occu `WebUI/www/rega/esp/programs.fn` `DeleteProgram`. Anything else\n * emits `{\"removed\":false}`.\n */\nexport function buildDeleteProgram(programId: string): string {\n  if (!PROGRAM_ID.test(programId)) {\n    throw new ValidationError(`Invalid program id \"${programId}\".`);\n  }\n  return `! nodehomematic:deleteProgram\nstring sId = \"${programId}\";\nstring sPid;\nboolean bProgram = false;\nforeach(sPid, dom.GetObject(ID_PROGRAMS).EnumUsedIDs()) {\n    if (sPid == sId) {\n        bProgram = true;\n    }\n}\nif (bProgram) {\n    object oProg = dom.GetObject(sId);\n    if (oProg) {\n        dom.DeleteObject(oProg.ID());\n        Write(\"{\\\\\"removed\\\\\":true}\");\n    } else {\n        Write(\"{\\\\\"removed\\\\\":false}\");\n    }\n} else {\n    Write(\"{\\\\\"removed\\\\\":false}\");\n}`;\n}\n","/**\n * The CCU program that makes a HmIP device send key presses to the access\n * point (see `../rega/key-event-program.ts`), over `ReGa.runScript`. Inputs are\n * validated before a script runs; every answer arrives as `unknown` and is\n * narrowed here.\n */\nimport { Interface } from '../../support/constants.js';\nimport { ClientError, ValidationError } from '../../support/errors.js';\nimport {\n  GET_KEY_EVENT_PROGRAM,\n  REMOVE_KEY_EVENT_PROGRAM,\n  buildDeleteProgram,\n  buildEnsureKeyEventProgram,\n} from '../rega/key-event-program.js';\nimport type {\n  HmKeyEventParameter,\n  HmKeyEventProgram,\n  HmKeyEventProgramInput,\n  HmKeyEventProgramResult,\n} from '../../api/types.js';\nimport type { RegaScriptRunner } from './ccu-topology.js';\n\nconst CHANNEL_ADDRESS = /^[0-9A-Za-z_-]+:\\d+$/;\nconst CONTROL_CHARS = /[\\u0000-\\u001F\\u007F]/;\nconst MAX_NAME = 128;\nconst DEFAULT_PARAMETERS: readonly HmKeyEventParameter[] = ['PRESS_SHORT', 'PRESS_LONG'];\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction record(raw: unknown, label: string): Record<string, unknown> {\n  if (!isRecord(raw)) throw new ClientError(`${label}: unexpected answer from the CCU.`);\n  return raw;\n}\n\nfunction throwIfDuplicate(answer: Record<string, unknown>, name: string): void {\n  if (answer['error'] !== 'duplicate') return;\n  const raw = answer['ids'];\n  const ids = Array.isArray(raw)\n    ? raw.filter((id): id is string => typeof id === 'string' && id !== '')\n    : [];\n  const listed = ids.length > 0 ? ids.join(', ') : '?';\n  throw new ValidationError(\n    `More than one program is named \"${name}\" (ids ${listed}). deleteProgram(id) deletes one of them.`,\n  );\n}\n\nfunction validName(raw: string): string {\n  const name = raw.trim();\n  if (name === '' || name.length > MAX_NAME || CONTROL_CHARS.test(name)) {\n    throw new ValidationError(\n      `Program name must be 1..${MAX_NAME} characters without control characters.`,\n    );\n  }\n  return name;\n}\n\n/** The CCU interface name (`HmIP-RF`) a library interface id (`<central>-HmIP-RF`) ends with. */\nexport function interfaceNameOf(interfaceId: string): string {\n  const match = (Object.values(Interface) as string[]).find((name) =>\n    interfaceId.endsWith(`-${name}`),\n  );\n  if (match === undefined) {\n    throw new ValidationError(`Cannot derive the CCU interface from \"${interfaceId}\".`);\n  }\n  return match;\n}\n\nexport class CcuKeyPrograms {\n  readonly #rega: RegaScriptRunner;\n\n  public constructor(rega: RegaScriptRunner) {\n    this.#rega = rega;\n  }\n\n  /**\n   * Create or rewrite the program so its conditions are exactly\n   * `channelAddresses` x `parameters`. `interfaceName` is the CCU interface the\n   * channels live on (`HmIP-RF`).\n   */\n  public async ensure(\n    interfaceName: string,\n    input: HmKeyEventProgramInput,\n  ): Promise<HmKeyEventProgramResult> {\n    const name = validName(input.name);\n    const parameters = input.parameters ?? DEFAULT_PARAMETERS;\n    if (parameters.length === 0) throw new ValidationError('At least one key parameter is needed.');\n    const datapoints = input.channelAddresses.flatMap((address) => {\n      if (!CHANNEL_ADDRESS.test(address)) {\n        throw new ValidationError(`Invalid channel address \"${address}\".`);\n      }\n      return parameters.map((param) => `${interfaceName}.${address}.${param}`);\n    });\n    const label = 'ReGa.runScript(ensureKeyEventProgram)';\n    const answer = record(\n      await this.#rega(label, buildEnsureKeyEventProgram(datapoints), { name }),\n      label,\n    );\n    throwIfDuplicate(answer, name);\n    if (answer['error'] === 'datapoint') {\n      const missing = Array.isArray(answer['missing']) ? answer['missing'].join(', ') : '?';\n      throw new ValidationError(`The CCU has no such key data point: ${missing}.`);\n    }\n    const programId = answer['programId'];\n    const created = answer['created'];\n    if (typeof programId !== 'string' || programId === '' || typeof created !== 'boolean') {\n      throw new ClientError(`${label}: the CCU did not return the program.`);\n    }\n    return { programId, created };\n  }\n\n  /**\n   * Delete the program `programId` (digits only). `removed: false` when the id\n   * is missing or is not a program; nothing is deleted in that case.\n   */\n  public async delete(programId: string): Promise<{ removed: boolean }> {\n    const script = buildDeleteProgram(programId);\n    const label = 'ReGa.runScript(deleteProgram)';\n    const answer = record(await this.#rega(label, script), label);\n    if (typeof answer['removed'] !== 'boolean') {\n      throw new ClientError(`${label}: unexpected answer from the CCU.`);\n    }\n    return { removed: answer['removed'] };\n  }\n\n  /** Delete the program by name; `removed: false` when it does not exist. */\n  public async remove(rawName: string): Promise<{ removed: boolean }> {\n    const name = validName(rawName);\n    const label = 'ReGa.runScript(removeKeyEventProgram)';\n    const answer = record(await this.#rega(label, REMOVE_KEY_EVENT_PROGRAM, { name }), label);\n    throwIfDuplicate(answer, name);\n    if (typeof answer['removed'] !== 'boolean') {\n      throw new ClientError(`${label}: unexpected answer from the CCU.`);\n    }\n    return { removed: answer['removed'] };\n  }\n\n  /** The program and the channels it listens to, or `null` when absent. */\n  public async get(rawName: string): Promise<HmKeyEventProgram | null> {\n    const name = validName(rawName);\n    const label = 'ReGa.runScript(getKeyEventProgram)';\n    const answer = record(await this.#rega(label, GET_KEY_EVENT_PROGRAM, { name }), label);\n    throwIfDuplicate(answer, name);\n    if (answer['found'] !== true) return null;\n    const programId = answer['programId'];\n    if (typeof programId !== 'string' || programId === '') {\n      throw new ClientError(`${label}: the CCU did not return the program id.`);\n    }\n    const datapoints = Array.isArray(answer['datapoints']) ? answer['datapoints'] : [];\n    const channels = new Set<string>();\n    for (const dp of datapoints) {\n      if (typeof dp !== 'string') continue;\n      const match = /\\.([0-9A-Za-z_-]+:\\d+)\\.PRESS_(?:SHORT|LONG)$/.exec(dp);\n      if (match?.[1] !== undefined) channels.add(match[1]);\n    }\n    return { programId, channelAddresses: [...channels] };\n  }\n}\n","/**\n * ReGa script that reads (never writes) what the CCU knows about a device's\n * key channels, to answer \"does the CCU itself register the key press?\".\n *\n * For every given key channel it reads the channel object and its\n * `PRESS_SHORT` / `PRESS_LONG` / `PRESS_LONG_RELEASE` data points, and it lists\n * every program whose condition references one of those data points.\n *\n * Sources for every call below (eq-3/occu, `WebUI`):\n * - Channel lookup by address: enumerate `ID_CHANNELS` (`EnumUsedIDs()`) and\n *   compare `Address()` (the same idiom as `getregaidbyaddress.tcl`, used by\n *   `RENAME_DEVICE` in `scripts.ts`). `ID()`, `Name()`.\n * - Channel flags: `Visible()` (`www/rega/esp/channels.fn` `setVisible`),\n *   `ReadyConfig()` (`channels.fn` `setReadyConfig`: `chn.ReadyConfig()`),\n *   (`Enabled()` is NOT read: occu only ever sets it, and one unknown method\n *   aborts the whole ReGa script; the field is always `null`),\n *   `LastDPActionTimeSeconds()` (`www/rega/esp/system.fn`, the \"last action\"\n *   dialog: `obj.LastDPActionTime()` / `LastDPActionTimeSeconds()` for an\n *   `OT_CHANNEL`).\n * - Data point by name `<interface>.<address>.<PARAM>`: `dom.GetObject(name)`;\n *   `Value()`; `Timestamp()` / `TimestampSeconds()` (`system.fn`, same dialog\n *   for an `OT_DP`: the time of the last update, even when the value did not\n *   change). `LastTimestamp()` is NOT read: occu only tests it for truth and\n *   no source converts it to a time; `lastTimestamp` is always `null`.\n * - Programs: `EnumUsedIDs()` of `ID_PROGRAMS`, `Active()` (`system.fn`\n *   `objProg.Active()`), `ProgramLastExecuteTime()` /\n *   `ProgramLastExecuteTimeSeconds()` (`system.fn`, the \"last action\" dialog\n *   for an `OT_PROGRAM`). `Internal()` is NOT read on a program (occu never\n *   reads it there); `internal` is always `null`.\n * - Conditions: `Rule()`, `RuleConditions().Count()`, `RuleCondition(i)`,\n *   `CndSingleCount()`, `CndSingleCondition(i)`, `LeftVal()` (`programs.fn`\n *   and the read script in `key-event-program.ts`). Only single conditions of\n *   a rule's conditions are scanned; a program whose reference sits in a\n *   deeper structure is not listed.\n *\n * Every value is written as a quoted string (a ReGa boolean concatenated with\n * `#` is `true` / `false`, as `system.fn` writes `objProg.Active()` into text)\n * and a name goes through `UriEncode()`, decoded by `decodeRegaName`. The\n * script is built, not constant, because the channel list varies; addresses\n * and the interface name are validated before they reach the script text.\n */\nimport { ValidationError } from '../../support/errors.js';\n\nconst CHANNEL_ADDRESS = /^([0-9A-Za-z_-]+):\\d+$/;\nconst INTERFACE_NAME = /^[0-9A-Za-z_-]+$/;\n\n/** The key parameters whose ReGa data points are read. */\nexport const KEY_DIAGNOSIS_PARAMETERS: readonly string[] = [\n  'PRESS_SHORT',\n  'PRESS_LONG',\n  'PRESS_LONG_RELEASE',\n];\n\n/** The ReGa name of a key data point. */\nexport function keyDatapointName(\n  interfaceName: string,\n  channelAddress: string,\n  parameter: string,\n): string {\n  return `${interfaceName}.${channelAddress}.${parameter}`;\n}\n\n/**\n * The scan of `ID_PROGRAMS` against `sTargets` (a `|`-delimited name list the\n * caller declared): writes one `{\"id\",\"name\",\"active\",...,\"datapoints\":[...]}`\n * object per program whose single conditions reference a target. Shared by the\n * per-device diagnosis and the cluster-wide key program read.\n */\nconst PROGRAM_SCAN = `string sPrgId;\nstring sPSep = \"\";\nforeach(sPrgId, dom.GetObject(ID_PROGRAMS).EnumUsedIDs()) {\n    object oPrg = dom.GetObject(sPrgId);\n    if (oPrg) {\n        string sRefs = \"\";\n        string sRSep = \"\";\n        object oRule = oPrg.Rule();\n        if (oRule) {\n            integer iC = 0;\n            integer iCn = oRule.RuleConditions().Count();\n            while (iC < iCn) {\n                object oCnd = oRule.RuleCondition(iC);\n                if (oCnd) {\n                    integer iN = oCnd.CndSingleCount();\n                    integer iI = 0;\n                    while (iI < iN) {\n                        object oSc = oCnd.CndSingleCondition(iI);\n                        object oLeft = dom.GetObject(oSc.LeftVal());\n                        if (oLeft) {\n                            string sLn = oLeft.Name();\n                            if (sTargets.Find(\"|\" # sLn # \"|\") != -1) {\n                                sRefs = sRefs # sRSep # \"\\\\\"\" # sLn # \"\\\\\"\";\n                                sRSep = \",\";\n                            }\n                        }\n                        iI = iI + 1;\n                    }\n                }\n                iC = iC + 1;\n            }\n        }\n        if (sRefs != \"\") {\n            Write(sPSep);\n            sPSep = \",\";\n            Write(\"{\\\\\"id\\\\\":\\\\\"\" # oPrg.ID() # \"\\\\\",\\\\\"name\\\\\":\\\\\"\" # oPrg.Name().UriEncode() # \"\\\\\",\\\\\"active\\\\\":\\\\\"\" # oPrg.Active() # \"\\\\\",\\\\\"internal\\\\\":\\\\\"\" # \"\" # \"\\\\\",\\\\\"lastExecuteSeconds\\\\\":\\\\\"\" # oPrg.ProgramLastExecuteTimeSeconds() # \"\\\\\",\\\\\"datapoints\\\\\":[\" # sRefs # \"]}\");\n        }\n    }\n}\n`;\n\nfunction checkedInput(\n  interfaceName: string,\n  channelAddresses: readonly string[],\n): readonly string[] {\n  if (!INTERFACE_NAME.test(interfaceName)) {\n    throw new ValidationError(`Invalid interface name \"${interfaceName}\".`);\n  }\n  for (const address of channelAddresses) {\n    if (!CHANNEL_ADDRESS.test(address)) {\n      throw new ValidationError(`Invalid channel address \"${address}\".`);\n    }\n  }\n  return channelAddresses;\n}\n\nfunction channelBlock(interfaceName: string, address: string, i: number): string {\n  const dps = KEY_DIAGNOSIS_PARAMETERS.map((parameter) => {\n    const name = keyDatapointName(interfaceName, address, parameter);\n    return `oDp = dom.GetObject(\"${name}\");\nWrite(sDpSep);\nsDpSep = \",\";\nWrite(\"{\\\\\"name\\\\\":\\\\\"${name}\\\\\"\");\nif (oDp) {\n    Write(\",\\\\\"exists\\\\\":true,\\\\\"id\\\\\":\\\\\"\" # oDp.ID() # \"\\\\\",\\\\\"value\\\\\":\\\\\"\" # (\"\" # oDp.Value()).UriEncode() # \"\\\\\",\\\\\"timestampSeconds\\\\\":\\\\\"\" # oDp.TimestampSeconds() # \"\\\\\",\\\\\"lastTimestampSeconds\\\\\":\\\\\"\" # \"\" # \"\\\\\"}\");\n} else {\n    Write(\",\\\\\"exists\\\\\":false}\");\n}`;\n  }).join('\\n');\n  return `Write(sSep);\nsSep = \",\";\nWrite(\"{\\\\\"address\\\\\":\\\\\"${address}\\\\\",\");\nif (sChId${i} == \"\") {\n    Write(\"\\\\\"found\\\\\":false,\");\n} else {\n    object oChn${i} = dom.GetObject(sChId${i});\n    Write(\"\\\\\"found\\\\\":true,\\\\\"id\\\\\":\\\\\"\" # oChn${i}.ID() # \"\\\\\",\\\\\"name\\\\\":\\\\\"\" # oChn${i}.Name().UriEncode() # \"\\\\\",\\\\\"visible\\\\\":\\\\\"\" # oChn${i}.Visible() # \"\\\\\",\\\\\"enabled\\\\\":\\\\\"\" # \"\" # \"\\\\\",\\\\\"readyConfig\\\\\":\\\\\"\" # oChn${i}.ReadyConfig() # \"\\\\\",\\\\\"lastActionSeconds\\\\\":\\\\\"\" # oChn${i}.LastDPActionTimeSeconds() # \"\\\\\",\");\n}\nWrite(\"\\\\\"datapoints\\\\\":[\");\nsDpSep = \"\";\n${dps}\nWrite(\"]}\");`;\n}\n\n/**\n * Read the key channels `channelAddresses` (all on `interfaceName`) and the\n * programs that reference their key data points. Emits\n * `{\"channels\":[{\"address\",\"found\",\"id\",\"name\":<enc>,\"visible\",\"enabled\",\n * \"readyConfig\",\"lastActionSeconds\",\"datapoints\":[{\"name\",\"exists\",\"id\",\n * \"value\":<enc>,\"timestampSeconds\",\"lastTimestampSeconds\"}]}],\n * \"programs\":[{\"id\",\"name\":<enc>,\"active\",\"internal\",\"lastExecuteSeconds\",\n * \"datapoints\":[\"<dp name>\"]}]}`; every value but `exists` / `found` is a string.\n */\nexport function buildDiagnoseKeyEvents(\n  interfaceName: string,\n  channelAddresses: readonly string[],\n): string {\n  const addresses = checkedInput(interfaceName, channelAddresses);\n  const lookups = addresses.map((_a, i) => `string sChId${i} = \"\";`).join('\\n');\n  const matches = addresses\n    .map(\n      (address, i) => `if (oTmp.Address() == \"${address}\") {\n            sChId${i} = sId;\n        }`,\n    )\n    .join('\\n        ');\n  const targets = addresses\n    .flatMap((address) =>\n      KEY_DIAGNOSIS_PARAMETERS.map(\n        (parameter) =>\n          `sTargets = sTargets # \"${keyDatapointName(interfaceName, address, parameter)}|\";`,\n      ),\n    )\n    .join('\\n');\n  const blocks = addresses.map((address, i) => channelBlock(interfaceName, address, i)).join('\\n');\n  return `! nodehomematic:diagnoseKeyEvents\nstring sId;\nstring sSep = \"\";\nstring sDpSep = \"\";\nstring sTargets = \"|\";\nobject oDp;\n${lookups}\n${targets}\nforeach(sId, dom.GetObject(ID_CHANNELS).EnumUsedIDs()) {\n    object oTmp = dom.GetObject(sId);\n    if (oTmp) {\n        ${matches}\n    }\n}\nWrite(\"{\\\\\"channels\\\\\":[\");\n${blocks}\nWrite(\"],\\\\\"programs\\\\\":[\");\n${PROGRAM_SCAN}\nWrite(\"]}\");`;\n}\n\n/** Key data points per script run; keeps `sTargets` and the script bounded. */\nexport const KEY_PROGRAM_CHUNK = 100;\n\n/**\n * Read which programs reference the key data points of `channels` (each\n * `{ interfaceName, address }`), in one scan of `ID_PROGRAMS`. Emits\n * `{\"programs\":[{\"id\",\"name\":<enc>,\"active\",\"internal\",\"lastExecuteSeconds\",\n * \"datapoints\":[\"<dp name>\"]}]}`.\n */\nexport function buildKeyProgramReferences(\n  channels: readonly { readonly interfaceName: string; readonly address: string }[],\n): string {\n  const targets = channels\n    .flatMap((channel) => {\n      checkedInput(channel.interfaceName, [channel.address]);\n      return KEY_DIAGNOSIS_PARAMETERS.map(\n        (parameter) =>\n          `sTargets = sTargets # \"${keyDatapointName(channel.interfaceName, channel.address, parameter)}|\";`,\n      );\n    })\n    .join('\\n');\n  return `! nodehomematic:keyProgramReferences\nstring sTargets = \"|\";\n${targets}\nWrite(\"{\\\\\"programs\\\\\":[\");\n${PROGRAM_SCAN}\nWrite(\"]}\");`;\n}\n","/**\n * Read-only ReGa side of the key event diagnosis (see\n * `../rega/key-diagnosis.ts`), over `ReGa.runScript`. The answer arrives as\n * `unknown` and is narrowed here; a field the CCU left empty is `null`.\n */\nimport { ClientError, ValidationError } from '../../support/errors.js';\nimport {\n  KEY_PROGRAM_CHUNK,\n  buildDiagnoseKeyEvents,\n  buildKeyProgramReferences,\n} from '../rega/key-diagnosis.js';\nimport { decodeRegaName } from '../rega/rega-runner.js';\nimport type {\n  HmKeyProgramReference,\n  HmKeyRegaChannel,\n  HmKeyRegaDatapoint,\n  HmKeyRegaProgram,\n  HmKeyRegaState,\n} from '../../api/types.js';\nimport type { RegaScriptRunner } from './ccu-topology.js';\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction records(value: unknown): Record<string, unknown>[] {\n  return Array.isArray(value) ? value.filter(isRecord) : [];\n}\n\n/** A non-empty string field, else `null`. */\nfunction str(entry: Record<string, unknown>, key: string): string | null {\n  const value = entry[key];\n  return typeof value === 'string' && value !== '' ? value : null;\n}\n\n/** A name field: `UriEncode`d by the script. */\nfunction name(entry: Record<string, unknown>, key: string): string | null {\n  const value = str(entry, key);\n  return value === null ? null : decodeRegaName(value);\n}\n\n/** ReGa prints a boolean as `true` / `false`; anything else (empty included) is unknown. */\nfunction bool(entry: Record<string, unknown>, key: string): boolean | null {\n  const value = str(entry, key);\n  if (value === 'true' || value === '1') return true;\n  if (value === 'false' || value === '0') return false;\n  return null;\n}\n\n/** ReGa epoch seconds as epoch ms; `0` / empty / non-numeric is `null` (never happened). */\nfunction epochMs(entry: Record<string, unknown>, key: string): number | null {\n  const value = str(entry, key);\n  if (value === null) return null;\n  const seconds = Number(value);\n  return Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : null;\n}\n\nfunction datapoint(entry: Record<string, unknown>): HmKeyRegaDatapoint | null {\n  const dpName = str(entry, 'name');\n  if (dpName === null) return null;\n  if (entry['exists'] !== true) {\n    return {\n      name: dpName,\n      exists: false,\n      id: null,\n      value: null,\n      timestamp: null,\n      lastTimestamp: null,\n    };\n  }\n  return {\n    name: dpName,\n    exists: true,\n    id: str(entry, 'id'),\n    value: name(entry, 'value'),\n    timestamp: epochMs(entry, 'timestampSeconds'),\n    lastTimestamp: epochMs(entry, 'lastTimestampSeconds'),\n  };\n}\n\nfunction channel(entry: Record<string, unknown>): HmKeyRegaChannel | null {\n  const address = str(entry, 'address');\n  if (address === null) return null;\n  const datapoints = records(entry['datapoints']).flatMap((dp) => {\n    const parsed = datapoint(dp);\n    return parsed === null ? [] : [parsed];\n  });\n  const found = entry['found'] === true;\n  return {\n    address,\n    found,\n    id: found ? str(entry, 'id') : null,\n    name: found ? name(entry, 'name') : null,\n    visible: found ? bool(entry, 'visible') : null,\n    enabled: found ? bool(entry, 'enabled') : null,\n    readyConfig: found ? bool(entry, 'readyConfig') : null,\n    lastActionAt: found ? epochMs(entry, 'lastActionSeconds') : null,\n    datapoints,\n  };\n}\n\nfunction program(entry: Record<string, unknown>): HmKeyRegaProgram | null {\n  const id = str(entry, 'id');\n  if (id === null) return null;\n  const datapoints = Array.isArray(entry['datapoints'])\n    ? entry['datapoints'].filter((dp): dp is string => typeof dp === 'string')\n    : [];\n  return {\n    id,\n    name: name(entry, 'name') ?? '',\n    active: bool(entry, 'active'),\n    internal: bool(entry, 'internal'),\n    lastExecutedAt: epochMs(entry, 'lastExecuteSeconds'),\n    datapoints,\n  };\n}\n\nexport class CcuKeyDiagnosis {\n  readonly #rega: RegaScriptRunner;\n\n  public constructor(rega: RegaScriptRunner) {\n    this.#rega = rega;\n  }\n\n  /**\n   * Read the ReGa channel objects, key data points and referencing programs\n   * for `channelAddresses` on `interfaceName` (`HmIP-RF`). Writes nothing.\n   */\n  public async read(\n    interfaceName: string,\n    channelAddresses: readonly string[],\n  ): Promise<HmKeyRegaState> {\n    if (channelAddresses.length === 0) {\n      throw new ValidationError('The key diagnosis needs at least one channel.');\n    }\n    const label = 'ReGa.runScript(diagnoseKeyEvents)';\n    const answer = await this.#rega(label, buildDiagnoseKeyEvents(interfaceName, channelAddresses));\n    if (!isRecord(answer)) throw new ClientError(`${label}: unexpected answer from the CCU.`);\n    return {\n      channels: records(answer['channels']).flatMap((entry) => {\n        const parsed = channel(entry);\n        return parsed === null ? [] : [parsed];\n      }),\n      programs: records(answer['programs']).flatMap((entry) => {\n        const parsed = program(entry);\n        return parsed === null ? [] : [parsed];\n      }),\n    };\n  }\n\n  /**\n   * The programs whose conditions reference a key data point of `channels`\n   * (`{ interfaceName, address }`), one ReGa scan per {@link KEY_PROGRAM_CHUNK}\n   * channels. A program seen in several chunks is merged by id. A failed or\n   * unparseable answer throws: the caller must not read it as \"no program\".\n   */\n  public async programReferences(\n    channels: readonly { readonly interfaceName: string; readonly address: string }[],\n  ): Promise<HmKeyProgramReference[]> {\n    const byId = new Map<string, { entry: HmKeyProgramReference; channels: Set<string> }>();\n    for (let i = 0; i < channels.length; i += KEY_PROGRAM_CHUNK) {\n      const label = 'ReGa.runScript(keyProgramReferences)';\n      const answer = await this.#rega(\n        label,\n        buildKeyProgramReferences(channels.slice(i, i + KEY_PROGRAM_CHUNK)),\n      );\n      if (!isRecord(answer) || !Array.isArray(answer['programs'])) {\n        throw new ClientError(`${label}: unexpected answer from the CCU.`);\n      }\n      for (const parsed of records(answer['programs']).flatMap((entry) => {\n        const p = program(entry);\n        return p === null ? [] : [p];\n      })) {\n        const seen = byId.get(parsed.id) ?? {\n          entry: { id: parsed.id, name: parsed.name, active: parsed.active, channels: [] },\n          channels: new Set<string>(),\n        };\n        for (const dp of parsed.datapoints) {\n          const address = dp.split('.')[1];\n          if (address !== undefined && address !== '') seen.channels.add(address);\n        }\n        byId.set(parsed.id, seen);\n      }\n    }\n    return [...byId.values()].map(({ entry, channels: set }) => ({ ...entry, channels: [...set] }));\n  }\n}\n","/**\n * CCU management: interfaces & radio health, pairing, service messages, CCU\n * info and heating groups. Pure orchestration over two transports:\n *\n * - the per-interface XML-RPC clients (`listBidcosInterfaces`, `setInstallMode`,\n *   `getInstallMode`), and\n * - the WebUI JSON-RPC client with the library's existing session handling (the\n *   session id is fetched per call through `getSessionId`, so renews apply).\n *\n * Every CCU answer arrives as `unknown` and is narrowed defensively. A value the\n * CCU did not answer is `null`; a failed call is a {@link CcuManagementError}\n * that names the method and keeps the CCU's fault text.\n */\nimport type {\n  HmCcuInfo,\n  HmGroup,\n  HmGroupCreate,\n  HmGroupMember,\n  HmGroupUpdate,\n  HmInstallModeRequest,\n  HmInterfaceInfo,\n  HmRadioGateway,\n  HmServiceMessage,\n} from '../../api/types.js';\nimport { Interface } from '../../support/constants.js';\nimport {\n  CcuManagementError,\n  ClientError,\n  GroupWriteVerificationError,\n  ValidationError,\n} from '../../support/errors.js';\nimport { jsEscape, type WebUiHttp } from '../../transport/webui/webui-http.js';\nimport { JsonRpcMethod } from '../../transport/jsonrpc/methods.js';\nimport type { InstallModeCall, RadioGatewayInfo } from '../../transport/interface-client.js';\nimport { decodeRegaName, runScript, type RegaPostClient } from '../rega/rega-runner.js';\nimport { CcuTopology } from './ccu-topology.js';\nimport { CcuKeyPrograms } from './ccu-key-programs.js';\nimport { CcuKeyDiagnosis } from './ccu-key-diagnosis.js';\nimport {\n  ACKNOWLEDGE_SERVICE_MESSAGE,\n  GET_CCU_PLATFORM,\n  GET_SERVICE_MESSAGES,\n} from '../rega/scripts.js';\n\n/** The slice of {@link import('../../transport/interface-client.js').InterfaceClient} used here. */\nexport interface ManagementInterfaceClient {\n  listBidcosInterfaces(): Promise<RadioGatewayInfo[]>;\n  setInstallMode(request: InstallModeCall): Promise<void>;\n  getInstallModeRemaining(): Promise<number | null>;\n}\n\n/** Constructor dependencies. */\nexport interface CcuManagementOptions {\n  /** WebUI JSON-RPC client, or `undefined` without credentials. */\n  readonly json: RegaPostClient | undefined;\n  /** WebUI HMServer page transport (group writes), or `undefined` without credentials. */\n  readonly webUi?: WebUiHttp | undefined;\n  /** Current (renewed if needed) session id; `undefined` for session-less clients. */\n  readonly getSessionId: () => Promise<string | undefined>;\n  /** The XML-RPC client of a configured interface. */\n  readonly interfaceClient: (iface: Interface) => ManagementInterfaceClient | undefined;\n  /** Interfaces the facade was configured with, in order. */\n  readonly configuredInterfaces: () => readonly Interface[];\n}\n\nconst GROUP_CREATE_PATH = '/pages/jpages/group/create';\nconst GROUP_SAVE_PATH = '/pages/jpages/group/save';\nconst GROUP_DELETE_PATH = '/pages/jpages/group/delete';\n/** The draft id the `create` page embeds: `self.groupId = 7;` (GroupEditPage.ftl). */\nconst DRAFT_GROUP_ID = /self\\.groupId\\s*=\\s*(\\d+)/;\n/** Group types the WebUI offers; any type seen in `groups()` is accepted too. */\nconst KNOWN_GROUP_TYPES: readonly string[] = ['hmip.heating.group', 'HomeMatic.heating'];\nconst CHANNEL_ADDRESS = /^[0-9A-Za-z_-]+:\\d+$/;\nconst MAX_GROUP_NAME = 64;\nconst DEFAULT_INSTALL_SECONDS = 60;\nconst MAX_INSTALL_SECONDS = 3600;\nconst SERVICE_MESSAGE_ID = /^\\d+$/;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction asRecordArray(value: unknown): Record<string, unknown>[] {\n  return Array.isArray(value) ? value.filter(isRecord) : [];\n}\n\nfunction strOrNull(value: unknown): string | null {\n  if (typeof value === 'string') return value === '' ? null : value;\n  if (typeof value === 'number' && Number.isFinite(value)) return String(value);\n  return null;\n}\n\nfunction numOrNull(value: unknown): number | null {\n  if (value === null || value === undefined || value === '') return null;\n  const num = typeof value === 'number' ? value : Number(value);\n  return Number.isFinite(num) ? num : null;\n}\n\nconst INTERFACES_BY_NAME: ReadonlyMap<string, Interface> = new Map(\n  Object.values(Interface).map((iface): [string, Interface] => [iface.toString(), iface]),\n);\n\nfunction toInterface(name: string): Interface {\n  const match = INTERFACES_BY_NAME.get(name);\n  if (match === undefined) throw new ValidationError(`Unknown interface \"${name}\".`);\n  return match;\n}\n\nfunction toGateway(info: RadioGatewayInfo): HmRadioGateway {\n  return { ...info };\n}\n\n/** Parse a ReGa `UriEncode`d text and trim it; `null` when empty. */\nfunction decodedOrNull(value: unknown): string | null {\n  if (typeof value !== 'string') return null;\n  const text = decodeRegaName(value).trim();\n  return text === '' ? null : text;\n}\n\n/** `VERSION=3.75.7` style lines → map. */\nfunction parseKeyValueLines(text: string): Map<string, string> {\n  const out = new Map<string, string>();\n  for (const line of text.split(/\\r?\\n/)) {\n    const eq = line.indexOf('=');\n    if (eq > 0) out.set(line.slice(0, eq).trim(), line.slice(eq + 1).trim());\n  }\n  return out;\n}\n\n/** Product families derived from the raw `PRODUCT=` value of `/VERSION`. */\nconst OPENCCU_PRODUCTS: ReadonlySet<string> = new Set(['raspberrymatic', 'openccu', 'ova']);\n\nfunction productFamily(raw: string | null): HmCcuInfo['productFamily'] {\n  if (raw === null) return 'unknown';\n  const key = raw.toLowerCase();\n  if (key === 'ccu3') return 'ccu3';\n  return OPENCCU_PRODUCTS.has(key) ? 'openccu' : 'unknown';\n}\n\nexport class CcuManagement {\n  private readonly json: RegaPostClient | undefined;\n  private readonly webUi: WebUiHttp | undefined;\n  private readonly getSessionId: () => Promise<string | undefined>;\n  private readonly interfaceClient: (iface: Interface) => ManagementInterfaceClient | undefined;\n  private readonly configuredInterfaces: () => readonly Interface[];\n\n  public constructor(options: CcuManagementOptions) {\n    this.json = options.json;\n    this.webUi = options.webUi;\n    this.getSessionId = options.getSessionId;\n    this.interfaceClient = options.interfaceClient;\n    this.configuredInterfaces = options.configuredInterfaces;\n  }\n\n  // --- interfaces & radio health ---------------------------------------------\n\n  /**\n   * Every interface the CCU offers (JSON-RPC `Interface.listInterfaces`), with\n   * connection state, duty cycle and, for BidCos, the radio gateways. Without a\n   * JSON-RPC client only the configured interfaces are listed and every probe\n   * result is `null`.\n   */\n  public async listInterfaces(): Promise<HmInterfaceInfo[]> {\n    const offered = await this.offeredInterfaces();\n    const gatewaysByName = new Map<string, HmRadioGateway[]>();\n    for (const entry of offered) {\n      const iface = INTERFACES_BY_NAME.get(entry.name);\n      const client = iface === undefined ? undefined : this.interfaceClient(iface);\n      if (client === undefined || (iface !== Interface.BIDCOS_RF && iface !== Interface.HMIP_RF)) {\n        continue;\n      }\n      const gateways = await this.tryOrNull(() => client.listBidcosInterfaces());\n      if (gateways !== null) gatewaysByName.set(entry.name, gateways.map(toGateway));\n    }\n    const needsFallback = offered.some(\n      (e) =>\n        e.name === Interface.BIDCOS_RF.toString() &&\n        (gatewaysByName.get(e.name) ?? []).every((g) => g.dutyCycle === null),\n    );\n    const fallbackDuty = needsFallback ? await this.ownRadioDutyCycle() : null;\n\n    const result: HmInterfaceInfo[] = [];\n    for (const entry of offered) {\n      const gateways = gatewaysByName.get(entry.name) ?? [];\n      const primary = gateways.find((g) => g.isDefault) ?? gateways[0];\n      const connected = primary?.connected ?? (await this.isPresent(entry.name));\n      const dutyCycle =\n        primary?.dutyCycle ?? (entry.name === Interface.BIDCOS_RF.toString() ? fallbackDuty : null);\n      result.push({\n        name: entry.name,\n        port: entry.port,\n        info: entry.info,\n        connected,\n        dutyCycle,\n        firmware: primary?.firmware ?? null,\n        type: primary?.type ?? null,\n        gateways,\n      });\n    }\n    return result;\n  }\n\n  // --- pairing -----------------------------------------------------------------\n\n  /** Open (default 60 s) or close the pairing window of a configured interface. */\n  public async setInstallMode(request: HmInstallModeRequest): Promise<void> {\n    const client = this.requireClient(request.interface);\n    if (!request.on) {\n      await client.setInstallMode({ on: false });\n      return;\n    }\n    const seconds = request.seconds ?? DEFAULT_INSTALL_SECONDS;\n    if (!Number.isInteger(seconds) || seconds < 1 || seconds > MAX_INSTALL_SECONDS) {\n      throw new ValidationError(\n        `seconds must be an integer between 1 and ${MAX_INSTALL_SECONDS}, got ${String(seconds)}.`,\n      );\n    }\n    const call: InstallModeCall =\n      request.mode === undefined\n        ? { on: true, seconds }\n        : { on: true, seconds, mode: request.mode === 'secure' ? 2 : 1 };\n    await client.setInstallMode(call);\n  }\n\n  /** Seconds left of the pairing window; `null` when the CCU's answer was unusable. */\n  public async getInstallMode(interfaceName: string): Promise<number | null> {\n    return this.requireClient(interfaceName).getInstallModeRemaining();\n  }\n\n  // --- service messages --------------------------------------------------------\n\n  /** Every active service message (ReGa listing of `ID_SERVICES`). */\n  public async serviceMessages(): Promise<HmServiceMessage[]> {\n    const raw = await this.rega('ReGa.runScript(serviceMessages)', GET_SERVICE_MESSAGES);\n    return asRecordArray(raw).flatMap((entry) => {\n      const id = strOrNull(entry['id']);\n      if (id === null) return [];\n      const address = strOrNull(entry['address']);\n      const colon = address === null ? -1 : address.lastIndexOf(':');\n      const device = address === null ? null : colon === -1 ? address : address.slice(0, colon);\n      const channel = address === null || colon === -1 ? null : numOrNull(address.slice(colon + 1));\n      const seconds = numOrNull(entry['timestamp']);\n      const message: HmServiceMessage = {\n        id,\n        name: decodedOrNull(entry['name']),\n        address: device,\n        channel,\n        type: strOrNull(entry['type']),\n        timestamp: seconds === null || seconds <= 0 ? null : seconds * 1000,\n        acknowledgeable: entry['acknowledgeable'] === true,\n      };\n      return [message];\n    });\n  }\n\n  /** Acknowledge one service message by its id. */\n  public async acknowledgeServiceMessage(id: string): Promise<void> {\n    if (!SERVICE_MESSAGE_ID.test(id)) {\n      throw new ValidationError(`Invalid service message id \"${id}\".`);\n    }\n    const raw = await this.rega(\n      'ReGa.runScript(acknowledgeServiceMessage)',\n      ACKNOWLEDGE_SERVICE_MESSAGE,\n      {\n        id,\n      },\n    );\n    if (!isRecord(raw) || raw['ok'] !== true) {\n      throw new ValidationError(`Unknown service message \"${id}\".`);\n    }\n  }\n\n  // --- CCU info ----------------------------------------------------------------\n\n  /** Version, product, serial and hostname; each `null` when unanswered. */\n  public async ccuInfo(): Promise<HmCcuInfo> {\n    const [version, serial, platform] = await Promise.allSettled([\n      this.call(JsonRpcMethod.CCU_GET_VERSION),\n      this.call(JsonRpcMethod.CCU_GET_SERIAL),\n      this.rega('ReGa.runScript(ccuPlatform)', GET_CCU_PLATFORM),\n    ]);\n    if (\n      version.status === 'rejected' &&\n      serial.status === 'rejected' &&\n      platform.status === 'rejected'\n    ) {\n      throw version.reason instanceof CcuManagementError\n        ? version.reason\n        : new CcuManagementError(JsonRpcMethod.CCU_GET_VERSION, version.reason);\n    }\n    const release =\n      platform.status === 'fulfilled' && isRecord(platform.value)\n        ? parseKeyValueLines(decodeRegaName(releaseText(platform.value)))\n        : new Map<string, string>();\n    const hostname =\n      platform.status === 'fulfilled' && isRecord(platform.value)\n        ? decodedOrNull(platform.value['host'])\n        : null;\n    const product = strOrNull(release.get('PRODUCT'));\n    return {\n      version: version.status === 'fulfilled' ? strOrNull(version.value) : null,\n      product,\n      productFamily: productFamily(product),\n      platform: strOrNull(release.get('PLATFORM')),\n      serial: serial.status === 'fulfilled' ? strOrNull(serial.value) : null,\n      hostname,\n    };\n  }\n\n  // --- groups ------------------------------------------------------------------\n\n  /**\n   * The heating groups of the CCU (\"Gruppen\"), read from `CCU.getHeatingGroupList`\n   * (the HMServer's `/etc/config/groups.gson`). `[]` when the CCU has no groups\n   * file. Writes (`createGroup` / `updateGroup` / `deleteGroup`) go through the\n   * HMServer's WebUI pages instead, see the group-writes section below.\n   */\n  public async groups(): Promise<HmGroup[]> {\n    const raw = await this.call(JsonRpcMethod.CCU_GET_HEATING_GROUP_LIST);\n    if (typeof raw !== 'string' || raw.trim() === '') return [];\n    let parsed: unknown;\n    try {\n      parsed = JSON.parse(raw);\n    } catch (err) {\n      throw new CcuManagementError(JsonRpcMethod.CCU_GET_HEATING_GROUP_LIST, err);\n    }\n    if (!isRecord(parsed)) return [];\n    // The groups sit in arrays below the top level; the WebUI walks them without\n    // naming the key, so do the same.\n    return Object.keys(parsed)\n      .sort()\n      .flatMap((key) => asRecordArray(parsed[key]))\n      .flatMap((entry) => {\n        const group = toGroup(entry);\n        return group === null ? [] : [group];\n      });\n  }\n\n  // --- group writes ------------------------------------------------------------\n  //\n  // WARNING: UNDOCUMENTED and firmware-dependent. There is no JSON-RPC / XML-RPC\n  // method for group writes; these calls reproduce what the CCU WebUI's own\n  // JavaScript sends to the HMServer pages, copied from eq-3/occu\n  //   HMserver/opt/HMServer/pages/GroupEditPage.ftl  (`_SaveGroup`: POST\n  //     /pages/jpages/group/save?sid=...)\n  //   HMserver/opt/HMServer/pages/GroupListPage.ftl  (`NewGroup`: GET\n  //     /pages/jpages/group/create; `removeGroup`: POST /pages/jpages/group/delete)\n  // plus the `Interface.setMetadata inHeatingGroup` hints the same page sets.\n  // Every write is verified by reading `groups()` back; a mismatch is a\n  // GroupWriteVerificationError. Unlike the WebUI, the virtual group device and\n  // its channels are not renamed afterwards.\n\n  /** Create a group; resolves with the group as read back from the CCU. */\n  public async createGroup(input: HmGroupCreate): Promise<HmGroup> {\n    const name = validateGroupName(input.name);\n    const members = validateMembers(input.members);\n    const before = await this.groups();\n    this.validateType(input.type, before);\n    const { webUi, sid } = await this.requireWebUi('group/create');\n\n    // The page comes in the HMServer envelope (`=` written as =); a new\n    // group's draft id is 0 and the save answers with the id the CCU assigned.\n    const page = checkWebUiResponse(GROUP_CREATE_PATH, await webUi.get(GROUP_CREATE_PATH, sid));\n    const draft = DRAFT_GROUP_ID.exec(page);\n    if (draft === null || draft[1] === undefined) {\n      throw new CcuManagementError(GROUP_CREATE_PATH, new ClientError('no group id in the page'));\n    }\n    const draftId = Number(draft[1]);\n    const response = await this.saveGroup(webUi, sid, {\n      groupId: draftId,\n      groupName: jsEscape(name),\n      groupTypeId: input.type,\n      forbidSingleOperation: false,\n      assignedDevicesIds: members,\n      isNewGroup: true,\n      // The WebUI sends the (still empty) virtual device serial after the name.\n      groupDeviceName: `${name} `,\n    });\n    const id = numOrNull(response) ?? draftId;\n    await this.flagMembers(members, 'true');\n    return this.verifyPresent(id, { name, type: input.type, members });\n  }\n\n  /** Change a group's name and/or member list; resolves with the group read back. */\n  public async updateGroup(id: number, patch: HmGroupUpdate): Promise<HmGroup> {\n    if (patch.name === undefined && patch.members === undefined) {\n      throw new ValidationError('updateGroup needs a name and/or members.');\n    }\n    const name = patch.name === undefined ? undefined : validateGroupName(patch.name);\n    const members = patch.members === undefined ? undefined : validateMembers(patch.members);\n    const current = await this.requireGroup(id);\n    const { webUi, sid } = await this.requireWebUi('group/save');\n\n    const nextName = name ?? current.name;\n    const nextMembers = members ?? current.members.map((m) => m.address);\n    await this.saveGroup(webUi, sid, {\n      groupId: id,\n      groupName: jsEscape(nextName),\n      groupTypeId: current.type,\n      forbidSingleOperation: current.forbidSingleOperation,\n      assignedDevicesIds: nextMembers,\n      isNewGroup: false,\n      // The WebUI appends the virtual device serial; a CCU whose groups carry\n      // no such suffix (observed on OpenCCU 3.89) keeps the plain name.\n      groupDeviceName:\n        current.deviceAddress === null ? nextName : `${nextName} ${virtualDeviceSerial(id)}`,\n    });\n    await this.flagMembers(nextMembers, 'true');\n    const kept = new Set(nextMembers);\n    await this.flagMembers(\n      current.members.map((m) => m.address).filter((a) => !kept.has(a)),\n      'false',\n    );\n    return this.verifyPresent(id, { name: nextName, type: current.type, members: nextMembers });\n  }\n\n  /** Delete a group; verified by the group being gone from the read-back. */\n  public async deleteGroup(id: number): Promise<void> {\n    const current = await this.requireGroup(id);\n    const { webUi, sid } = await this.requireWebUi('group/delete');\n    const text = await webUi.post(GROUP_DELETE_PATH, sid, JSON.stringify({ groupId: id }));\n    checkWebUiResponse(GROUP_DELETE_PATH, text);\n    await this.flagMembers(\n      current.members.map((m) => m.address),\n      'false',\n    );\n    const after = await this.groups();\n    if (after.some((g) => g.id === id)) {\n      throw new GroupWriteVerificationError(`Group ${id} is still listed after deleteGroup.`);\n    }\n  }\n\n  private async requireGroup(id: number): Promise<HmGroup> {\n    if (!Number.isInteger(id)) throw new ValidationError(`Invalid group id ${String(id)}.`);\n    const found = (await this.groups()).find((g) => g.id === id);\n    if (found === undefined) throw new ValidationError(`Unknown group ${id}.`);\n    return found;\n  }\n\n  private validateType(type: string, existing: readonly HmGroup[]): void {\n    const known = new Set<string>([...KNOWN_GROUP_TYPES, ...existing.map((g) => g.type)]);\n    if (!known.has(type)) {\n      throw new ValidationError(`Unknown group type \"${type}\" (known: ${[...known].join(', ')}).`);\n    }\n  }\n\n  private async requireWebUi(label: string): Promise<{ webUi: WebUiHttp; sid: string }> {\n    if (this.webUi === undefined) {\n      throw new ValidationError(\n        `${label} needs WebUI credentials (HMServer pages); none are configured.`,\n      );\n    }\n    const sid = await this.getSessionId();\n    if (sid === undefined) {\n      throw new ValidationError(`${label} needs a WebUI session.`);\n    }\n    return { webUi: this.webUi, sid };\n  }\n\n  /** POST `group/save`; returns the response `content` (the group id as text). */\n  private async saveGroup(\n    webUi: WebUiHttp,\n    sid: string,\n    payload: Record<string, string | number | boolean | string[]>,\n  ): Promise<string> {\n    const text = await webUi.post(GROUP_SAVE_PATH, sid, JSON.stringify(payload));\n    return checkWebUiResponse(GROUP_SAVE_PATH, text);\n  }\n\n  /**\n   * The WebUI marks every device it puts in / takes out of a heating group with\n   * `Interface.setMetadata inHeatingGroup` (its pages use the flag to hide\n   * grouped devices). Best effort: the hint is cosmetic and the group itself is\n   * verified separately.\n   */\n  private async flagMembers(addresses: readonly string[], value: 'true' | 'false'): Promise<void> {\n    const devices = [...new Set(addresses.map((a) => a.slice(0, a.lastIndexOf(':'))))];\n    for (const address of devices) {\n      try {\n        const objectId = await this.call(JsonRpcMethod.DEVICE_GET_REGA_ID_BY_ADDRESS, { address });\n        if (typeof objectId !== 'string' || objectId === '' || objectId === 'noDeviceFound')\n          continue;\n        await this.call(JsonRpcMethod.INTERFACE_SET_METADATA, {\n          objectId,\n          dataId: 'inHeatingGroup',\n          value,\n        });\n      } catch {\n        // cosmetic hint only\n      }\n    }\n  }\n\n  private async verifyPresent(\n    id: number,\n    want: { name: string; type: string; members: readonly string[] },\n  ): Promise<HmGroup> {\n    const found = (await this.groups()).find((g) => g.id === id);\n    if (found === undefined) {\n      throw new GroupWriteVerificationError(`Group ${id} is not listed after the write.`);\n    }\n    const have = found.members.map((m) => m.address).sort();\n    const expected = [...want.members].sort();\n    const sameMembers = have.length === expected.length && have.every((a, i) => a === expected[i]);\n    if (found.name !== want.name || found.type !== want.type || !sameMembers) {\n      throw new GroupWriteVerificationError(\n        `Group ${id} reads back as \"${found.name}\" (${found.type}, ${have.length} members), ` +\n          `expected \"${want.name}\" (${want.type}, ${expected.length} members).`,\n      );\n    }\n    return found;\n  }\n\n  // --- names and rooms ---------------------------------------------------------\n\n  /** Device/channel names and rooms over ReGa, on this service's session. */\n  public topology(): CcuTopology {\n    return new CcuTopology((label, script, params) => this.rega(label, script, params));\n  }\n\n  /** The key-event program service (HmIP key presses), on this service's session. */\n  public keyPrograms(): CcuKeyPrograms {\n    return new CcuKeyPrograms((label, script, params) => this.rega(label, script, params));\n  }\n\n  /** The read-only key diagnosis (ReGa side), on this service's session. */\n  public keyDiagnosis(): CcuKeyDiagnosis {\n    return new CcuKeyDiagnosis((label, script, params) => this.rega(label, script, params));\n  }\n\n  // --- internals ---------------------------------------------------------------\n\n  private requireClient(interfaceName: string): ManagementInterfaceClient {\n    const iface = toInterface(interfaceName);\n    const client = this.interfaceClient(iface);\n    if (client === undefined) {\n      throw new ValidationError(`Interface \"${interfaceName}\" is not configured.`);\n    }\n    return client;\n  }\n\n  private requireJson(method: string): RegaPostClient {\n    if (this.json === undefined) {\n      throw new ValidationError(\n        `${method} needs WebUI credentials (JSON-RPC); none are configured.`,\n      );\n    }\n    return this.json;\n  }\n\n  /** A session-bound JSON-RPC call whose failure names the method. */\n  private async call(method: string, params?: Record<string, unknown>): Promise<unknown> {\n    const json = this.requireJson(method);\n    try {\n      const sessionId = await this.getSessionId();\n      return await json.post(method, params, sessionId !== undefined ? { sessionId } : undefined);\n    } catch (err) {\n      throw err instanceof ValidationError ? err : new CcuManagementError(method, err);\n    }\n  }\n\n  private async rega(\n    label: string,\n    script: string,\n    params?: Record<string, string | number>,\n  ): Promise<unknown> {\n    const json = this.requireJson(label);\n    try {\n      const sessionId = await this.getSessionId();\n      return await runScript(json, sessionId, script, params);\n    } catch (err) {\n      throw err instanceof ValidationError ? err : new CcuManagementError(label, err);\n    }\n  }\n\n  private async tryOrNull<T>(fn: () => Promise<T>): Promise<T | null> {\n    try {\n      return await fn();\n    } catch {\n      return null;\n    }\n  }\n\n  private async offeredInterfaces(): Promise<\n    { name: string; port: number | null; info: string | null }[]\n  > {\n    if (this.json === undefined) {\n      return this.configuredInterfaces().map((iface) => ({\n        name: iface,\n        port: null,\n        info: null,\n      }));\n    }\n    const raw = await this.call(JsonRpcMethod.INTERFACE_LIST_INTERFACES);\n    return asRecordArray(raw).flatMap((entry) => {\n      const name = strOrNull(entry['name']);\n      return name === null\n        ? []\n        : [{ name, port: numOrNull(entry['port']), info: strOrNull(entry['info']) }];\n    });\n  }\n\n  private async isPresent(name: string): Promise<boolean | null> {\n    if (this.json === undefined) return null;\n    const answer = await this.tryOrNull(() =>\n      this.call(JsonRpcMethod.INTERFACE_IS_PRESENT, { interface: name }),\n    );\n    if (typeof answer === 'boolean') return answer;\n    if (answer === 'true') return true;\n    if (answer === 'false') return false;\n    return null;\n  }\n\n  /**\n   * Fallback when `listBidcosInterfaces` gave no answer: `Interface.getDutyCycle`\n   * (RaspberryMatic / OpenCCU) reports the CCU's own radio module as ONE entry\n   * with string numbers (`\"7\"`). It cannot be attributed to HmIP, so it only\n   * ever stands in for BidCos-RF; non-numeric or absent is `null`.\n   */\n  private async ownRadioDutyCycle(): Promise<number | null> {\n    if (this.json === undefined) return null;\n    const raw = await this.tryOrNull(() => this.call(JsonRpcMethod.INTERFACE_GET_DUTY_CYCLE));\n    const entries = asRecordArray(raw);\n    return entries.length === 1 ? numOrNull(entries[0]?.['dutyCycle']) : null;\n  }\n}\n\nfunction releaseText(value: Record<string, unknown>): string {\n  const release = value['release'];\n  return typeof release === 'string' ? release : '';\n}\n\nconst DEVICE_ADDRESS_SUFFIX = /\\b(INT\\d{7})\\s*$/;\n\nfunction toGroup(entry: Record<string, unknown>): HmGroup | null {\n  const id = numOrNull(entry['id']);\n  if (id === null) return null;\n  const props = isRecord(entry['groupProperties']) ? entry['groupProperties'] : {};\n  const groupType = isRecord(entry['groupType']) ? entry['groupType'] : {};\n  const deviceName = strOrNull(props['GROUP_DEVICE_NAME']);\n  const deviceMatch = deviceName === null ? null : DEVICE_ADDRESS_SUFFIX.exec(deviceName);\n  const members: HmGroupMember[] = asRecordArray(entry['groupMembers']).flatMap((m) => {\n    const address = strOrNull(m['id']);\n    if (address === null) return [];\n    const memberType = isRecord(m['memberType']) ? strOrNull(m['memberType']['id']) : null;\n    return [{ address, type: memberType ?? '' }];\n  });\n  return {\n    id,\n    name: (strOrNull(props['NAME']) ?? '').trim(),\n    type: strOrNull(groupType['id']) ?? '',\n    typeLabel: strOrNull(groupType['label']),\n    deviceAddress: deviceMatch === null ? null : (deviceMatch[1] ?? null),\n    forbidSingleOperation: props['FORBID_SINGLE_OPERATION'] === true,\n    members,\n  };\n}\n\n/** `INT` + the id left-padded to 7 digits (`createVirtualDeviceSerialNumber`, viewmodels.js). */\nfunction virtualDeviceSerial(id: number): string {\n  return `INT${String(id).padStart(7, '0')}`;\n}\n\nfunction validateGroupName(raw: string): string {\n  const name = raw.replace(/\"/g, \"'\").trim();\n  if (name === '' || name.length > MAX_GROUP_NAME) {\n    throw new ValidationError(`Group name must be 1..${MAX_GROUP_NAME} characters.`);\n  }\n  return name;\n}\n\nfunction validateMembers(members: readonly string[]): string[] {\n  for (const address of members) {\n    if (!CHANNEL_ADDRESS.test(address)) {\n      throw new ValidationError(`Invalid member channel address \"${address}\".`);\n    }\n  }\n  return [...new Set(members)];\n}\n\n/**\n * Check the HMServer's `{isSuccessful, errorCode, content}` envelope. The\n * content (HTML on failure) is never copied into the error.\n */\nfunction checkWebUiResponse(path: string, text: string): string {\n  let parsed: unknown;\n  try {\n    parsed = JSON.parse(text);\n  } catch {\n    throw new CcuManagementError(path, new ClientError('response was not JSON'));\n  }\n  if (!isRecord(parsed) || parsed['isSuccessful'] !== true) {\n    const code = isRecord(parsed) ? strOrNull(parsed['errorCode']) : null;\n    throw new CcuManagementError(\n      path,\n      new ClientError(\n        code === '42' ? 'session expired (errorCode 42)' : `refused (errorCode ${code ?? 'none'})`,\n      ),\n    );\n  }\n  const content = parsed['content'];\n  return typeof content === 'string' || typeof content === 'number' ? String(content) : '';\n}\n","/**\n * Local XML-RPC callback server. The CCU POSTs its notifications (`event`,\n * `newDevices`, `system.multicall`, …) here; we parse the methodCall, dispatch\n * it to {@link handlers}, and reply with an XML-RPC methodResponse or fault.\n *\n * Protocol specifics handled:\n * - Inbound bodies are UTF-8 (note: this differs from the ISO-8859-1 used for\n *   OUTBOUND XML-RPC calls to the CCU).\n * - A handler returning `null`/`undefined` is serialized as boolean `true`\n *   (Homematic expects an ack).\n * - Method-not-found → fault -32601; handler exception → fault -32603. XML-RPC\n *   faults are returned with HTTP 200.\n */\n\nimport { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';\nimport type { AddressInfo } from 'node:net';\nimport { parseXmlRpc } from '../xmlrpc/parse.js';\nimport { serializeFault, serializeMethodResponse } from '../xmlrpc/serialize.js';\nimport type { XmlRpcValue } from '../xmlrpc/types.js';\nimport type { RawCallbackEvent } from './events.js';\nimport {\n  dispatch,\n  FAULT_INTERNAL_ERROR,\n  FAULT_METHOD_NOT_FOUND,\n  MethodNotFoundError,\n  type DispatchContext,\n} from './handlers.js';\n\nconst CONTENT_TYPE = 'text/xml; charset=utf-8';\n\n/** Construction options for {@link CallbackServer}. */\nexport interface CallbackServerOptions {\n  /** Host/interface to bind. */\n  readonly host: string;\n  /** Port to bind; `0` requests an ephemeral port (read it back via {@link CallbackServer.port}). */\n  readonly port: number;\n  /** Invoked for every normalized callback event the CCU pushes. */\n  readonly onEvent: (event: RawCallbackEvent) => void;\n  /** Supplies the device list for `listDevices(interfaceId)`. Defaults to `() => []`. */\n  readonly listDevicesProvider?: (interfaceId: string) => readonly XmlRpcValue[];\n}\n\n/** An XML-RPC callback HTTP server backed by `node:http`. */\nexport class CallbackServer {\n  private readonly host: string;\n  private readonly requestedPort: number;\n  private readonly onEvent: (event: RawCallbackEvent) => void;\n  private readonly listDevicesProvider: (interfaceId: string) => readonly XmlRpcValue[];\n  private readonly httpServer: Server;\n  private boundPort = 0;\n\n  public constructor(options: CallbackServerOptions) {\n    this.host = options.host;\n    this.requestedPort = options.port;\n    this.onEvent = options.onEvent;\n    this.listDevicesProvider = options.listDevicesProvider ?? ((): readonly XmlRpcValue[] => []);\n    this.httpServer = createServer((req, res) => {\n      this.handleRequest(req, res);\n    });\n  }\n\n  /** The actual bound port (meaningful only after {@link start} resolves). */\n  public get port(): number {\n    return this.boundPort;\n  }\n\n  /** Start listening. Resolves once the socket is bound. */\n  public async start(): Promise<void> {\n    await new Promise<void>((resolve, reject) => {\n      const onError = (err: Error): void => {\n        this.httpServer.removeListener('error', onError);\n        reject(err);\n      };\n      this.httpServer.once('error', onError);\n      this.httpServer.listen(this.requestedPort, this.host, () => {\n        this.httpServer.removeListener('error', onError);\n        const address = this.httpServer.address() as AddressInfo | null;\n        this.boundPort = address?.port ?? this.requestedPort;\n        resolve();\n      });\n    });\n  }\n\n  /** Stop listening and release the socket. Resolves once closed. */\n  public async stop(): Promise<void> {\n    await new Promise<void>((resolve, reject) => {\n      this.httpServer.close((err) => {\n        if (err) reject(err);\n        else resolve();\n      });\n    });\n  }\n\n  private handleRequest(req: IncomingMessage, res: ServerResponse): void {\n    const chunks: Buffer[] = [];\n    req.on('data', (chunk: Buffer) => chunks.push(chunk));\n    req.on('end', () => {\n      const body = Buffer.concat(chunks);\n      const payload = this.process(body);\n      res.writeHead(200, { 'Content-Type': CONTENT_TYPE, 'Content-Length': payload.length });\n      res.end(payload);\n    });\n    req.on('error', () => {\n      const payload = serializeFault(FAULT_INTERNAL_ERROR, 'request stream error');\n      res.writeHead(200, { 'Content-Type': CONTENT_TYPE, 'Content-Length': payload.length });\n      res.end(payload);\n    });\n  }\n\n  /** Parse, dispatch and serialize a single request body into a response buffer. */\n  private process(body: Buffer): Buffer {\n    let methodName = '';\n    let params: XmlRpcValue[] = [];\n    try {\n      // Inbound callback bodies are UTF-8.\n      const parsed = parseXmlRpc(body.toString('utf-8'));\n      if (parsed.kind !== 'call') {\n        return serializeFault(FAULT_INTERNAL_ERROR, 'expected an XML-RPC methodCall');\n      }\n      methodName = parsed.call.methodName;\n      params = parsed.call.params;\n    } catch (err) {\n      return serializeFault(FAULT_INTERNAL_ERROR, errorMessage(err));\n    }\n\n    const ctx: DispatchContext = {\n      emit: this.onEvent,\n      listDevices: this.listDevicesProvider,\n    };\n\n    try {\n      const result = dispatch({ methodName, params }, ctx);\n      // A handler that conceptually returns void acks with boolean true.\n      const value: XmlRpcValue = result ?? true;\n      return serializeMethodResponse(value);\n    } catch (err) {\n      if (err instanceof MethodNotFoundError) {\n        return serializeFault(FAULT_METHOD_NOT_FOUND, errorMessage(err));\n      }\n      return serializeFault(FAULT_INTERNAL_ERROR, errorMessage(err));\n    }\n  }\n}\n\nfunction errorMessage(err: unknown): string {\n  return err instanceof Error ? err.message : String(err);\n}\n","/**\n * Pure dispatch logic for the XML-RPC callback methods the CCU invokes on us.\n *\n * Each handler decodes positional arguments (exact CCU arg order), optionally\n * emits a {@link RawCallbackEvent}, and returns the XML-RPC response value.\n * There is NO I/O here: {@link CallbackServer} owns the HTTP and serialization.\n */\n\nimport { BaseHomematicError } from '../../support/errors.js';\nimport type { XmlRpcMethodCall, XmlRpcValue } from '../xmlrpc/types.js';\nimport type { RawCallbackEvent } from './events.js';\n\n/** JSON-RPC / XML-RPC standard fault code: requested method does not exist. */\nexport const FAULT_METHOD_NOT_FOUND = -32601;\n/** JSON-RPC / XML-RPC standard fault code: internal error while handling a call. */\nexport const FAULT_INTERNAL_ERROR = -32603;\n\n/** Thrown by {@link dispatch} when no handler matches the method name. */\nexport class MethodNotFoundError extends BaseHomematicError {}\n\n/** Thrown when a handler receives malformed / missing positional arguments. */\nexport class InvalidParamsError extends BaseHomematicError {}\n\n/** Context injected into the dispatcher: event sink + device-list provider. */\nexport interface DispatchContext {\n  /** Emit a normalized event (CCU → us notifications). */\n  readonly emit: (event: RawCallbackEvent) => void;\n  /** Provide the device list for `listDevices(interfaceId)`. */\n  readonly listDevices: (interfaceId: string) => readonly XmlRpcValue[];\n}\n\nfunction requireString(params: readonly XmlRpcValue[], index: number, name: string): string {\n  const value = params[index];\n  if (typeof value !== 'string') {\n    throw new InvalidParamsError(`expected string argument \"${name}\" at position ${index}`);\n  }\n  return value;\n}\n\nfunction requireNumber(params: readonly XmlRpcValue[], index: number, name: string): number {\n  const value = params[index];\n  if (typeof value !== 'number' || Number.isNaN(value)) {\n    throw new InvalidParamsError(`expected number argument \"${name}\" at position ${index}`);\n  }\n  return value;\n}\n\nfunction requireArg(params: readonly XmlRpcValue[], index: number, name: string): XmlRpcValue {\n  if (index >= params.length) {\n    throw new InvalidParamsError(`missing required argument \"${name}\" at position ${index}`);\n  }\n  return params[index] as XmlRpcValue;\n}\n\nfunction requireStringArray(params: readonly XmlRpcValue[], index: number, name: string): string[] {\n  const value = requireArg(params, index, name);\n  if (!Array.isArray(value)) {\n    throw new InvalidParamsError(`expected array argument \"${name}\" at position ${index}`);\n  }\n  return value.map((item, i) => {\n    if (typeof item !== 'string') {\n      throw new InvalidParamsError(`expected string at \"${name}\"[${i}]`);\n    }\n    return item;\n  });\n}\n\nfunction requireStructArray(\n  params: readonly XmlRpcValue[],\n  index: number,\n  name: string,\n): Record<string, unknown>[] {\n  const value = requireArg(params, index, name);\n  if (!Array.isArray(value)) {\n    throw new InvalidParamsError(`expected array argument \"${name}\" at position ${index}`);\n  }\n  return value.map((item, i) => {\n    if (typeof item !== 'object' || item === null || Array.isArray(item)) {\n      throw new InvalidParamsError(`expected struct at \"${name}\"[${i}]`);\n    }\n    return item as Record<string, unknown>;\n  });\n}\n\ntype Handler = (call: XmlRpcMethodCall, ctx: DispatchContext) => XmlRpcValue;\n\nconst handlers: Readonly<Record<string, Handler>> = {\n  event(call, ctx): XmlRpcValue {\n    const { params } = call;\n    ctx.emit({\n      type: 'event',\n      interfaceId: requireString(params, 0, 'interfaceId'),\n      channelAddress: requireString(params, 1, 'channelAddress'),\n      parameter: requireString(params, 2, 'parameter'),\n      value: requireArg(params, 3, 'value'),\n    });\n    return true;\n  },\n\n  newDevices(call, ctx): XmlRpcValue {\n    const { params } = call;\n    ctx.emit({\n      type: 'newDevices',\n      interfaceId: requireString(params, 0, 'interfaceId'),\n      descriptions: requireStructArray(params, 1, 'deviceDescriptions'),\n    });\n    return true;\n  },\n\n  deleteDevices(call, ctx): XmlRpcValue {\n    const { params } = call;\n    ctx.emit({\n      type: 'deleteDevices',\n      interfaceId: requireString(params, 0, 'interfaceId'),\n      addresses: requireStringArray(params, 1, 'addresses'),\n    });\n    return true;\n  },\n\n  updateDevice(call, ctx): XmlRpcValue {\n    const { params } = call;\n    ctx.emit({\n      type: 'updateDevice',\n      interfaceId: requireString(params, 0, 'interfaceId'),\n      address: requireString(params, 1, 'address'),\n      hint: requireNumber(params, 2, 'hint'),\n    });\n    return true;\n  },\n\n  replaceDevice(call, ctx): XmlRpcValue {\n    const { params } = call;\n    ctx.emit({\n      type: 'replaceDevice',\n      interfaceId: requireString(params, 0, 'interfaceId'),\n      oldAddress: requireString(params, 1, 'oldAddress'),\n      newAddress: requireString(params, 2, 'newAddress'),\n    });\n    return true;\n  },\n\n  readdedDevice(call, ctx): XmlRpcValue {\n    const { params } = call;\n    ctx.emit({\n      type: 'readdedDevice',\n      interfaceId: requireString(params, 0, 'interfaceId'),\n      addresses: requireStringArray(params, 1, 'addresses'),\n    });\n    return true;\n  },\n\n  error(call, ctx): XmlRpcValue {\n    const { params } = call;\n    ctx.emit({\n      type: 'error',\n      interfaceId: requireString(params, 0, 'interfaceId'),\n      code: requireNumber(params, 1, 'errorCode'),\n      message: requireString(params, 2, 'msg'),\n    });\n    return true;\n  },\n\n  listDevices(call, ctx): XmlRpcValue {\n    const interfaceId = requireString(call.params, 0, 'interfaceId');\n    return [...ctx.listDevices(interfaceId)];\n  },\n\n  'system.listMethods'(): XmlRpcValue {\n    return [...SUPPORTED_METHODS];\n  },\n\n  'system.methodHelp'(): XmlRpcValue {\n    // No per-method help text is required; return an empty string.\n    return '';\n  },\n\n  'system.multicall'(call, ctx): XmlRpcValue {\n    return runMulticall(call.params[0], ctx);\n  },\n};\n\n/** Method names this server advertises via `system.listMethods`. */\nexport const SUPPORTED_METHODS: readonly string[] = [\n  'event',\n  'newDevices',\n  'deleteDevices',\n  'updateDevice',\n  'replaceDevice',\n  'readdedDevice',\n  'listDevices',\n  'error',\n  'system.listMethods',\n  'system.methodHelp',\n  'system.multicall',\n];\n\nfunction faultStruct(code: number, message: string): XmlRpcValue {\n  return { faultCode: code, faultString: message };\n}\n\n/** Narrow an {@link XmlRpcValue} to a plain struct (rejecting arrays/Date/binary). */\nfunction asStruct(value: XmlRpcValue): { [key: string]: XmlRpcValue } | undefined {\n  if (\n    typeof value !== 'object' ||\n    value === null ||\n    Array.isArray(value) ||\n    value instanceof Date ||\n    value instanceof Uint8Array\n  ) {\n    return undefined;\n  }\n  return value;\n}\n\n/** Execute a `system.multicall` payload, wrapping each result/fault per spec. */\nfunction runMulticall(rawCalls: XmlRpcValue | undefined, ctx: DispatchContext): XmlRpcValue[] {\n  if (!Array.isArray(rawCalls)) {\n    throw new InvalidParamsError('system.multicall expects an array of calls');\n  }\n  return rawCalls.map((entry) => {\n    const struct = asStruct(entry);\n    if (struct === undefined) {\n      return faultStruct(FAULT_INTERNAL_ERROR, 'multicall entry is not a struct');\n    }\n    const methodName = struct['methodName'];\n    const params = struct['params'];\n    if (typeof methodName !== 'string') {\n      return faultStruct(FAULT_INTERNAL_ERROR, 'multicall entry missing methodName');\n    }\n    if (methodName === 'system.multicall') {\n      // Per the XML-RPC multicall convention, recursion is not allowed.\n      return faultStruct(FAULT_INTERNAL_ERROR, 'recursive system.multicall is not supported');\n    }\n    const callParams: XmlRpcValue[] = Array.isArray(params) ? params : [];\n    try {\n      const result = dispatch({ methodName, params: callParams }, ctx);\n      return [result ?? true];\n    } catch (err) {\n      if (err instanceof MethodNotFoundError) {\n        return faultStruct(FAULT_METHOD_NOT_FOUND, errorMessage(err));\n      }\n      return faultStruct(FAULT_INTERNAL_ERROR, errorMessage(err));\n    }\n  });\n}\n\nfunction errorMessage(err: unknown): string {\n  return err instanceof Error ? err.message : String(err);\n}\n\n/**\n * Dispatch a parsed XML-RPC method call to its handler.\n *\n * @throws {MethodNotFoundError} when the method name is unknown.\n * @throws {InvalidParamsError} (or any handler error) on malformed arguments.\n */\nexport function dispatch(call: XmlRpcMethodCall, ctx: DispatchContext): XmlRpcValue {\n  const handler = handlers[call.methodName];\n  if (handler === undefined) {\n    throw new MethodNotFoundError(`unknown callback method: ${call.methodName}`);\n  }\n  return handler(call, ctx);\n}\n","/**\n * Typed central events. {@link CentralEvent} is a discriminated union keyed on\n * the `type` field; the {@link EventBus} dispatches by that discriminant. Each\n * event has a \"natural routing key\" (see {@link eventKey}) used by key-specific\n * subscribers.\n */\n\nimport { dpkToUniqueId, type DataPointKey } from '../support/dpk.js';\n\n/** A value was received for a data point. */\nexport interface ValueReceivedEvent {\n  readonly type: 'valueReceived';\n  readonly dpk: DataPointKey;\n  readonly value: unknown;\n  /** Monotonic/epoch millis when the value was received. */\n  readonly receivedAt: number;\n  /**\n   * `event`: the CCU pushed it through the XML-RPC callback (a live change or\n   * a key press). `seed`: read back from a VALUES paramset (start-up seeding).\n   * Absent is treated like `seed` for ACTION parameters: only a pushed event\n   * may count as a key press.\n   */\n  readonly origin?: 'event' | 'seed';\n}\n\n/** A device was added to the registry. */\nexport interface DeviceAddedEvent {\n  readonly type: 'deviceAdded';\n  readonly address: string;\n}\n\n/** A device was removed from the registry. */\nexport interface DeviceRemovedEvent {\n  readonly type: 'deviceRemoved';\n  readonly address: string;\n}\n\n/** A batch of devices was created (e.g. after `newDevices`). */\nexport interface DevicesCreatedEvent {\n  readonly type: 'devicesCreated';\n  readonly addresses: string[];\n}\n\n/** An interface connection state transition. */\nexport interface ConnectionStateChangedEvent {\n  readonly type: 'connectionStateChanged';\n  readonly interfaceId: string;\n  readonly state: string;\n  readonly reason?: string;\n}\n\n/** A recovery stage transition for an interface. */\nexport interface RecoveryStageChangedEvent {\n  readonly type: 'recoveryStageChanged';\n  readonly interfaceId: string;\n  readonly stage: string;\n}\n\n/** The backend reported a system-level error for an interface. */\nexport interface SystemErrorEvent {\n  readonly type: 'systemError';\n  readonly interfaceId: string;\n  readonly code: number;\n  readonly message: string;\n}\n\n/** The central finished its initial startup. */\nexport interface ReadyEvent {\n  readonly type: 'ready';\n}\n\n/** Discriminated union of all central events. */\nexport type CentralEvent =\n  | ValueReceivedEvent\n  | DeviceAddedEvent\n  | DeviceRemovedEvent\n  | DevicesCreatedEvent\n  | ConnectionStateChangedEvent\n  | RecoveryStageChangedEvent\n  | SystemErrorEvent\n  | ReadyEvent;\n\n/** All valid event type discriminants. */\nexport type CentralEventType = CentralEvent['type'];\n\n/**\n * The natural routing key for an event, used by key-specific subscribers:\n * - `valueReceived` → the dpk unique id\n * - `deviceAdded` / `deviceRemoved` → the device address\n * - `connectionStateChanged` / `recoveryStageChanged` / `systemError` → interfaceId\n * - `devicesCreated` / `ready` → `undefined` (no natural key)\n */\nexport function eventKey(event: CentralEvent): string | undefined {\n  switch (event.type) {\n    case 'valueReceived':\n      return dpkToUniqueId(event.dpk);\n    case 'deviceAdded':\n    case 'deviceRemoved':\n      return event.address;\n    case 'connectionStateChanged':\n    case 'recoveryStageChanged':\n    case 'systemError':\n      return event.interfaceId;\n    case 'devicesCreated':\n    case 'ready':\n      return undefined;\n  }\n}\n","/**\n * Typed in-process event bus for the central.\n *\n * Dispatch is by event CLASS (the `type` discriminant), not by a topic string.\n * A subscriber for type `T` receives only events of that type whose natural key\n * matches its `key` (or all of that type when no `key` is given — a wildcard).\n * Handlers are ordered by priority then insertion order and run concurrently\n * with error isolation: a throwing/rejecting handler is logged via the injected\n * logger and never prevents the other handlers from running, nor is it\n * rethrown to the publisher.\n */\n\nimport { eventKey, type CentralEvent, type CentralEventType } from './events.js';\n\n/** Handler priority. Lower numeric value runs first. */\nexport enum EventPriority {\n  CRITICAL = 0,\n  HIGH = 1,\n  NORMAL = 2,\n  LOW = 3,\n}\n\n/** Minimal logger contract used to report handler failures. */\nexport interface EventBusLogger {\n  error(message: string, error: unknown): void;\n}\n\n/** Options accepted by {@link EventBus.subscribe}. */\nexport interface SubscribeOptions<T extends CentralEventType> {\n  /** Event type discriminant to listen for. */\n  readonly type: T;\n  /** Optional natural routing key; omit for a wildcard over the whole type. */\n  readonly key?: string;\n  /** Handler invoked with the narrowed event payload. */\n  readonly handler: (event: Extract<CentralEvent, { type: T }>) => void | Promise<void>;\n  /** Priority; defaults to {@link EventPriority.NORMAL}. */\n  readonly priority?: EventPriority;\n}\n\n/** Constructor options for {@link EventBus}. */\nexport interface EventBusOptions {\n  /** Logger used to report handler failures; defaults to a no-op. */\n  readonly logger?: EventBusLogger;\n}\n\ninterface Subscription {\n  readonly type: CentralEventType;\n  readonly key: string | undefined;\n  readonly handler: (event: CentralEvent) => void | Promise<void>;\n  readonly priority: EventPriority;\n  /** Monotonically increasing id used as a stable insertion-order tiebreak. */\n  readonly seq: number;\n}\n\nconst NOOP_LOGGER: EventBusLogger = {\n  error: () => {\n    /* no-op */\n  },\n};\n\nexport class EventBus {\n  private readonly logger: EventBusLogger;\n  private readonly subscriptions = new Set<Subscription>();\n  private seq = 0;\n\n  public constructor(options: EventBusOptions = {}) {\n    this.logger = options.logger ?? NOOP_LOGGER;\n  }\n\n  /** Number of active subscriptions. */\n  public get subscriptionCount(): number {\n    return this.subscriptions.size;\n  }\n\n  /**\n   * Subscribe to events of a given type (optionally filtered by key).\n   * Returns an unsubscribe function.\n   */\n  public subscribe<T extends CentralEventType>(opts: SubscribeOptions<T>): () => void {\n    const subscription: Subscription = {\n      type: opts.type,\n      key: opts.key,\n      // The cast narrows the generic handler to the erased union shape; it is\n      // sound because we only ever invoke it with an event of `opts.type`.\n      handler: opts.handler as (event: CentralEvent) => void | Promise<void>,\n      priority: opts.priority ?? EventPriority.NORMAL,\n      seq: this.seq++,\n    };\n    this.subscriptions.add(subscription);\n    return () => {\n      this.subscriptions.delete(subscription);\n    };\n  }\n\n  /** Publish a single event to all matching handlers. */\n  public async publish(event: CentralEvent): Promise<void> {\n    const naturalKey = eventKey(event);\n    const matching = [...this.subscriptions]\n      .filter((sub) => sub.type === event.type && (sub.key === undefined || sub.key === naturalKey))\n      .sort((a, b) => a.priority - b.priority || a.seq - b.seq);\n\n    if (matching.length === 0) return;\n\n    const results = await Promise.allSettled(matching.map(async (sub) => sub.handler(event)));\n    for (let i = 0; i < results.length; i++) {\n      const result = results[i];\n      if (result && result.status === 'rejected') {\n        this.logger.error(`Event handler for \"${event.type}\" failed`, result.reason);\n      }\n    }\n  }\n\n  /** Publish a batch of events sequentially. */\n  public async publishBatch(events: CentralEvent[]): Promise<void> {\n    for (const event of events) {\n      await this.publish(event);\n    }\n  }\n\n  /** Remove all subscriptions. */\n  public clear(): void {\n    this.subscriptions.clear();\n  }\n}\n","/**\n * Immutable device registry.\n *\n * Holds the device graph keyed by device address and answers lookups used by\n * value routing (channel + parameter resolution by dpk).\n *\n * Immutability choice: per the project's immutability rules, callers only ever\n * see readonly snapshots — {@link DeviceNode}s are deeply readonly and\n * {@link DeviceRegistry.getAll} returns a fresh array copy, so external code\n * cannot mutate registry state. The single, controlled exception is the private\n * internal `Map`, which is mutated copy-on-write per device (`upsert` replaces a\n * whole node, `removeDevice` drops one) — this is the documented performance\n * trade-off versus rebuilding the entire registry object on every change.\n */\n\nimport type { DeviceNode, ChannelNode, ParameterSpec } from './graph.js';\nimport type { DataPointKey } from '../support/dpk.js';\n\nconst CHANNEL_SEPARATOR = ':';\n\nexport class DeviceRegistry {\n  /** Internal address → node map. Never exposed directly. */\n  private readonly devices = new Map<string, DeviceNode>();\n\n  /** A snapshot array of all devices (a copy; mutating it is harmless). */\n  public getAll(): DeviceNode[] {\n    return [...this.devices.values()];\n  }\n\n  /** Get a device by its address. */\n  public get(address: string): DeviceNode | undefined {\n    return this.devices.get(address);\n  }\n\n  /**\n   * Resolve a channel by its full address (`DEV:idx`). The parent device is\n   * found by stripping the last `:`-segment; returns `undefined` for addresses\n   * without a channel suffix or for unknown devices/channels.\n   */\n  public getChannel(channelAddress: string): ChannelNode | undefined {\n    const lastColon = channelAddress.lastIndexOf(CHANNEL_SEPARATOR);\n    if (lastColon < 0) return undefined;\n    const deviceAddress = channelAddress.slice(0, lastColon);\n    const device = this.devices.get(deviceAddress);\n    if (device === undefined) return undefined;\n    return device.channels.find((channel) => channel.address === channelAddress);\n  }\n\n  /**\n   * Resolve the {@link ParameterSpec} addressed by a dpk: device → channel\n   * (`dpk.channelAddress`) → parameter (`dpk.parameter`) → spec for\n   * `dpk.paramsetKey`. Returns `undefined` if any hop is missing.\n   */\n  public resolveParameter(dpk: DataPointKey): ParameterSpec | undefined {\n    const channel = this.getChannel(dpk.channelAddress);\n    if (channel === undefined) return undefined;\n    const specs = channel.parameters.get(dpk.parameter);\n    if (specs === undefined) return undefined;\n    if (dpk.paramsetKey === 'VALUES') return specs.VALUES;\n    if (dpk.paramsetKey === 'MASTER') return specs.MASTER;\n    return undefined;\n  }\n\n  /** Insert or replace a device (by address). */\n  public upsert(device: DeviceNode): void {\n    this.devices.set(device.address, device);\n  }\n\n  /** Remove a device; its channels are part of the node and go with it. */\n  public removeDevice(address: string): void {\n    this.devices.delete(address);\n  }\n}\n","/**\n * Persistent description caches: device descriptions and paramset descriptions.\n *\n * Both caches share the same persistence machinery:\n *  - A `{ schemaVersion, data }` envelope on disk. On load, a mismatched\n *    `schemaVersion` (or any parse failure) discards the on-disk data and the\n *    cache stays empty — invalidation is by SCHEMA VERSION, never by age.\n *  - A deterministic, key-sorted JSON serialization so the sha256 `contentHash`\n *    is stable across insertion order; `saveIfChanged` only writes when the\n *    hash differs from the last saved one.\n *\n * The caches store the raw transport-layer shapes (`DeviceDescription`,\n * `ParameterData`); the graph/model layer derives typed nodes from them.\n */\n\nimport { createHash } from 'node:crypto';\nimport type { StorageBackend } from './storage-backend.js';\nimport type { DeviceDescription, ParameterData } from '../../transport/xmlrpc/types.js';\n\n/** Outcome of a cache {@link DescriptionCacheBase.load}. */\nexport type LoadResult = 'loaded' | 'empty' | 'version-mismatch' | 'fail';\n\n/** Persisted envelope wrapping the cache data with its schema version. */\ninterface Envelope {\n  readonly schemaVersion: number;\n  readonly data: unknown;\n}\n\n/** Recursively serialize a value with object keys sorted, for a stable hash. */\nfunction stableStringify(value: unknown): string {\n  if (value === null || typeof value !== 'object') {\n    return JSON.stringify(value) ?? 'null';\n  }\n  if (Array.isArray(value)) {\n    return `[${value.map(stableStringify).join(',')}]`;\n  }\n  const record = value as Record<string, unknown>;\n  const keys = Object.keys(record).sort();\n  const entries = keys.map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`);\n  return `{${entries.join(',')}}`;\n}\n\n/** Shared persistence/hash/version machinery for the description caches. */\nabstract class DescriptionCacheBase<TData> {\n  protected abstract readonly schemaVersion: number;\n  private lastSavedHash: string | null = null;\n\n  protected constructor(\n    private readonly backend: StorageBackend,\n    private readonly fileName: string,\n  ) {}\n\n  /**\n   * Seed the \"last saved\" baseline to the current (empty) content so a pristine\n   * cache reports no unsaved changes. Subclasses MUST call this once their data\n   * fields are initialised (the base constructor cannot, as it runs before the\n   * subclass field initialisers).\n   */\n  protected seedBaseline(): void {\n    this.lastSavedHash = this.contentHash();\n  }\n\n  /** Snapshot of the in-memory data in a JSON-serializable form. */\n  protected abstract toData(): TData;\n\n  /** Replace the in-memory data from a previously persisted snapshot. */\n  protected abstract fromData(data: unknown): void;\n\n  /** Reset the in-memory data to empty. */\n  protected abstract resetData(): void;\n\n  /** sha256 of the deterministic serialization of the current data. */\n  public contentHash(): string {\n    return createHash('sha256').update(stableStringify(this.toData())).digest('hex');\n  }\n\n  /** True if the current content differs from the last persisted snapshot. */\n  public get hasUnsavedChanges(): boolean {\n    return this.contentHash() !== this.lastSavedHash;\n  }\n\n  /**\n   * Load the cache from the backend. On version mismatch or parse failure the\n   * cache is left empty and the corresponding status is returned.\n   */\n  public async load(): Promise<LoadResult> {\n    const raw = await this.backend.load(this.fileName);\n    if (raw === null) return 'empty';\n    let envelope: Envelope;\n    try {\n      envelope = JSON.parse(raw) as Envelope;\n    } catch {\n      this.resetData();\n      return 'fail';\n    }\n    if (\n      typeof envelope !== 'object' ||\n      envelope === null ||\n      typeof envelope.schemaVersion !== 'number'\n    ) {\n      this.resetData();\n      return 'fail';\n    }\n    if (envelope.schemaVersion !== this.schemaVersion) {\n      this.resetData();\n      return 'version-mismatch';\n    }\n    try {\n      this.fromData(envelope.data);\n    } catch {\n      this.resetData();\n      return 'fail';\n    }\n    this.lastSavedHash = this.contentHash();\n    return 'loaded';\n  }\n\n  /** Persist the cache unconditionally. */\n  public async saveAll(): Promise<void> {\n    const envelope: Envelope = { schemaVersion: this.schemaVersion, data: this.toData() };\n    await this.backend.save(this.fileName, JSON.stringify(envelope));\n    this.lastSavedHash = this.contentHash();\n  }\n\n  /** Persist only if the content hash changed since the last save. */\n  public async saveIfChanged(): Promise<void> {\n    if (this.contentHash() === this.lastSavedHash) return;\n    await this.saveAll();\n  }\n}\n\n/** Persisted shape: interfaceId → address → DeviceDescription. */\ntype DeviceData = Record<string, Record<string, DeviceDescription>>;\n\n/**\n * Cache of {@link DeviceDescription}s, keyed by interface then address.\n * Addresses include both device addresses (`VCU1`) and channel addresses\n * (`VCU1:1`).\n */\nexport class DeviceDescriptionCache extends DescriptionCacheBase<DeviceData> {\n  public static readonly SCHEMA_VERSION = 1;\n  protected readonly schemaVersion = DeviceDescriptionCache.SCHEMA_VERSION;\n\n  private byInterface = new Map<string, Map<string, DeviceDescription>>();\n\n  public constructor(backend: StorageBackend, fileName: string) {\n    super(backend, fileName);\n    this.seedBaseline();\n  }\n\n  /** Add or replace a description for `desc.ADDRESS` under `interfaceId`. */\n  public add(interfaceId: string, desc: DeviceDescription): void {\n    let forIface = this.byInterface.get(interfaceId);\n    if (forIface === undefined) {\n      forIface = new Map<string, DeviceDescription>();\n      this.byInterface.set(interfaceId, forIface);\n    }\n    forIface.set(desc.ADDRESS, desc);\n  }\n\n  /** Get a single description by interface and address. */\n  public get(interfaceId: string, address: string): DeviceDescription | undefined {\n    return this.byInterface.get(interfaceId)?.get(address);\n  }\n\n  /** All descriptions for an interface (devices and channels). */\n  public getAll(interfaceId: string): DeviceDescription[] {\n    const forIface = this.byInterface.get(interfaceId);\n    return forIface === undefined ? [] : [...forIface.values()];\n  }\n\n  /** All known interface ids. */\n  public getAllInterfaces(): string[] {\n    return [...this.byInterface.keys()];\n  }\n\n  /** Remove a device and all of its channel addresses (`address:*`). */\n  public removeDevice(interfaceId: string, address: string): void {\n    const forIface = this.byInterface.get(interfaceId);\n    if (forIface === undefined) return;\n    const channelPrefix = `${address}:`;\n    for (const key of [...forIface.keys()]) {\n      if (key === address || key.startsWith(channelPrefix)) {\n        forIface.delete(key);\n      }\n    }\n  }\n\n  protected toData(): DeviceData {\n    const data: DeviceData = {};\n    for (const [iface, forIface] of this.byInterface) {\n      const addresses: Record<string, DeviceDescription> = {};\n      for (const [address, desc] of forIface) {\n        addresses[address] = desc;\n      }\n      data[iface] = addresses;\n    }\n    return data;\n  }\n\n  protected fromData(data: unknown): void {\n    const next = new Map<string, Map<string, DeviceDescription>>();\n    const record = (data ?? {}) as Record<string, Record<string, DeviceDescription>>;\n    for (const [iface, addresses] of Object.entries(record)) {\n      const forIface = new Map<string, DeviceDescription>();\n      for (const [address, desc] of Object.entries(addresses)) {\n        forIface.set(address, desc);\n      }\n      next.set(iface, forIface);\n    }\n    this.byInterface = next;\n  }\n\n  protected resetData(): void {\n    this.byInterface = new Map<string, Map<string, DeviceDescription>>();\n  }\n}\n\n/** A paramset is a record of parameter name → its {@link ParameterData}. */\ntype Paramset = Record<string, ParameterData>;\n/** Persisted shape: interfaceId → channelAddress → paramsetKey → Paramset. */\ntype ParamsetData = Record<string, Record<string, Record<string, Paramset>>>;\n\n/**\n * Cache of paramset descriptions, keyed by interface → channel address →\n * paramset key → parameter → {@link ParameterData}.\n */\nexport class ParamsetDescriptionCache extends DescriptionCacheBase<ParamsetData> {\n  public static readonly SCHEMA_VERSION = 1;\n  protected readonly schemaVersion = ParamsetDescriptionCache.SCHEMA_VERSION;\n\n  private byInterface = new Map<string, Map<string, Map<string, Paramset>>>();\n\n  public constructor(backend: StorageBackend, fileName: string) {\n    super(backend, fileName);\n    this.seedBaseline();\n  }\n\n  private paramsetMap(interfaceId: string, channelAddress: string): Map<string, Paramset> {\n    let forIface = this.byInterface.get(interfaceId);\n    if (forIface === undefined) {\n      forIface = new Map<string, Map<string, Paramset>>();\n      this.byInterface.set(interfaceId, forIface);\n    }\n    let forChannel = forIface.get(channelAddress);\n    if (forChannel === undefined) {\n      forChannel = new Map<string, Paramset>();\n      forIface.set(channelAddress, forChannel);\n    }\n    return forChannel;\n  }\n\n  /** Add a single parameter's data into a paramset. */\n  public add(\n    interfaceId: string,\n    channelAddress: string,\n    paramsetKey: string,\n    parameter: string,\n    data: ParameterData,\n  ): void {\n    const forChannel = this.paramsetMap(interfaceId, channelAddress);\n    const existing = forChannel.get(paramsetKey);\n    forChannel.set(paramsetKey, { ...(existing ?? {}), [parameter]: data });\n  }\n\n  /** Add or replace a whole paramset record at once. */\n  public addParamset(\n    interfaceId: string,\n    channelAddress: string,\n    paramsetKey: string,\n    paramset: Paramset,\n  ): void {\n    this.paramsetMap(interfaceId, channelAddress).set(paramsetKey, { ...paramset });\n  }\n\n  /** Get a paramset record (parameter → data) for a channel, or undefined. */\n  public getParamset(\n    interfaceId: string,\n    channelAddress: string,\n    paramsetKey: string,\n  ): Paramset | undefined {\n    return this.byInterface.get(interfaceId)?.get(channelAddress)?.get(paramsetKey);\n  }\n\n  /** The paramset keys known for a channel. */\n  public getParamsetKeys(interfaceId: string, channelAddress: string): string[] {\n    const forChannel = this.byInterface.get(interfaceId)?.get(channelAddress);\n    return forChannel === undefined ? [] : [...forChannel.keys()];\n  }\n\n  /**\n   * Remove all paramsets for a device: the channel equal to `address` (its\n   * own MASTER paramset) and every channel `address:*`.\n   */\n  public removeDevice(interfaceId: string, address: string): void {\n    const forIface = this.byInterface.get(interfaceId);\n    if (forIface === undefined) return;\n    const channelPrefix = `${address}:`;\n    for (const channelAddress of [...forIface.keys()]) {\n      if (channelAddress === address || channelAddress.startsWith(channelPrefix)) {\n        forIface.delete(channelAddress);\n      }\n    }\n  }\n\n  protected toData(): ParamsetData {\n    const data: ParamsetData = {};\n    for (const [iface, forIface] of this.byInterface) {\n      const channels: Record<string, Record<string, Paramset>> = {};\n      for (const [channelAddress, forChannel] of forIface) {\n        const paramsets: Record<string, Paramset> = {};\n        for (const [paramsetKey, paramset] of forChannel) {\n          paramsets[paramsetKey] = paramset;\n        }\n        channels[channelAddress] = paramsets;\n      }\n      data[iface] = channels;\n    }\n    return data;\n  }\n\n  protected fromData(data: unknown): void {\n    const next = new Map<string, Map<string, Map<string, Paramset>>>();\n    const record = (data ?? {}) as ParamsetData;\n    for (const [iface, channels] of Object.entries(record)) {\n      const forIface = new Map<string, Map<string, Paramset>>();\n      for (const [channelAddress, paramsets] of Object.entries(channels)) {\n        const forChannel = new Map<string, Paramset>();\n        for (const [paramsetKey, paramset] of Object.entries(paramsets)) {\n          forChannel.set(paramsetKey, paramset);\n        }\n        forIface.set(channelAddress, forChannel);\n      }\n      next.set(iface, forIface);\n    }\n    this.byInterface = next;\n  }\n\n  protected resetData(): void {\n    this.byInterface = new Map<string, Map<string, Map<string, Paramset>>>();\n  }\n}\n","/**\n * Dynamic in-memory value cache.\n *\n * Holds the latest value received for each data point, keyed by the dpk's\n * stable `unique_id`. Staleness is computed against an injected clock so the\n * scheduler and tests stay deterministic; the default freshness window is 10s\n * (the production `MAX_CACHE_AGE`). This cache is volatile and never persisted.\n */\n\nimport { dpkToUniqueId, type DataPointKey } from '../../support/dpk.js';\n\n/** Default freshness window in milliseconds (production `MAX_CACHE_AGE`). */\nexport const DEFAULT_MAX_CACHE_AGE_MS = 10_000;\n\n/** A cached value together with the time it was recorded. */\nexport interface CachedValue {\n  readonly value: unknown;\n  /** Epoch/monotonic millis when the value was recorded. */\n  readonly at: number;\n}\n\n/** In-memory latest-value store keyed by dpk unique id. */\nexport class ValueCache {\n  private readonly store = new Map<string, CachedValue>();\n\n  /** Record a value for a data point at time `at`. */\n  public add(dpk: DataPointKey, value: unknown, at: number): void {\n    this.store.set(dpkToUniqueId(dpk), { value, at });\n  }\n\n  /** Return the cached value for a data point, or `undefined` if absent. */\n  public get(dpk: DataPointKey): CachedValue | undefined {\n    return this.store.get(dpkToUniqueId(dpk));\n  }\n\n  /**\n   * True if the entry is missing or older than `maxAgeMs` relative to `now`.\n   * Unknown entries are always considered stale.\n   */\n  public isStale(\n    dpk: DataPointKey,\n    maxAgeMs: number = DEFAULT_MAX_CACHE_AGE_MS,\n    now: number = Date.now(),\n  ): boolean {\n    const entry = this.store.get(dpkToUniqueId(dpk));\n    if (entry === undefined) return true;\n    return now - entry.at > maxAgeMs;\n  }\n\n  /** Remove all cached values. */\n  public clear(): void {\n    this.store.clear();\n  }\n\n  /** Iterate `[uniqueId, CachedValue]` pairs. */\n  public entries(): IterableIterator<readonly [string, CachedValue]> {\n    return this.store.entries();\n  }\n}\n","/**\n * Pluggable persistence backend for the central's caches.\n *\n * The central never touches the filesystem directly; it persists named blobs\n * through a {@link StorageBackend}. Tests inject {@link InMemoryStorageBackend}\n * so they stay fast and hermetic; production uses {@link FileStorageBackend}.\n */\n\nimport { mkdir, readFile, writeFile, rm } from 'node:fs/promises';\nimport { join } from 'node:path';\n\n/** Persistence contract for named JSON blobs. */\nexport interface StorageBackend {\n  /** Load a blob by logical name, or `null` if it does not exist. */\n  load(name: string): Promise<string | null>;\n  /** Persist a blob under a logical name (overwrites). */\n  save(name: string, content: string): Promise<void>;\n  /** Remove a blob by name; a no-op if it is already absent. */\n  remove(name: string): Promise<void>;\n}\n\n/**\n * Normalise an arbitrary string into a filesystem-safe slug: lowercased with\n * every run of non-alphanumeric characters collapsed to a single underscore.\n */\nexport function slug(value: string): string {\n  return value.toLowerCase().replace(/[^a-z0-9]/g, '_');\n}\n\n/** Constructor options for {@link FileStorageBackend}. */\nexport interface FileStorageBackendOptions {\n  /** Directory where cache files live; created on first write. */\n  readonly dir: string;\n  /** Central name; slugged into each filename to namespace by central. */\n  readonly centralName: string;\n}\n\n/**\n * File-backed storage. Files are written as `${slug(centralName)}_${name}.json`\n * inside the configured directory, which is created on demand.\n */\nexport class FileStorageBackend implements StorageBackend {\n  private readonly dir: string;\n  private readonly prefix: string;\n\n  public constructor(options: FileStorageBackendOptions) {\n    this.dir = options.dir;\n    this.prefix = slug(options.centralName);\n  }\n\n  private fileFor(name: string): string {\n    return join(this.dir, `${this.prefix}_${name}.json`);\n  }\n\n  public async load(name: string): Promise<string | null> {\n    try {\n      return await readFile(this.fileFor(name), 'utf-8');\n    } catch (err: unknown) {\n      if (isNotFound(err)) return null;\n      throw err;\n    }\n  }\n\n  public async save(name: string, content: string): Promise<void> {\n    await mkdir(this.dir, { recursive: true });\n    await writeFile(this.fileFor(name), content, 'utf-8');\n  }\n\n  public async remove(name: string): Promise<void> {\n    await rm(this.fileFor(name), { force: true });\n  }\n}\n\nfunction isNotFound(err: unknown): boolean {\n  return typeof err === 'object' && err !== null && (err as { code?: unknown }).code === 'ENOENT';\n}\n\n/** In-memory storage backed by a `Map`; intended for tests. */\nexport class InMemoryStorageBackend implements StorageBackend {\n  private readonly store = new Map<string, string>();\n\n  public load(name: string): Promise<string | null> {\n    return Promise.resolve(this.store.get(name) ?? null);\n  }\n\n  public save(name: string, content: string): Promise<void> {\n    this.store.set(name, content);\n    return Promise.resolve();\n  }\n\n  public remove(name: string): Promise<void> {\n    this.store.delete(name);\n    return Promise.resolve();\n  }\n}\n","/**\n * Immutable device graph model.\n *\n * The graph is raw, typed protocol data — NOT domain model (that is a later\n * phase). A {@link DeviceNode} carries its channels; each {@link ChannelNode}\n * carries the typed {@link ParameterSpec}s derived from the raw paramset\n * descriptions. All shapes are deeply readonly so consumers cannot mutate the\n * graph in place.\n */\n\nimport {\n  ParameterType,\n  isReadable,\n  isWritable,\n  hasEvents,\n  isVisible,\n} from '../support/constants.js';\nimport type { DeviceDescription, ParameterData } from '../transport/xmlrpc/types.js';\n\n/**\n * A typed view of a single parameter, derived from raw {@link ParameterData}.\n * `operations`/`flags` are the raw bitmasks; the booleans are their decoded\n * gating, computed via the shared constant helpers.\n */\nexport interface ParameterSpec {\n  readonly type: ParameterType;\n  readonly operations: number;\n  readonly flags: number;\n  readonly min?: number;\n  readonly max?: number;\n  readonly default?: unknown;\n  readonly unit?: string;\n  readonly valueList?: readonly string[];\n  readonly special?: unknown;\n  readonly readable: boolean;\n  readonly writable: boolean;\n  readonly hasEvents: boolean;\n  readonly visible: boolean;\n}\n\n/** Coerce a raw `TYPE` string to a {@link ParameterType}, defaulting to EMPTY. */\nfunction toParameterType(raw: string): ParameterType {\n  return (Object.values(ParameterType) as string[]).includes(raw)\n    ? (raw as ParameterType)\n    : ParameterType.EMPTY;\n}\n\n/** Build a {@link ParameterSpec} from raw {@link ParameterData}. */\nexport function parameterSpecFromData(data: ParameterData): ParameterSpec {\n  const operations = data.OPERATIONS ?? 0;\n  const flags = data.FLAGS ?? 0;\n  const spec: ParameterSpec = {\n    type: toParameterType(data.TYPE),\n    operations,\n    flags,\n    readable: isReadable(operations),\n    writable: isWritable(operations),\n    hasEvents: hasEvents(operations),\n    visible: isVisible(flags),\n    // Optional fields are only present when supplied (exactOptionalPropertyTypes).\n    // min/max are narrowed to a number at construction; non-numeric CCU values\n    // (the type allows any XmlRpcValue) are dropped so the spec type holds.\n    ...(typeof data.MIN === 'number' ? { min: data.MIN } : {}),\n    ...(typeof data.MAX === 'number' ? { max: data.MAX } : {}),\n    ...(data.DEFAULT !== undefined ? { default: data.DEFAULT } : {}),\n    ...(data.UNIT !== undefined ? { unit: data.UNIT } : {}),\n    ...(data.VALUE_LIST !== undefined ? { valueList: data.VALUE_LIST } : {}),\n    ...(data.SPECIAL !== undefined ? { special: data.SPECIAL } : {}),\n  };\n  return spec;\n}\n\n/** The typed specs for one parameter across its paramsets. */\nexport interface ParameterSpecs {\n  readonly VALUES?: ParameterSpec;\n  readonly MASTER?: ParameterSpec;\n}\n\n/** A channel of a device, with its parameters keyed by parameter name. */\nexport interface ChannelNode {\n  readonly address: string;\n  readonly index: number;\n  readonly type?: string;\n  readonly direction?: number;\n  /** CCU user-given name (`Device.listAllDetail`). Absent when the CCU has none. */\n  readonly name?: string;\n  readonly parameters: ReadonlyMap<string, ParameterSpecs>;\n}\n\n/** A device, carrying its channels plus the merged JSON-RPC metadata. */\nexport interface DeviceNode {\n  readonly address: string;\n  readonly type: string;\n  readonly interfaceId: string;\n  /** Installed firmware version, e.g. `1.18.24` (descriptor `FIRMWARE`). */\n  readonly firmware?: string;\n  /** Latest firmware the CCU knows of (descriptor `AVAILABLE_FIRMWARE`). */\n  readonly availableFirmware?: string;\n  /** Whether a firmware update can be installed (descriptor `UPDATABLE`). */\n  readonly updatable?: boolean;\n  /** Update lifecycle state, e.g. `UP_TO_DATE` (descriptor `FIRMWARE_UPDATE_STATE`). */\n  readonly firmwareUpdateState?: string;\n  readonly name?: string;\n  readonly rooms?: readonly string[];\n  readonly functions?: readonly string[];\n  readonly channels: readonly ChannelNode[];\n  readonly raw: DeviceDescription;\n}\n","/**\n * Device discovery for a single CCU interface.\n *\n * The discovery sequence (mirrors aiohomematic):\n *  1. `listDevices()` → entries that are either devices (no PARENT) or channels\n *     (PARENT = device address). Each entry is stored in the device cache.\n *  2. For each CHANNEL entry, fetch its `VALUES` and `MASTER` paramset\n *     descriptions (SKIP `LINK` and any other paramset key) and store them in\n *     the paramset cache.\n *  3. Optionally merge human-facing metadata (names, rooms, functions) fetched\n *     from the CCU WebUI over JSON-RPC.\n *  4. Build an immutable {@link DeviceNode}[] from the populated caches.\n *\n * `warmStart` rebuilds the graph purely from already-populated caches without\n * issuing any source calls — used on a cache hit at start-up.\n *\n * All raw protocol data crosses a trust boundary: JSON-RPC responses are typed\n * as `unknown` and narrowed defensively with the helpers at the bottom of this\n * file. We never throw on a missing field; we extract what is present and skip\n * the rest.\n */\n\nimport { ParamsetKey } from '../support/constants.js';\nimport type { DeviceDescription, ParameterData } from '../transport/xmlrpc/types.js';\nimport type {\n  DeviceDescriptionCache,\n  ParamsetDescriptionCache,\n} from './store/description-cache.js';\nimport {\n  parameterSpecFromData,\n  type ChannelNode,\n  type DeviceNode,\n  type ParameterSpec,\n  type ParameterSpecs,\n} from './graph.js';\nimport { JsonRpcMethod } from '../transport/jsonrpc/methods.js';\n\n/**\n * The minimal slice of an interface client that discovery needs. The Phase 1\n * {@link import('../transport/interface-client.js').InterfaceClient} satisfies\n * this shape structurally, so tests can inject a lightweight fake.\n */\nexport interface DiscoverySource {\n  readonly interfaceId: string;\n  listDevices(): Promise<DeviceDescription[]>;\n  getParamsetDescription(\n    channelAddress: string,\n    paramsetKey: string,\n  ): Promise<Record<string, ParameterData>>;\n}\n\n/** The minimal JSON-RPC client slice needed to fetch device details. */\nexport interface DetailsJsonRpcClient {\n  post(\n    method: string,\n    params?: Record<string, unknown>,\n    opts?: { readonly sessionId?: string },\n  ): Promise<unknown>;\n}\n\n/**\n * Human-facing metadata merged into the graph, keyed by device OR channel\n * address. Rooms/functions are usually attached to channel addresses by the\n * CCU; consumers can look up either level.\n */\nexport type DeviceDetails = {\n  readonly nameByAddress: ReadonlyMap<string, string>;\n  readonly roomsByAddress: ReadonlyMap<string, readonly string[]>;\n  readonly functionsByAddress: ReadonlyMap<string, readonly string[]>;\n};\n\n/** Paramset keys discovery fetches and stores; everything else is skipped. */\nconst FETCHED_PARAMSET_KEYS: readonly string[] = [ParamsetKey.VALUES, ParamsetKey.MASTER];\n\n/** True when a description entry represents a device (no parent). */\nfunction isDeviceEntry(entry: DeviceDescription): boolean {\n  return entry.PARENT === undefined || entry.PARENT === '';\n}\n\n/** Parse the channel index from a `DEV:idx` address; 0 when there is no suffix. */\nfunction channelIndexOf(address: string): number {\n  const colon = address.lastIndexOf(':');\n  if (colon === -1) return 0;\n  const parsed = Number.parseInt(address.slice(colon + 1), 10);\n  return Number.isNaN(parsed) ? 0 : parsed;\n}\n\n/** Run discovery against a live source, populating both caches and the graph. */\nexport async function discoverInterface(opts: {\n  readonly source: DiscoverySource;\n  readonly deviceCache: DeviceDescriptionCache;\n  readonly paramsetCache: ParamsetDescriptionCache;\n  readonly details?: DeviceDetails;\n}): Promise<DeviceNode[]> {\n  const { source, deviceCache, paramsetCache, details } = opts;\n  const interfaceId = source.interfaceId;\n\n  const entries = await source.listDevices();\n\n  // 1. Cache every entry (devices and channels alike).\n  for (const entry of entries) {\n    if (typeof entry.ADDRESS !== 'string' || entry.ADDRESS === '') continue;\n    deviceCache.add(interfaceId, entry);\n  }\n\n  // 2. For each channel, fetch + cache its VALUES/MASTER paramsets (skip LINK).\n  for (const entry of entries) {\n    if (isDeviceEntry(entry)) continue;\n    const channelAddress = entry.ADDRESS;\n    if (typeof channelAddress !== 'string' || channelAddress === '') continue;\n    const paramsets = entry.PARAMSETS ?? [];\n    for (const key of paramsets) {\n      if (!FETCHED_PARAMSET_KEYS.includes(key)) continue;\n      const ps = await source.getParamsetDescription(channelAddress, key);\n      paramsetCache.addParamset(interfaceId, channelAddress, key, ps);\n    }\n  }\n\n  // 3 + 4. Build the graph from the now-populated caches.\n  return buildGraph({ interfaceId, deviceCache, paramsetCache, ...(details ? { details } : {}) });\n}\n\n/** Rebuild the graph purely from the caches, issuing NO source calls. */\nexport function warmStart(opts: {\n  readonly interfaceId: string;\n  readonly deviceCache: DeviceDescriptionCache;\n  readonly paramsetCache: ParamsetDescriptionCache;\n  readonly details?: DeviceDetails;\n}): DeviceNode[] {\n  return buildGraph(opts);\n}\n\n/** Construct {@link DeviceNode}[] from cached descriptions + paramsets + details. */\nfunction buildGraph(opts: {\n  readonly interfaceId: string;\n  readonly deviceCache: DeviceDescriptionCache;\n  readonly paramsetCache: ParamsetDescriptionCache;\n  readonly details?: DeviceDetails;\n}): DeviceNode[] {\n  const { interfaceId, deviceCache, paramsetCache, details } = opts;\n  const all = deviceCache.getAll(interfaceId);\n\n  const devices = all.filter(isDeviceEntry);\n  const channelsByParent = new Map<string, DeviceDescription[]>();\n  for (const entry of all) {\n    if (isDeviceEntry(entry)) continue;\n    const parent = entry.PARENT;\n    if (typeof parent !== 'string' || parent === '') continue;\n    const list = channelsByParent.get(parent);\n    if (list === undefined) channelsByParent.set(parent, [entry]);\n    else list.push(entry);\n  }\n\n  const nodes: DeviceNode[] = [];\n  for (const device of devices) {\n    const address = device.ADDRESS;\n    if (typeof address !== 'string' || address === '') continue;\n\n    const channelAddresses = collectChannelAddresses(device, channelsByParent.get(address) ?? []);\n    const channels: ChannelNode[] = [];\n    for (const channelAddress of channelAddresses) {\n      const desc = deviceCache.get(interfaceId, channelAddress);\n      channels.push(buildChannel(interfaceId, channelAddress, desc, paramsetCache, details));\n    }\n\n    nodes.push(buildDevice(interfaceId, device, channels, details));\n  }\n  return nodes;\n}\n\n/** Union of a device's CHILDREN and the channels whose PARENT points to it. */\nfunction collectChannelAddresses(\n  device: DeviceDescription,\n  childEntries: readonly DeviceDescription[],\n): string[] {\n  const seen = new Set<string>();\n  const ordered: string[] = [];\n  const push = (addr: unknown): void => {\n    if (typeof addr !== 'string' || addr === '' || seen.has(addr)) return;\n    seen.add(addr);\n    ordered.push(addr);\n  };\n  for (const child of device.CHILDREN ?? []) push(child);\n  for (const entry of childEntries) push(entry.ADDRESS);\n  return ordered;\n}\n\n/** Build a single {@link ChannelNode} from its description + cached paramsets. */\nfunction buildChannel(\n  interfaceId: string,\n  channelAddress: string,\n  desc: DeviceDescription | undefined,\n  paramsetCache: ParamsetDescriptionCache,\n  details: DeviceDetails | undefined,\n): ChannelNode {\n  const parameters = new Map<string, ParameterSpecs>();\n  for (const key of FETCHED_PARAMSET_KEYS) {\n    const paramset = paramsetCache.getParamset(interfaceId, channelAddress, key);\n    if (paramset === undefined) continue;\n    for (const [parameter, data] of Object.entries(paramset)) {\n      const spec = parameterSpecFromData(data);\n      mergeSpec(parameters, parameter, key, spec);\n    }\n  }\n\n  const name = details?.nameByAddress.get(channelAddress);\n  const node: ChannelNode = {\n    address: channelAddress,\n    index: channelIndexOf(channelAddress),\n    parameters,\n    ...(desc?.TYPE !== undefined ? { type: desc.TYPE } : {}),\n    ...(desc?.DIRECTION !== undefined ? { direction: desc.DIRECTION } : {}),\n    // Channel names come from the same `Device.listAllDetail` map as the device\n    // name (keyed by channel address). Rooms/functions stay on the device node.\n    ...(name !== undefined ? { name } : {}),\n  };\n  return node;\n}\n\n/** Attach a spec to the per-parameter VALUES/MASTER record, preserving the other. */\nfunction mergeSpec(\n  parameters: Map<string, ParameterSpecs>,\n  parameter: string,\n  key: string,\n  spec: ParameterSpec,\n): void {\n  const existing = parameters.get(parameter) ?? {};\n  if (key === (ParamsetKey.VALUES as string)) {\n    parameters.set(parameter, { ...existing, VALUES: spec });\n  } else if (key === (ParamsetKey.MASTER as string)) {\n    parameters.set(parameter, { ...existing, MASTER: spec });\n  }\n}\n\n/** Build a {@link DeviceNode}, merging in details when present. */\nfunction buildDevice(\n  interfaceId: string,\n  device: DeviceDescription,\n  channels: readonly ChannelNode[],\n  details: DeviceDetails | undefined,\n): DeviceNode {\n  const address = device.ADDRESS;\n  const name = details?.nameByAddress.get(address);\n  const rooms = details?.roomsByAddress.get(address);\n  const functions = details?.functionsByAddress.get(address);\n\n  // Real CCUs key device-update availability as `UPDATABLE`; tolerate the\n  // legacy `FIRMWARE_UPDATABLE` alias too. Both are booleans (XML-RPC 1/0).\n  const updatable = device.UPDATABLE ?? device.FIRMWARE_UPDATABLE;\n\n  const node: DeviceNode = {\n    address,\n    type: device.TYPE,\n    interfaceId,\n    channels,\n    raw: device,\n    ...(device.FIRMWARE !== undefined ? { firmware: device.FIRMWARE } : {}),\n    ...(device.AVAILABLE_FIRMWARE !== undefined\n      ? { availableFirmware: device.AVAILABLE_FIRMWARE }\n      : {}),\n    ...(updatable !== undefined ? { updatable } : {}),\n    ...(device.FIRMWARE_UPDATE_STATE !== undefined\n      ? { firmwareUpdateState: device.FIRMWARE_UPDATE_STATE }\n      : {}),\n    ...(name !== undefined ? { name } : {}),\n    ...(rooms !== undefined && rooms.length > 0 ? { rooms } : {}),\n    ...(functions !== undefined && functions.length > 0 ? { functions } : {}),\n  };\n  return node;\n}\n\n// ---------------------------------------------------------------------------\n// JSON-RPC details merge.\n//\n// IMPORTANT: the exact CCU JSON-RPC response shapes below are documented from\n// aiohomematic + the RaspberryMatic WebUI and are only fully verifiable against\n// real hardware. The parsing is deliberately defensive — every field is\n// optional and a missing/oddly-typed field is skipped, never thrown on.\n// ---------------------------------------------------------------------------\n\n/**\n * Fetch and merge device/room/function metadata over JSON-RPC.\n *\n * Real CCU response shapes (confirmed against hardware):\n *  - `Device.listAllDetail` → array of\n *    `{ id, name, address, interface, type, channels: [{ id, name, address, index, channelType, ... }] }`.\n *    Device name is keyed by the device `address`; each channel has BOTH a\n *    numeric `id` (string) and an `address` (e.g. `001B9D89A09163:0`). We map\n *    both device- and channel-level `address → name`, and build a\n *    `channelId → channelAddress` index used to resolve rooms/functions.\n *  - `Room.getAll` → array of `{ id, name, description, channelIds: string[] }`\n *    where `channelIds` are the numeric channel IDs (matching channel `id`),\n *    NOT addresses. Each room name is attached to its member channels'\n *    addresses AND their derived device addresses (union, deduped).\n *  - `Subsection.getAll` → same shape as rooms but represents \"functions\".\n */\nexport async function mergeDetails(\n  jsonClient: DetailsJsonRpcClient,\n  sessionId?: string,\n): Promise<DeviceDetails> {\n  const opts = sessionId !== undefined ? { sessionId } : undefined;\n\n  const nameByAddress = new Map<string, string>();\n  const channelIdToAddress = new Map<string, string>();\n  const roomsByAddress = new Map<string, string[]>();\n  const functionsByAddress = new Map<string, string[]>();\n\n  const detail = await safePost(jsonClient, JsonRpcMethod.DEVICE_LIST_ALL_DETAIL, opts);\n  for (const item of asArray(detail)) {\n    parseDeviceDetail(item, nameByAddress, channelIdToAddress);\n  }\n\n  const rooms = await safePost(jsonClient, JsonRpcMethod.ROOM_GET_ALL, opts);\n  for (const item of asArray(rooms)) {\n    parseGroup(item, channelIdToAddress, roomsByAddress);\n  }\n\n  const subsections = await safePost(jsonClient, JsonRpcMethod.SUBSECTION_GET_ALL, opts);\n  for (const item of asArray(subsections)) {\n    parseGroup(item, channelIdToAddress, functionsByAddress);\n  }\n\n  return { nameByAddress, roomsByAddress, functionsByAddress };\n}\n\n/** Post a JSON-RPC method, returning `null` (not throwing) on any failure. */\nasync function safePost(\n  jsonClient: DetailsJsonRpcClient,\n  method: string,\n  opts: { readonly sessionId?: string } | undefined,\n): Promise<unknown> {\n  try {\n    return await jsonClient.post(method, undefined, opts);\n  } catch {\n    return null;\n  }\n}\n\n/**\n * Map a single `Device.listAllDetail` entry's device + channel names AND index\n * every channel's numeric `id → address` so rooms/functions can join later.\n */\nfunction parseDeviceDetail(\n  item: unknown,\n  nameByAddress: Map<string, string>,\n  channelIdToAddress: Map<string, string>,\n): void {\n  const record = asRecord(item);\n  if (record === undefined) return;\n  const address = asString(record.address);\n  const name = asString(record.name);\n  if (address !== undefined && name !== undefined) nameByAddress.set(address, name);\n\n  for (const channel of asArray(record.channels)) {\n    const ch = asRecord(channel);\n    if (ch === undefined) continue;\n    const chAddress = asString(ch.address);\n    if (chAddress === undefined) continue;\n    const chName = asString(ch.name);\n    if (chName !== undefined) nameByAddress.set(chAddress, chName);\n    const chId = asString(ch.id);\n    if (chId !== undefined) channelIdToAddress.set(chId, chAddress);\n  }\n}\n\n/** Derive a device address from a channel address by stripping the `:index` suffix. */\nfunction deviceAddressOf(channelAddress: string): string {\n  const colon = channelAddress.lastIndexOf(':');\n  return colon === -1 ? channelAddress : channelAddress.slice(0, colon);\n}\n\n/** Append `name` to `address`'s list in `into`, deduping. */\nfunction addGroupName(into: Map<string, string[]>, address: string, name: string): void {\n  const existing = into.get(address);\n  if (existing === undefined) into.set(address, [name]);\n  else if (!existing.includes(name)) existing.push(name);\n}\n\n/**\n * Map a single room/subsection entry: its `name` is attached to every member\n * channel's ADDRESS and its derived DEVICE address. Members are numeric channel\n * `id`s in `channelIds`, resolved to addresses via `channelIdToAddress`; unknown\n * ids are skipped (no bogus entry). `channelAddresses`/`members` are accepted as\n * fallbacks and, when already address-shaped, used directly.\n */\nfunction parseGroup(\n  item: unknown,\n  channelIdToAddress: Map<string, string>,\n  into: Map<string, string[]>,\n): void {\n  const record = asRecord(item);\n  if (record === undefined) return;\n  const name = asString(record.name);\n  if (name === undefined) return;\n\n  const idMembers = asArray(record.channelIds);\n  for (const member of idMembers) {\n    const channelId = asString(member);\n    if (channelId === undefined) continue;\n    const channelAddress = channelIdToAddress.get(channelId);\n    if (channelAddress === undefined) continue; // unknown id → skip, no throw\n    addGroupName(into, channelAddress, name);\n    addGroupName(into, deviceAddressOf(channelAddress), name);\n  }\n\n  // Fallbacks for CCUs/responses that key members by address directly.\n  const addressMembers = firstArray(record.channelAddresses, record.members);\n  for (const member of addressMembers) {\n    const channelAddress = asString(member);\n    if (channelAddress === undefined) continue;\n    addGroupName(into, channelAddress, name);\n    addGroupName(into, deviceAddressOf(channelAddress), name);\n  }\n}\n\n// --- narrowing helpers (trust boundary) ------------------------------------\n\nfunction asArray(value: unknown): unknown[] {\n  return Array.isArray(value) ? value : [];\n}\n\nfunction firstArray(...candidates: readonly unknown[]): unknown[] {\n  for (const candidate of candidates) {\n    if (Array.isArray(candidate)) return candidate;\n  }\n  return [];\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> | undefined {\n  if (typeof value === 'object' && value !== null && !Array.isArray(value)) {\n    return value as Record<string, unknown>;\n  }\n  return undefined;\n}\n\nfunction asString(value: unknown): string | undefined {\n  if (typeof value === 'string' && value !== '') return value;\n  if (typeof value === 'number') return String(value);\n  return undefined;\n}\n","/**\n * System-variable domain model + value parsing.\n *\n * The CCU exposes system variables via `SysVar.getAll`, which returns a loose\n * `type` string and a stringified `value`. This module normalises the type and\n * parses the raw value into the library's {@link HmValue} domain. Pure: no I/O.\n */\nimport type { HmValue } from '../../model/converter.js';\n\n/** The CCU's system-variable value types. */\nexport enum HubValueType {\n  ALARM = 'ALARM',\n  FLOAT = 'FLOAT',\n  INTEGER = 'INTEGER',\n  LIST = 'LIST',\n  LOGIC = 'LOGIC',\n  NUMBER = 'NUMBER',\n  STRING = 'STRING',\n}\n\n/** A normalised system variable as exposed by the hub layer. */\nexport interface SystemVariable {\n  readonly id: string;\n  readonly name: string;\n  readonly type: HubValueType;\n  readonly value: HmValue;\n  readonly unit?: string;\n  readonly isInternal: boolean;\n  /** True when the description carried the `HAHM` extended-sysvar marker. */\n  readonly writable: boolean;\n  readonly valueList?: string[];\n  readonly min?: number;\n  readonly max?: number;\n}\n\nconst TRUE_TOKENS: ReadonlySet<string> = new Set(['y', 'yes', 't', 'true', 'on', '1']);\n\n/** Coerce a CCU truthiness string to a boolean (y/yes/t/true/on/1, case-insensitive). */\nexport function toBool(s: string): boolean {\n  return TRUE_TOKENS.has(s.trim().toLowerCase());\n}\n\nconst KNOWN_TYPES: ReadonlySet<string> = new Set<string>(Object.values(HubValueType));\n\n/**\n * Normalise a CCU type name to a {@link HubValueType}. A bare `NUMBER` is\n * refined to FLOAT when the raw value contains a decimal point, else INTEGER.\n * Unknown type strings fall back to STRING.\n */\nexport function normalizeType(type: string, rawValue: string): HubValueType {\n  const upper = type.trim().toUpperCase();\n  if (upper === (HubValueType.NUMBER as string)) {\n    return rawValue.includes('.') ? HubValueType.FLOAT : HubValueType.INTEGER;\n  }\n  return KNOWN_TYPES.has(upper) ? (upper as HubValueType) : HubValueType.STRING;\n}\n\n/**\n * Parse a raw CCU value string into the {@link HmValue} domain according to the\n * normalised type: ALARM/LOGIC→bool, FLOAT→number, INTEGER/LIST→int,\n * STRING/NUMBER→raw string.\n */\nexport function parseSysVarValue(type: HubValueType, raw: string): HmValue {\n  switch (type) {\n    case HubValueType.ALARM:\n    case HubValueType.LOGIC:\n      return toBool(raw);\n    case HubValueType.FLOAT:\n      return Number(raw);\n    case HubValueType.INTEGER:\n    case HubValueType.LIST:\n      return Number.parseInt(raw, 10);\n    case HubValueType.STRING:\n    case HubValueType.NUMBER:\n    default:\n      return raw;\n  }\n}\n","/**\n * Hub fetcher: system variables, programs, and the rooms/functions mapping.\n *\n * Combines JSON-RPC (`SysVar.*`, `Program.*`) with ReGa scripts (descriptions,\n * string-sysvar writes, program enable/disable, rooms/functions). All CCU\n * responses arrive as `unknown` and are narrowed defensively before use.\n */\nimport type { HmValue } from '../../model/converter.js';\nimport { ValidationError } from '../../support/errors.js';\nimport { JsonRpcMethod } from '../../transport/jsonrpc/methods.js';\nimport { decodeRegaName, runScript, type RegaPostClient } from '../rega/rega-runner.js';\nimport {\n  GET_ROOMS_FUNCTIONS,\n  SET_PROGRAM_STATE,\n  SET_SYSTEM_VARIABLE,\n  SYSVAR_DESCRIPTIONS,\n} from '../rega/scripts.js';\nimport type { HmProgramRecord } from './program.js';\nimport { normalizeType, parseSysVarValue, toBool, type SystemVariable } from './sysvar.js';\n\n/** The description marker the CCU sets on extended (writable) system variables. */\nconst WRITABLE_MARKER = 'HAHM';\n\n/**\n * Constructor dependencies. The session id is read lazily so it can rotate; an\n * async getter lets the owner ensure (log in / renew) a session per call.\n */\nexport interface HubFetcherOptions {\n  readonly client: RegaPostClient;\n  readonly getSessionId: () => string | undefined | Promise<string | undefined>;\n}\n\n/** Read an object property as `unknown` after narrowing the container. */\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === 'object';\n}\n\n/** Coerce an unknown CCU scalar to a string (used for value/type fields). */\nfunction asString(value: unknown): string {\n  if (typeof value === 'string') return value;\n  if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n  return '';\n}\n\n/** Coerce an unknown CCU flag (boolean or \"true\"/\"false\" string) to a boolean. */\nfunction asBool(value: unknown): boolean {\n  if (typeof value === 'boolean') return value;\n  if (typeof value === 'string') return toBool(value);\n  if (typeof value === 'number') return value !== 0;\n  return false;\n}\n\n/** Coerce an unknown to a finite number, or undefined. */\nfunction asOptionalNumber(value: unknown): number | undefined {\n  if (value === undefined || value === null || value === '') return undefined;\n  const num = Number(value);\n  return Number.isFinite(num) ? num : undefined;\n}\n\n/** Narrow an unknown JSON-RPC result to an array of records. */\nfunction asRecordArray(value: unknown): Record<string, unknown>[] {\n  if (!Array.isArray(value)) return [];\n  return value.filter(isRecord);\n}\n\n/**\n * Fetches and writes hub-level entities. One instance is bound to a JSON-RPC\n * client and a session-id getter; all methods are independently callable.\n */\nexport class HubFetcher {\n  private readonly client: RegaPostClient;\n  private readonly getSessionId: () => string | undefined | Promise<string | undefined>;\n\n  public constructor(options: HubFetcherOptions) {\n    this.client = options.client;\n    this.getSessionId = options.getSessionId;\n  }\n\n  private async sid(): Promise<string | undefined> {\n    return this.getSessionId();\n  }\n\n  /**\n   * Fetch all system variables and join them with their ReGa descriptions to\n   * determine writability (the `HAHM` marker). Missing descriptions are\n   * tolerated (such a variable is treated as read-only).\n   */\n  public async fetchSystemVariables(): Promise<SystemVariable[]> {\n    const sid = await this.sid();\n    const rawAll = await this.client.post(JsonRpcMethod.SYSVAR_GET_ALL, undefined, sidOpts(sid));\n    const entries = asRecordArray(rawAll);\n\n    const descriptions = await this.fetchSysVarDescriptions();\n\n    return entries.map((entry) => this.toSystemVariable(entry, descriptions));\n  }\n\n  /** Read a single system variable's raw value by name. */\n  public async getSystemVariable(name: string): Promise<HmValue> {\n    const sid = await this.sid();\n    const raw = await this.client.post(\n      JsonRpcMethod.SYSVAR_GET_VALUE_BY_NAME,\n      { name },\n      sidOpts(sid),\n    );\n    if (typeof raw === 'string' || typeof raw === 'number' || typeof raw === 'boolean') {\n      return raw;\n    }\n    if (raw === null || raw === undefined) return null;\n    return asString(raw);\n  }\n\n  /**\n   * Write a system variable, dispatching on the JS value type: boolean →\n   * `SysVar.setBool` (1/0), number → `SysVar.setFloat`, string → ReGa\n   * `SET_SYSTEM_VARIABLE`. A null value is rejected.\n   */\n  public async setSystemVariable(name: string, value: HmValue): Promise<void> {\n    const sid = await this.sid();\n    if (value === null) {\n      throw new ValidationError(`Cannot set system variable \"${name}\" to null`);\n    }\n    if (typeof value === 'boolean') {\n      await this.client.post(\n        JsonRpcMethod.SYSVAR_SET_BOOL,\n        { name, value: value ? 1 : 0 },\n        sidOpts(sid),\n      );\n      return;\n    }\n    if (typeof value === 'number') {\n      await this.client.post(JsonRpcMethod.SYSVAR_SET_FLOAT, { name, value }, sidOpts(sid));\n      return;\n    }\n    await runScript(this.client, sid, SET_SYSTEM_VARIABLE, { name, value });\n  }\n\n  /** Fetch all programs, coercing flags to booleans. */\n  public async fetchPrograms(): Promise<HmProgramRecord[]> {\n    const sid = await this.sid();\n    const raw = await this.client.post(JsonRpcMethod.PROGRAM_GET_ALL, undefined, sidOpts(sid));\n    return asRecordArray(raw).map((entry) => {\n      const lastExecuteTime = entry.lastExecuteTime;\n      const record: HmProgramRecord = {\n        id: asString(entry.id),\n        name: asString(entry.name),\n        isActive: asBool(entry.isActive),\n        isInternal: asBool(entry.isInternal),\n        ...(typeof lastExecuteTime === 'string' && lastExecuteTime !== ''\n          ? { lastExecuteTime }\n          : {}),\n      };\n      return record;\n    });\n  }\n\n  /** Execute a program by id. */\n  public async runProgram(id: string): Promise<void> {\n    const sid = await this.sid();\n    await this.client.post(JsonRpcMethod.PROGRAM_EXECUTE, { id }, sidOpts(sid));\n  }\n\n  /** Enable/disable a program via the ReGa `SET_PROGRAM_STATE` script. */\n  public async setProgramActive(id: string, active: boolean): Promise<void> {\n    const sid = await this.sid();\n    await runScript(this.client, sid, SET_PROGRAM_STATE, { id, state: active ? 1 : 0 });\n  }\n\n  /**\n   * Run the custom ReGa script to recover the rooms/functions mapping keyed by\n   * channel address, decoding the latin1 `UriEncode`d names. Tolerates empty.\n   */\n  public async fetchRoomsFunctions(): Promise<{\n    rooms: Map<string, string[]>;\n    functions: Map<string, string[]>;\n  }> {\n    const sid = await this.sid();\n    const parsed = await runScript(this.client, sid, GET_ROOMS_FUNCTIONS);\n    return {\n      rooms: toDecodedMap(isRecord(parsed) ? parsed.rooms : undefined),\n      functions: toDecodedMap(isRecord(parsed) ? parsed.functions : undefined),\n    };\n  }\n\n  /** Build the `SYSVAR_DESCRIPTIONS` map: sysvar id → description text. */\n  private async fetchSysVarDescriptions(): Promise<Map<string, string>> {\n    const sid = await this.sid();\n    const out = new Map<string, string>();\n    try {\n      const parsed = await runScript(this.client, sid, SYSVAR_DESCRIPTIONS);\n      for (const entry of asRecordArray(parsed)) {\n        const id = asString(entry.id);\n        if (id !== '') out.set(id, asString(entry.description));\n      }\n    } catch {\n      // Descriptions are best-effort; without them everything is read-only.\n    }\n    return out;\n  }\n\n  /** Map a single `SysVar.getAll` entry to a {@link SystemVariable}. */\n  private toSystemVariable(\n    entry: Record<string, unknown>,\n    descriptions: Map<string, string>,\n  ): SystemVariable {\n    const id = asString(entry.id);\n    const rawValue = asString(entry.value);\n    const type = normalizeType(asString(entry.type), rawValue);\n    const description = descriptions.get(id);\n    const unit = asString(entry.unit);\n    const valueListRaw = asString(entry.valueList);\n    const valueList =\n      valueListRaw !== '' ? valueListRaw.split(';').map((s) => s.trim()) : undefined;\n    const min = asOptionalNumber(entry.minValue);\n    const max = asOptionalNumber(entry.maxValue);\n\n    return {\n      id,\n      name: asString(entry.name),\n      type,\n      value: parseSysVarValue(type, rawValue),\n      ...(unit !== '' ? { unit } : {}),\n      isInternal: asBool(entry.isInternal),\n      writable: description !== undefined && description.includes(WRITABLE_MARKER),\n      ...(valueList ? { valueList } : {}),\n      ...(min !== undefined ? { min } : {}),\n      ...(max !== undefined ? { max } : {}),\n    };\n  }\n}\n\n/** Build the per-call options object (omitted entirely when no session). */\nfunction sidOpts(sid: string | undefined): { sessionId?: string } | undefined {\n  return sid !== undefined ? { sessionId: sid } : undefined;\n}\n\n/** Turn `{ addr: [encName,...] }` into a `Map<addr, decodedName[]>`. */\nfunction toDecodedMap(value: unknown): Map<string, string[]> {\n  const map = new Map<string, string[]>();\n  if (!isRecord(value)) return map;\n  for (const [addr, names] of Object.entries(value)) {\n    if (Array.isArray(names)) {\n      map.set(\n        addr,\n        names.filter((n): n is string => typeof n === 'string').map((n) => decodeRegaName(n)),\n      );\n    }\n  }\n  return map;\n}\n","/**\n * Per-interface connection state, issue flags and callback liveness.\n *\n * Tracks the {@link ClientState} of each interface, a set of qualitative issue\n * flags (e.g. JSON-RPC down, XML-RPC down, callback silent) and the time of the\n * last inbound event. State changes are published on an optional {@link EventBus}\n * as `connectionStateChanged`. The clock is injectable for deterministic tests.\n */\n\nimport { ClientState } from '../../transport/resilience/state-machine.js';\nimport type { EventBus } from '../event-bus.js';\n\n/** Qualitative connection problem categories. */\nexport type ConnectionIssue = 'json' | 'rpc' | 'callback';\n\n/** Default callback-silence window (ms) before liveness is considered lost. */\nexport const DEFAULT_CALLBACK_WARN_INTERVAL_MS = 180_000;\n\n/** Constructor options for {@link ConnectionStateTracker}. */\nexport interface ConnectionStateTrackerOptions {\n  /** Bus to publish `connectionStateChanged` on; omit to skip publishing. */\n  readonly eventBus?: EventBus;\n  /** Injectable monotonic clock (defaults to `Date.now`). */\n  readonly now?: () => number;\n}\n\nexport class ConnectionStateTracker {\n  private readonly eventBus: EventBus | undefined;\n  private readonly now: () => number;\n\n  private readonly states = new Map<string, ClientState>();\n  private readonly issues = new Map<string, Set<ConnectionIssue>>();\n  private readonly lastEventAt = new Map<string, number>();\n\n  public constructor(options: ConnectionStateTrackerOptions = {}) {\n    this.eventBus = options.eventBus;\n    this.now = options.now ?? Date.now;\n  }\n\n  /** Set the state for an interface and publish `connectionStateChanged`. */\n  public setState(interfaceId: string, state: ClientState, reason?: string): void {\n    this.states.set(interfaceId, state);\n    if (this.eventBus) {\n      void this.eventBus.publish(\n        reason === undefined\n          ? { type: 'connectionStateChanged', interfaceId, state }\n          : { type: 'connectionStateChanged', interfaceId, state, reason },\n      );\n    }\n  }\n\n  /** Current state for an interface (defaults to {@link ClientState.CREATED}). */\n  public getState(interfaceId: string): ClientState {\n    return this.states.get(interfaceId) ?? ClientState.CREATED;\n  }\n\n  /** Flag an issue on an interface. */\n  public addIssue(interfaceId: string, kind: ConnectionIssue): void {\n    const set = this.issues.get(interfaceId) ?? new Set<ConnectionIssue>();\n    set.add(kind);\n    this.issues.set(interfaceId, set);\n  }\n\n  /** Clear a single issue flag on an interface. */\n  public removeIssue(interfaceId: string, kind: ConnectionIssue): void {\n    this.issues.get(interfaceId)?.delete(kind);\n  }\n\n  /**\n   * True if the interface has the given issue, or (when `kind` is omitted) any\n   * issue at all.\n   */\n  public hasIssue(interfaceId: string, kind?: ConnectionIssue): boolean {\n    const set = this.issues.get(interfaceId);\n    if (!set) return false;\n    return kind === undefined ? set.size > 0 : set.has(kind);\n  }\n\n  /** Clear all issue flags on an interface. */\n  public clearIssues(interfaceId: string): void {\n    this.issues.delete(interfaceId);\n  }\n\n  /** Record the time of the latest inbound event for an interface. */\n  public recordEvent(interfaceId: string, at: number = this.now()): void {\n    this.lastEventAt.set(interfaceId, at);\n  }\n\n  /** Time of the latest inbound event recorded for an interface, or `undefined`. */\n  public getLastEventAt(interfaceId: string): number | undefined {\n    return this.lastEventAt.get(interfaceId);\n  }\n\n  /**\n   * True if the callback channel is considered alive: either no event has been\n   * recorded yet (we have no evidence of silence) or the elapsed time since the\n   * last event is within the warn interval.\n   */\n  public isCallbackAlive(\n    interfaceId: string,\n    warnIntervalMs: number = DEFAULT_CALLBACK_WARN_INTERVAL_MS,\n    now: number = this.now(),\n  ): boolean {\n    const last = this.lastEventAt.get(interfaceId);\n    if (last === undefined) return true;\n    return now - last <= warnIntervalMs;\n  }\n}\n","/**\n * Ping/pong loss detector.\n *\n * Before each XML-RPC `ping(callerId=\"{interfaceId}#{token}\")` the central\n * records the token here ({@link PingPongTracker.handleSendPing}); when the CCU\n * echoes the token back as a PONG event the central reconciles it\n * ({@link PingPongTracker.handleReceivedPong}). A persistent excess of\n * unanswered pings (or unexpected pongs) indicates the callback channel is no\n * longer healthy, which the recovery logic treats as a loss signal.\n *\n * The clock is injectable so TTL pruning is deterministic in tests.\n */\n\n/** Default mismatch threshold before {@link PingPongTracker.isMismatch}. */\nexport const DEFAULT_PING_PONG_MISMATCH_COUNT = 15;\n/** Default TTL (ms) after which a pending ping / unknown pong is pruned. */\nexport const DEFAULT_PING_PONG_TTL_MS = 300_000;\n/** Default retry window (ms) for reconciling an unexpected pong. */\nexport const DEFAULT_UNKNOWN_RETRY_MS = 15_000;\n/** Default cap on the number of tracked entries per bucket. */\nexport const DEFAULT_MAX_SIZE = 100;\n\n/** Constructor options for {@link PingPongTracker}. */\nexport interface PingPongTrackerOptions {\n  /** Count above which {@link PingPongTracker.isMismatch} returns true. */\n  readonly mismatchThreshold?: number;\n  /** TTL (ms) after which stale entries are pruned. */\n  readonly ttlMs?: number;\n  /** Retry window (ms) used for unknown-pong reconciliation semantics. */\n  readonly unknownRetryMs?: number;\n  /** Maximum tracked entries per bucket (oldest dropped first). */\n  readonly maxSize?: number;\n  /** Injectable monotonic clock (defaults to `Date.now`). */\n  readonly now?: () => number;\n}\n\nexport class PingPongTracker {\n  private readonly mismatchThreshold: number;\n  private readonly ttlMs: number;\n  private readonly unknownRetryMs: number;\n  private readonly maxSize: number;\n  private readonly now: () => number;\n\n  /** token → time the ping was sent. */\n  private readonly pending = new Map<string, number>();\n  /** token → time the unexpected pong arrived. */\n  private readonly unknown = new Map<string, number>();\n\n  public constructor(options: PingPongTrackerOptions = {}) {\n    this.mismatchThreshold = options.mismatchThreshold ?? DEFAULT_PING_PONG_MISMATCH_COUNT;\n    this.ttlMs = options.ttlMs ?? DEFAULT_PING_PONG_TTL_MS;\n    this.unknownRetryMs = options.unknownRetryMs ?? DEFAULT_UNKNOWN_RETRY_MS;\n    this.maxSize = options.maxSize ?? DEFAULT_MAX_SIZE;\n    this.now = options.now ?? Date.now;\n  }\n\n  /** Record that a ping carrying `token` was just sent. */\n  public handleSendPing(token: string): void {\n    // A late ping for a token we already saw as an unexpected pong reconciles\n    // the two: drop the queued unknown rather than tracking a new pending ping.\n    if (this.unknown.delete(token)) {\n      return;\n    }\n    this.pending.set(token, this.now());\n    this.enforceMaxSize(this.pending);\n  }\n\n  /** Record a received PONG carrying `token`. */\n  public handleReceivedPong(token: string): void {\n    // Matched a ping we were waiting for → reconciled.\n    if (this.pending.delete(token)) {\n      return;\n    }\n    // A pong we did not (yet) expect; queue it for later reconciliation.\n    this.unknown.set(token, this.now());\n    this.enforceMaxSize(this.unknown);\n  }\n\n  /** Number of pings still awaiting a pong (after lazy pruning). */\n  public get pendingCount(): number {\n    this.prune();\n    return this.pending.size;\n  }\n\n  /** Number of unexpected pongs not yet reconciled (after lazy pruning). */\n  public get unknownCount(): number {\n    this.prune();\n    return this.unknown.size;\n  }\n\n  /** True when either bucket exceeds the mismatch threshold. */\n  public isMismatch(): boolean {\n    return this.pendingCount > this.mismatchThreshold || this.unknownCount > this.mismatchThreshold;\n  }\n\n  /** Drop entries older than the TTL (and re-enforce the size caps). */\n  public prune(): void {\n    const cutoff = this.now() - this.ttlMs;\n    for (const [token, at] of this.pending) {\n      if (at < cutoff) this.pending.delete(token);\n    }\n    for (const [token, at] of this.unknown) {\n      if (at < cutoff) this.unknown.delete(token);\n    }\n    this.enforceMaxSize(this.pending);\n    this.enforceMaxSize(this.unknown);\n  }\n\n  /** Forget all tracked state. */\n  public reset(): void {\n    this.pending.clear();\n    this.unknown.clear();\n  }\n\n  /** Drop the oldest insertion-order entries until the map fits `maxSize`. */\n  private enforceMaxSize(map: Map<string, number>): void {\n    while (map.size > this.maxSize) {\n      const oldest = map.keys().next().value;\n      if (oldest === undefined) break;\n      map.delete(oldest);\n    }\n  }\n}\n","/**\n * Rock-solid connection recovery.\n *\n * Drives a deterministic stage machine to bring an interface back online after\n * a loss, emitting `recoveryStageChanged` on the {@link EventBus} at every\n * transition. Two paths exist:\n *\n *  - **runtime** (an existing client is present):\n *    COOLDOWN → TCP_CHECKING → RPC_CHECKING → WARMING_UP → STABILITY_CHECK →\n *    RECONNECTING → DATA_LOADING → RECOVERED.\n *  - **startup** (no client yet): TCP_CHECKING → RECONNECTING → DATA_LOADING →\n *    RECOVERED.\n *\n * A failed attempt waits {@link ConnectionRecovery.nextRetryDelay} and retries\n * from the top; after `maxAttempts` the interface enters FAILED and a heartbeat\n * loop keeps retrying every `heartbeatMs` until success. A semaphore caps the\n * number of interfaces recovering concurrently, and concurrent `recover()`\n * calls for the *same* interface are deduplicated.\n *\n * Every wait goes through the injected `sleep`, and the heartbeat uses an\n * injectable timer, so the whole machine is deterministic under tests.\n */\n\nimport type { EventBus } from '../event-bus.js';\n\n/** Ordered recovery stages emitted as `recoveryStageChanged`. */\nexport enum RecoveryStage {\n  IDLE = 'IDLE',\n  COOLDOWN = 'COOLDOWN',\n  TCP_CHECKING = 'TCP_CHECKING',\n  RPC_CHECKING = 'RPC_CHECKING',\n  WARMING_UP = 'WARMING_UP',\n  STABILITY_CHECK = 'STABILITY_CHECK',\n  RECONNECTING = 'RECONNECTING',\n  DATA_LOADING = 'DATA_LOADING',\n  RECOVERED = 'RECOVERED',\n  FAILED = 'FAILED',\n}\n\n/** Injectable side effects the recovery machine drives. */\nexport interface RecoveryHooks {\n  /** Probe a raw TCP connection to the interface (resolves to reachability). */\n  tcpCheck(interfaceId: string): Promise<boolean>;\n  /** Probe RPC health (e.g. `system.listMethods`). */\n  rpcCheck(interfaceId: string): Promise<boolean>;\n  /** Re-initialise the client (deinit+init, resets the breaker). */\n  doReconnect(interfaceId: string): Promise<void>;\n  /** Re-sync values / hub data after a successful reconnect. */\n  reloadData(interfaceId: string): Promise<void>;\n  /** Whether a live client already exists (runtime path) or not (startup). */\n  hasExistingClient(interfaceId: string): boolean;\n}\n\n/** Opaque timer handle returned by {@link RecoveryOptions.setTimer}. */\nexport type TimerHandle = ReturnType<typeof setTimeout>;\n\n/** Constructor options for {@link ConnectionRecovery}. */\nexport interface RecoveryOptions {\n  readonly eventBus: EventBus;\n  /** Injectable delay primitive; tests pass an immediate/recording stub. */\n  readonly sleep: (ms: number) => Promise<void>;\n  readonly now?: () => number;\n  readonly cooldownMs?: number;\n  readonly warmupMs?: number;\n  readonly tcpCheckTimeoutMs?: number;\n  readonly baseRetryMs?: number;\n  readonly maxRetryMs?: number;\n  readonly maxAttempts?: number;\n  readonly heartbeatMs?: number;\n  /** Max interfaces recovering concurrently. */\n  readonly maxConcurrent?: number;\n  readonly hooks: RecoveryHooks;\n  /** Injectable timer scheduler (defaults to `setTimeout`). */\n  readonly setTimer?: (cb: () => void, ms: number) => TimerHandle;\n  /** Injectable timer canceller (defaults to `clearTimeout`). */\n  readonly clearTimer?: (handle: TimerHandle) => void;\n}\n\nconst DEFAULTS = {\n  cooldownMs: 30_000,\n  warmupMs: 15_000,\n  tcpCheckTimeoutMs: 2_000,\n  baseRetryMs: 5_000,\n  maxRetryMs: 60_000,\n  maxAttempts: 8,\n  heartbeatMs: 60_000,\n  maxConcurrent: 2,\n} as const;\n\nexport class ConnectionRecovery {\n  private readonly eventBus: EventBus;\n  private readonly sleep: (ms: number) => Promise<void>;\n  private readonly cooldownMs: number;\n  private readonly warmupMs: number;\n  private readonly tcpCheckTimeoutMs: number;\n  private readonly baseRetryMs: number;\n  private readonly maxRetryMs: number;\n  private readonly maxAttempts: number;\n  private readonly heartbeatMs: number;\n  private readonly maxConcurrent: number;\n  private readonly hooks: RecoveryHooks;\n  private readonly setTimer: (cb: () => void, ms: number) => TimerHandle;\n  private readonly clearTimer: (handle: TimerHandle) => void;\n\n  /** In-flight recover() promises keyed by interface (per-interface dedup). */\n  private readonly running = new Map<string, Promise<boolean>>();\n  /** Active heartbeat timers keyed by interface. */\n  private readonly heartbeats = new Map<string, TimerHandle>();\n  /** Set once {@link stop} is called; aborts loops and blocks new work. */\n  private stopped = false;\n\n  /** Concurrency semaphore state. */\n  private active = 0;\n  private readonly waiters: Array<() => void> = [];\n\n  public constructor(options: RecoveryOptions) {\n    this.eventBus = options.eventBus;\n    this.sleep = options.sleep;\n    this.cooldownMs = options.cooldownMs ?? DEFAULTS.cooldownMs;\n    this.warmupMs = options.warmupMs ?? DEFAULTS.warmupMs;\n    this.tcpCheckTimeoutMs = options.tcpCheckTimeoutMs ?? DEFAULTS.tcpCheckTimeoutMs;\n    this.baseRetryMs = options.baseRetryMs ?? DEFAULTS.baseRetryMs;\n    this.maxRetryMs = options.maxRetryMs ?? DEFAULTS.maxRetryMs;\n    this.maxAttempts = options.maxAttempts ?? DEFAULTS.maxAttempts;\n    this.heartbeatMs = options.heartbeatMs ?? DEFAULTS.heartbeatMs;\n    this.maxConcurrent = options.maxConcurrent ?? DEFAULTS.maxConcurrent;\n    this.hooks = options.hooks;\n    this.setTimer = options.setTimer ?? ((cb, ms) => setTimeout(cb, ms));\n    this.clearTimer = options.clearTimer ?? ((h) => clearTimeout(h));\n  }\n\n  /**\n   * Exponential backoff for the given (1-based) consecutive failure count:\n   * `min(baseRetryMs * 2^(failures-1), maxRetryMs)`.\n   */\n  public nextRetryDelay(consecutiveFailures: number): number {\n    const exp = Math.max(0, consecutiveFailures - 1);\n    return Math.min(this.baseRetryMs * 2 ** exp, this.maxRetryMs);\n  }\n\n  /**\n   * Recover an interface. Concurrent calls for the same interface return the\n   * same in-flight promise. Resolves true once RECOVERED, false once FAILED\n   * (after which a heartbeat loop continues retrying in the background).\n   */\n  public recover(interfaceId: string): Promise<boolean> {\n    const existing = this.running.get(interfaceId);\n    if (existing) return existing;\n\n    const run = this.runRecovery(interfaceId).finally(() => {\n      this.running.delete(interfaceId);\n    });\n    this.running.set(interfaceId, run);\n    return run;\n  }\n\n  /** Cancel heartbeat timers and stop scheduling further work. */\n  public stop(): void {\n    this.stopped = true;\n    for (const handle of this.heartbeats.values()) {\n      this.clearTimer(handle);\n    }\n    this.heartbeats.clear();\n    // Release anything blocked on the semaphore so promises settle.\n    while (this.waiters.length > 0) {\n      const next = this.waiters.shift();\n      if (next) next();\n    }\n  }\n\n  private async runRecovery(interfaceId: string): Promise<boolean> {\n    await this.acquire();\n    try {\n      let failures = 0;\n      while (!this.stopped) {\n        const ok = await this.attempt(interfaceId);\n        if (ok) {\n          await this.emit(interfaceId, RecoveryStage.RECOVERED);\n          return true;\n        }\n        failures++;\n        if (failures >= this.maxAttempts) {\n          await this.emit(interfaceId, RecoveryStage.FAILED);\n          this.scheduleHeartbeat(interfaceId);\n          return false;\n        }\n        await this.sleep(this.nextRetryDelay(failures));\n      }\n      return false;\n    } finally {\n      this.release();\n    }\n  }\n\n  /** Run a single recovery attempt; returns true if it reached RECOVERED. */\n  private async attempt(interfaceId: string): Promise<boolean> {\n    const runtime = this.hooks.hasExistingClient(interfaceId);\n\n    if (runtime) {\n      await this.emit(interfaceId, RecoveryStage.COOLDOWN);\n      await this.sleep(this.cooldownMs);\n      if (this.stopped) return false;\n    }\n\n    await this.emit(interfaceId, RecoveryStage.TCP_CHECKING);\n    if (!(await this.hooks.tcpCheck(interfaceId))) return false;\n\n    if (runtime) {\n      await this.emit(interfaceId, RecoveryStage.RPC_CHECKING);\n      if (!(await this.hooks.rpcCheck(interfaceId))) return false;\n\n      await this.emit(interfaceId, RecoveryStage.WARMING_UP);\n      await this.sleep(this.warmupMs);\n      if (this.stopped) return false;\n\n      await this.emit(interfaceId, RecoveryStage.STABILITY_CHECK);\n      if (!(await this.hooks.rpcCheck(interfaceId))) return false;\n    }\n\n    await this.emit(interfaceId, RecoveryStage.RECONNECTING);\n    await this.hooks.doReconnect(interfaceId);\n\n    await this.emit(interfaceId, RecoveryStage.DATA_LOADING);\n    await this.hooks.reloadData(interfaceId);\n\n    return true;\n  }\n\n  /** Schedule (or reschedule) the heartbeat retry loop for an interface. */\n  private scheduleHeartbeat(interfaceId: string): void {\n    if (this.stopped) return;\n    const existing = this.heartbeats.get(interfaceId);\n    if (existing) this.clearTimer(existing);\n\n    const handle = this.setTimer(() => {\n      this.heartbeats.delete(interfaceId);\n      if (this.stopped) return;\n      void this.recover(interfaceId).then((ok) => {\n        if (!ok && !this.stopped) this.scheduleHeartbeat(interfaceId);\n      });\n    }, this.heartbeatMs);\n    this.heartbeats.set(interfaceId, handle);\n  }\n\n  private async emit(interfaceId: string, stage: RecoveryStage): Promise<void> {\n    await this.eventBus.publish({ type: 'recoveryStageChanged', interfaceId, stage });\n  }\n\n  /** Acquire a semaphore slot, waiting if the concurrency cap is reached. */\n  private async acquire(): Promise<void> {\n    if (this.active < this.maxConcurrent) {\n      this.active++;\n      return;\n    }\n    await new Promise<void>((resolve) => {\n      this.waiters.push(resolve);\n    });\n    this.active++;\n  }\n\n  /** Release a semaphore slot, waking the next waiter if any. */\n  private release(): void {\n    this.active--;\n    const next = this.waiters.shift();\n    if (next) next();\n  }\n}\n","/**\n * Interval job scheduler.\n *\n * Runs registered jobs on their own `setInterval` cadence. During connection\n * trouble the central calls {@link Scheduler.pauseAllExcept} to suspend every\n * job but the connection-check, and {@link Scheduler.resume} to restart the\n * rest. A job whose `run` throws or rejects is caught and logged via the\n * injectable logger; it never tears down the loop. Uses real timers, so tests\n * drive it with `vi.useFakeTimers()`.\n */\n\n/** A periodic job. */\nexport interface ScheduledJob {\n  readonly name: string;\n  readonly intervalMs: number;\n  readonly run: () => Promise<void> | void;\n}\n\n/** Minimal logger contract used to report job failures. */\nexport interface SchedulerLogger {\n  error(message: string, error: unknown): void;\n}\n\n/** Constructor options for {@link Scheduler}. */\nexport interface SchedulerOptions {\n  readonly logger?: SchedulerLogger;\n}\n\nconst NOOP_LOGGER: SchedulerLogger = {\n  error: () => {\n    /* no-op */\n  },\n};\n\nexport class Scheduler {\n  private readonly logger: SchedulerLogger;\n  private readonly jobs = new Map<string, ScheduledJob>();\n  private readonly timers = new Map<string, ReturnType<typeof setInterval>>();\n  private started = false;\n\n  public constructor(options: SchedulerOptions = {}) {\n    this.logger = options.logger ?? NOOP_LOGGER;\n  }\n\n  /** Register a job (replacing any job with the same name). */\n  public add(job: ScheduledJob): void {\n    this.jobs.set(job.name, job);\n    if (this.started) {\n      this.arm(job);\n    }\n  }\n\n  /** Start all registered jobs. */\n  public start(): void {\n    this.started = true;\n    for (const job of this.jobs.values()) {\n      this.arm(job);\n    }\n  }\n\n  /** Stop and clear all interval timers. */\n  public stop(): void {\n    this.started = false;\n    for (const timer of this.timers.values()) {\n      clearInterval(timer);\n    }\n    this.timers.clear();\n  }\n\n  /** Suspend every job except the named one (keeps it running unchanged). */\n  public pauseAllExcept(name: string): void {\n    for (const [jobName, timer] of this.timers) {\n      if (jobName !== name) {\n        clearInterval(timer);\n        this.timers.delete(jobName);\n      }\n    }\n  }\n\n  /** Restart any registered job that is not currently armed. */\n  public resume(): void {\n    if (!this.started) return;\n    for (const job of this.jobs.values()) {\n      if (!this.timers.has(job.name)) {\n        this.arm(job);\n      }\n    }\n  }\n\n  /** Arm (or re-arm) the interval timer for a single job. */\n  private arm(job: ScheduledJob): void {\n    const existing = this.timers.get(job.name);\n    if (existing) clearInterval(existing);\n    const timer = setInterval(() => {\n      void this.invoke(job);\n    }, job.intervalMs);\n    this.timers.set(job.name, timer);\n  }\n\n  /** Invoke a job, catching and logging any sync throw or async rejection. */\n  private async invoke(job: ScheduledJob): Promise<void> {\n    try {\n      await job.run();\n    } catch (error: unknown) {\n      this.logger.error(`Scheduled job \"${job.name}\" failed`, error);\n    }\n  }\n}\n","/**\n * Routes raw {@link RawCallbackEvent}s from the {@link CallbackServer} onto the\n * central's typed {@link EventBus}, value cache and device registry.\n *\n * The router owns NO transport: it is a pure dispatcher fed normalized callback\n * events. Side effects that need transport access (incremental discovery, value\n * re-sync) are delegated back to the {@link CentralUnit} via the injected\n * {@link RouterHooks}. Keeping it here keeps {@link CentralUnit} focused on\n * lifecycle wiring.\n */\n\nimport { makeDpk } from '../support/dpk.js';\nimport { ParamsetKey } from '../support/constants.js';\nimport type { RawCallbackEvent } from '../transport/callback-server/events.js';\nimport type { XmlRpcValue } from '../transport/xmlrpc/types.js';\nimport type { EventBus } from './event-bus.js';\nimport type { ValueCache } from './store/value-cache.js';\nimport type { DeviceRegistry } from './device-registry.js';\nimport type { ConnectionStateTracker } from './connection/connection-state.js';\nimport type { PingPongTracker } from './connection/ping-pong.js';\n\n/** The parameter name a CCU uses for a ping/pong reconciliation event. */\nexport const PONG_PARAMETER = 'PONG';\n\n/** Side effects the router delegates back to the central (transport access). */\nexport interface RouterHooks {\n  /** Incrementally discover device addresses pushed via `newDevices`. */\n  onNewDevices(interfaceId: string, addresses: readonly string[]): Promise<void>;\n  /** Re-discover a single device whose description changed (`updateDevice`). */\n  onUpdateDevice(interfaceId: string, address: string): Promise<void>;\n  /** Re-discover after a `replaceDevice`/`readdedDevice` (old removed, new added). */\n  onReaddDevices(interfaceId: string, addresses: readonly string[]): Promise<void>;\n}\n\n/** Construction dependencies for the {@link CallbackRouter}. */\nexport interface CallbackRouterOptions {\n  readonly eventBus: EventBus;\n  readonly valueCache: ValueCache;\n  readonly registry: DeviceRegistry;\n  readonly connectionState: ConnectionStateTracker;\n  /** Resolve the {@link PingPongTracker} for an interface id (undefined if unknown). */\n  readonly pingPongFor: (interfaceId: string) => PingPongTracker | undefined;\n  readonly hooks: RouterHooks;\n  /** Injectable clock for `receivedAt` stamping. */\n  readonly now?: () => number;\n}\n\n/** Address of the device that owns a channel address (`DEV:idx` → `DEV`). */\nfunction deviceAddressOf(channelAddress: string): string {\n  const colon = channelAddress.lastIndexOf(':');\n  return colon === -1 ? channelAddress : channelAddress.slice(0, colon);\n}\n\n/** Extract the `ADDRESS` field from a raw device-description struct, if present. */\nfunction addressOf(description: Record<string, unknown>): string | undefined {\n  const address = description['ADDRESS'];\n  return typeof address === 'string' && address !== '' ? address : undefined;\n}\n\nexport class CallbackRouter {\n  private readonly eventBus: EventBus;\n  private readonly valueCache: ValueCache;\n  private readonly registry: DeviceRegistry;\n  private readonly connectionState: ConnectionStateTracker;\n  private readonly pingPongFor: (interfaceId: string) => PingPongTracker | undefined;\n  private readonly hooks: RouterHooks;\n  private readonly now: () => number;\n\n  public constructor(options: CallbackRouterOptions) {\n    this.eventBus = options.eventBus;\n    this.valueCache = options.valueCache;\n    this.registry = options.registry;\n    this.connectionState = options.connectionState;\n    this.pingPongFor = options.pingPongFor;\n    this.hooks = options.hooks;\n    this.now = options.now ?? Date.now;\n  }\n\n  /**\n   * Handle one normalized callback event. Returns a promise that resolves once\n   * any async side effect (discovery, publish) has completed, so the caller can\n   * await ordering in tests; transport errors are surfaced to the caller.\n   */\n  public async route(raw: RawCallbackEvent): Promise<void> {\n    switch (raw.type) {\n      case 'event':\n        await this.routeEvent(raw.interfaceId, raw.channelAddress, raw.parameter, raw.value);\n        return;\n      case 'newDevices':\n        await this.routeNewDevices(raw.interfaceId, raw.descriptions);\n        return;\n      case 'deleteDevices':\n        await this.routeDeleteDevices(raw.interfaceId, raw.addresses);\n        return;\n      case 'updateDevice':\n        await this.hooks.onUpdateDevice(raw.interfaceId, raw.address);\n        return;\n      case 'replaceDevice':\n        await this.routeReadd(raw.interfaceId, [raw.oldAddress], [raw.newAddress]);\n        return;\n      case 'readdedDevice':\n        await this.routeReadd(raw.interfaceId, raw.addresses, raw.addresses);\n        return;\n      case 'error':\n        await this.eventBus.publish({\n          type: 'systemError',\n          interfaceId: raw.interfaceId,\n          code: raw.code,\n          message: raw.message,\n        });\n        return;\n    }\n  }\n\n  private async routeEvent(\n    interfaceId: string,\n    channelAddress: string,\n    parameter: string,\n    value: XmlRpcValue,\n  ): Promise<void> {\n    // Any inbound event is also evidence the callback channel is alive.\n    this.connectionState.recordEvent(interfaceId);\n\n    // A PONG event echoes a ping token in its value; reconcile it instead of\n    // treating it as a data point value.\n    if (parameter === PONG_PARAMETER) {\n      const tracker = this.pingPongFor(interfaceId);\n      // The CCU broadcasts PONGs to EVERY registered client; only reconcile pongs\n      // whose token is ours (`${interfaceId}#<seq>`). Foreign clients' pongs\n      // (e.g. another central pinging the same CCU) are ignored so they don't\n      // pollute the mismatch tracker and trigger spurious reconnects.\n      if (\n        tracker !== undefined &&\n        typeof value === 'string' &&\n        value.startsWith(`${interfaceId}#`)\n      ) {\n        tracker.handleReceivedPong(value);\n      }\n      return;\n    }\n\n    const dpk = makeDpk(interfaceId, channelAddress, ParamsetKey.VALUES, parameter);\n    const receivedAt = this.now();\n    this.valueCache.add(dpk, value, receivedAt);\n    await this.eventBus.publish({ type: 'valueReceived', dpk, value, receivedAt, origin: 'event' });\n  }\n\n  private async routeNewDevices(\n    interfaceId: string,\n    descriptions: ReadonlyArray<Record<string, unknown>>,\n  ): Promise<void> {\n    const addresses = descriptions\n      .map(addressOf)\n      .filter((address): address is string => address !== undefined);\n    if (addresses.length === 0) return;\n    await this.hooks.onNewDevices(interfaceId, addresses);\n  }\n\n  private async routeDeleteDevices(\n    interfaceId: string,\n    addresses: readonly string[],\n  ): Promise<void> {\n    for (const address of addresses) {\n      // The CCU may delete channels or whole devices; resolve to the owning\n      // device so the registry drops the full node.\n      const deviceAddress = this.registry.get(address) ? address : deviceAddressOf(address);\n      this.registry.removeDevice(deviceAddress);\n      await this.eventBus.publish({ type: 'deviceRemoved', address: deviceAddress });\n    }\n  }\n\n  private async routeReadd(\n    interfaceId: string,\n    removed: readonly string[],\n    added: readonly string[],\n  ): Promise<void> {\n    for (const address of removed) {\n      const deviceAddress = this.registry.get(address) ? address : deviceAddressOf(address);\n      this.registry.removeDevice(deviceAddress);\n      await this.eventBus.publish({ type: 'deviceRemoved', address: deviceAddress });\n    }\n    await this.hooks.onReaddDevices(interfaceId, added);\n  }\n}\n","/**\n * Value conversion + validation between the CCU wire representation and the\n * library's JS-facing {@link HmValue} domain.\n *\n * The CCU speaks a small set of {@link ParameterType}s. Inbound values arrive as\n * loosely-typed XML-RPC scalars (numbers, strings, booleans); outbound writes\n * must be coerced and validated against the parameter metadata before hitting\n * the wire. This module is pure: it never touches the network.\n */\n\nimport type { ParameterSpec } from '../central/graph.js';\nimport { ParameterType } from '../support/constants.js';\nimport { ValidationError, UnsupportedError } from '../support/errors.js';\n\n/** The JS-facing value of a data point. */\nexport type HmValue = boolean | number | string | null;\n\n/** Coerce a loosely-typed scalar to a boolean (CCU sends 1/0, '1'/'0', 'true'/'false'). */\nfunction toBool(raw: unknown): boolean {\n  if (typeof raw === 'boolean') return raw;\n  if (typeof raw === 'number') return raw !== 0;\n  if (typeof raw === 'string') {\n    const lower = raw.trim().toLowerCase();\n    if (lower === 'true' || lower === '1') return true;\n    if (lower === 'false' || lower === '0' || lower === '') return false;\n    return Boolean(raw);\n  }\n  return Boolean(raw);\n}\n\n/**\n * Stringify an untrusted value safely. Objects/arrays are JSON-encoded rather\n * than relying on `Object.prototype.toString` (which would yield\n * `[object Object]`); primitives use their natural string form.\n */\nfunction safeStringify(raw: unknown): string {\n  if (typeof raw === 'string') return raw;\n  if (typeof raw === 'number' || typeof raw === 'boolean' || typeof raw === 'bigint') {\n    return String(raw);\n  }\n  if (raw === null || raw === undefined) return String(raw);\n  if (typeof raw === 'symbol') return raw.toString();\n  try {\n    return JSON.stringify(raw) ?? Object.prototype.toString.call(raw);\n  } catch {\n    return Object.prototype.toString.call(raw);\n  }\n}\n\n/** Coerce to a finite number, or `null` if the value is empty / not a finite number. */\nfunction toFiniteNumberOrNull(raw: unknown): number | null {\n  if (raw === '' || raw === null || raw === undefined) return null;\n  const num = Number(raw);\n  return Number.isFinite(num) ? num : null;\n}\n\n/**\n * Convert a raw CCU value to the JS-facing {@link HmValue}, using `spec` to pick\n * the right coercion. Inbound conversion is lenient: malformed numerics become\n * `null` rather than throwing (the CCU is the trusted source here).\n */\nexport function convertFromCcu(spec: ParameterSpec, raw: unknown): HmValue {\n  switch (spec.type) {\n    case ParameterType.FLOAT:\n    case ParameterType.INTEGER:\n      return toFiniteNumberOrNull(raw);\n\n    case ParameterType.BOOL:\n      return toBool(raw);\n\n    case ParameterType.ENUM:\n      return enumFromCcu(spec, raw);\n\n    case ParameterType.STRING:\n      return safeStringify(raw);\n\n    case ParameterType.ACTION:\n      return Boolean(raw);\n\n    default:\n      // Unknown / EMPTY / DUMMY: defensively reduce to a primitive.\n      if (raw === '' || raw === null || raw === undefined) return null;\n      return safeStringify(raw);\n  }\n}\n\n/** ENUM inbound: CCU sends a numeric index; map to the value-list string when possible. */\nfunction enumFromCcu(spec: ParameterSpec, raw: unknown): HmValue {\n  const list = spec.valueList;\n  if (list !== undefined) {\n    if (typeof raw === 'string') {\n      // Already a value-list member?\n      if (list.includes(raw)) return raw;\n      // Numeric-looking string index.\n      const idx = Number(raw);\n      if (Number.isInteger(idx) && idx >= 0 && idx < list.length) {\n        return list[idx] as string;\n      }\n    } else if (typeof raw === 'number' && Number.isInteger(raw) && raw >= 0 && raw < list.length) {\n      return list[raw] as string;\n    }\n  }\n  // No list, or index out of range: expose the numeric index as-is.\n  const num = Number(raw);\n  return Number.isFinite(num) ? num : String(raw);\n}\n\n/** Throw {@link UnsupportedError} if the parameter cannot be written. */\nexport function validateWritable(spec: ParameterSpec): void {\n  if (!spec.writable) {\n    throw new UnsupportedError('Parameter is not writable (OPERATIONS lacks WRITE).');\n  }\n}\n\n/** Options governing outbound conversion. */\nexport interface ToCcuOptions {\n  /** When true, ENUM values are serialised as the integer index (HM-style). */\n  readonly enumAsIndex: boolean;\n}\n\n/**\n * Convert and validate a JS-facing {@link HmValue} into the CCU wire scalar for\n * `spec`. Throws {@link UnsupportedError} if the parameter is not writable, and\n * {@link ValidationError} on an out-of-range, non-integer, or unknown-enum value.\n */\nexport function convertToCcu(\n  spec: ParameterSpec,\n  value: HmValue,\n  opts: ToCcuOptions,\n): boolean | number | string {\n  validateWritable(spec);\n\n  switch (spec.type) {\n    case ParameterType.FLOAT:\n      return numberToCcu(spec, value, false);\n\n    case ParameterType.INTEGER:\n      return numberToCcu(spec, value, true);\n\n    case ParameterType.BOOL:\n      return toBool(value);\n\n    case ParameterType.ENUM:\n      return enumToCcu(spec, value, opts.enumAsIndex);\n\n    case ParameterType.STRING:\n      return String(value);\n\n    case ParameterType.ACTION:\n      return true;\n\n    default:\n      // Unknown / EMPTY / DUMMY: pass through as a string.\n      return String(value);\n  }\n}\n\n/** Numeric outbound: coerce, optionally require integer, enforce MIN/MAX range. */\nfunction numberToCcu(spec: ParameterSpec, value: HmValue, requireInteger: boolean): number {\n  if (value === null) {\n    throw new ValidationError('A numeric value is required (got null).');\n  }\n  const num = Number(value);\n  if (!Number.isFinite(num)) {\n    throw new ValidationError(`Value is not a finite number: ${String(value)}`);\n  }\n  if (requireInteger && !Number.isInteger(num)) {\n    throw new ValidationError(`INTEGER parameter requires an integer value: ${String(value)}`);\n  }\n  if (spec.min !== undefined && num < spec.min) {\n    throw new ValidationError(`Value ${num} is below minimum ${spec.min}.`);\n  }\n  if (spec.max !== undefined && num > spec.max) {\n    throw new ValidationError(`Value ${num} is above maximum ${spec.max}.`);\n  }\n  return num;\n}\n\n/** ENUM outbound: resolve to index (HM) or string (HmIP), validating membership. */\nfunction enumToCcu(spec: ParameterSpec, value: HmValue, enumAsIndex: boolean): number | string {\n  const list = spec.valueList;\n\n  // Resolve the value to an index within the value list (when one exists).\n  let index: number | undefined;\n  if (typeof value === 'number') {\n    index = value;\n  } else if (typeof value === 'string') {\n    if (list !== undefined) {\n      const found = list.indexOf(value);\n      index = found >= 0 ? found : undefined;\n      if (found < 0) {\n        // Maybe a numeric-looking string index.\n        const asNum = Number(value);\n        if (Number.isInteger(asNum)) index = asNum;\n      }\n    }\n  }\n\n  if (list !== undefined) {\n    if (index === undefined || !Number.isInteger(index) || index < 0 || index >= list.length) {\n      throw new ValidationError(`ENUM value not in value list: ${String(value)}`);\n    }\n    return enumAsIndex ? index : (list[index] as string);\n  }\n\n  // No value list to validate against: trust the caller.\n  if (enumAsIndex) {\n    if (typeof value === 'number' && Number.isInteger(value)) return value;\n    throw new ValidationError(`ENUM index required (no value list): ${String(value)}`);\n  }\n  return String(value);\n}\n","/**\n * {@link GenericDataPoint} — a single live value point in the domain model.\n *\n * It binds a {@link DataPointKey} (its identity/routing key) to a typed\n * {@link ParameterSpec} (its metadata) and holds the current converted value.\n * Inbound CCU events flow through {@link GenericDataPoint.applyCcuValue} (which\n * converts + updates state + notifies subscribers on change); outbound writes\n * are validated and converted by {@link GenericDataPoint.prepareWrite}.\n *\n * State lives inside the data point, but its identity and metadata are fixed at\n * construction. The CCU is the source of truth for the value; subscribers are\n * notified only when the converted value actually changes.\n */\n\nimport type { ParameterSpec } from '../central/graph.js';\nimport type { ParameterType } from '../support/constants.js';\nimport { type DataPointKey, dpkToUniqueId } from '../support/dpk.js';\nimport { convertFromCcu, convertToCcu, type HmValue } from './converter.js';\n\n/** The interface family, which governs ENUM serialisation on writes. */\nexport type InterfaceFamily = 'HM' | 'HMIP';\n\n/** Construction inputs for a {@link GenericDataPoint}. */\nexport interface GenericDataPointInit {\n  readonly dpk: DataPointKey;\n  readonly spec: ParameterSpec;\n  readonly interfaceFamily: InterfaceFamily;\n}\n\n/** Result of applying an inbound CCU value. */\nexport interface ApplyResult {\n  readonly changed: boolean;\n  readonly prev: HmValue;\n  readonly next: HmValue;\n}\n\n/** A subscriber notified with `(next, prev)` whenever the value changes. */\nexport type ValueListener = (next: HmValue, prev: HmValue) => void;\n\nexport class GenericDataPoint {\n  readonly #dpk: DataPointKey;\n  readonly #spec: ParameterSpec;\n  readonly #interfaceFamily: InterfaceFamily;\n  readonly #id: string;\n  readonly #listeners = new Set<ValueListener>();\n\n  #value: HmValue = null;\n  #lastUpdatedAt: number | undefined = undefined;\n\n  public constructor(init: GenericDataPointInit) {\n    this.#dpk = init.dpk;\n    this.#spec = init.spec;\n    this.#interfaceFamily = init.interfaceFamily;\n    this.#id = dpkToUniqueId(init.dpk);\n  }\n\n  /** Stable, lowercased unique id derived from the dpk. */\n  public get id(): string {\n    return this.#id;\n  }\n\n  /** The routing key identifying this value point. */\n  public get dpk(): DataPointKey {\n    return this.#dpk;\n  }\n\n  /** The parameter name, e.g. `STATE`. */\n  public get parameter(): string {\n    return this.#dpk.parameter;\n  }\n\n  /** The parameter value type. */\n  public get type(): ParameterType {\n    return this.#spec.type;\n  }\n\n  public get readable(): boolean {\n    return this.#spec.readable;\n  }\n\n  public get writable(): boolean {\n    return this.#spec.writable;\n  }\n\n  public get hasEvents(): boolean {\n    return this.#spec.hasEvents;\n  }\n\n  public get visible(): boolean {\n    return this.#spec.visible;\n  }\n\n  public get unit(): string | undefined {\n    return this.#spec.unit;\n  }\n\n  public get valueList(): readonly string[] | undefined {\n    return this.#spec.valueList;\n  }\n\n  public get min(): number | undefined {\n    return this.#spec.min;\n  }\n\n  public get max(): number | undefined {\n    return this.#spec.max;\n  }\n\n  /** The current converted value (default `null` until the first event). */\n  public get value(): HmValue {\n    return this.#value;\n  }\n\n  /** Epoch-ms timestamp of the last `applyCcuValue`, or `undefined`. */\n  public get lastUpdatedAt(): number | undefined {\n    return this.#lastUpdatedAt;\n  }\n\n  /**\n   * Apply a raw inbound CCU value: convert it, update the current value and\n   * timestamp, and notify subscribers when (and only when) the value changed.\n   */\n  public applyCcuValue(raw: unknown, at: number): ApplyResult {\n    const prev = this.#value;\n    const next = convertFromCcu(this.#spec, raw);\n    this.#value = next;\n    this.#lastUpdatedAt = at;\n    const changed = prev !== next;\n    if (changed) {\n      this.#notify(next, prev);\n    }\n    return { changed, prev, next };\n  }\n\n  /**\n   * Validate (writable + range/membership) and convert a JS value to its CCU\n   * wire representation. ENUM is serialised as an index for HM interfaces and\n   * as a string for HmIP interfaces.\n   */\n  public prepareWrite(value: HmValue): boolean | number | string {\n    const enumAsIndex = this.#interfaceFamily === 'HM';\n    return convertToCcu(this.#spec, value, { enumAsIndex });\n  }\n\n  /** Subscribe to value changes. Returns an unsubscribe function. */\n  public subscribe(cb: ValueListener): () => void {\n    this.#listeners.add(cb);\n    return () => {\n      this.#listeners.delete(cb);\n    };\n  }\n\n  #notify(next: HmValue, prev: HmValue): void {\n    for (const listener of this.#listeners) {\n      listener(next, prev);\n    }\n  }\n}\n","/**\n * {@link ModelChannel} — a public, structurally-immutable view of one channel of\n * a device. It groups the channel's {@link GenericDataPoint}s and exposes a\n * by-parameter lookup. The data points carry their own live state, but the set\n * of data points (and the channel's identity) is fixed at construction.\n */\n\nimport type { GenericDataPoint } from './data-point.js';\n\n/** Construction inputs for a {@link ModelChannel}. */\nexport interface ModelChannelInit {\n  readonly address: string;\n  readonly index: number;\n  readonly type?: string;\n  /** CCU user-given name. Absent when the CCU has none or the name read failed. */\n  readonly name?: string;\n  readonly dataPoints: readonly GenericDataPoint[];\n}\n\nexport class ModelChannel {\n  public readonly address: string;\n  public readonly index: number;\n  public readonly type?: string;\n  public readonly name?: string;\n  public readonly dataPoints: readonly GenericDataPoint[];\n\n  readonly #byParameter: ReadonlyMap<string, GenericDataPoint>;\n\n  public constructor(init: ModelChannelInit) {\n    this.address = init.address;\n    this.index = init.index;\n    if (init.type !== undefined) {\n      this.type = init.type;\n    }\n    if (init.name !== undefined) {\n      this.name = init.name;\n    }\n    this.dataPoints = init.dataPoints;\n    this.#byParameter = new Map(init.dataPoints.map((dp) => [dp.parameter, dp]));\n  }\n\n  /** Resolve a data point on this channel by its parameter name. */\n  public dataPoint(parameter: string): GenericDataPoint | undefined {\n    return this.#byParameter.get(parameter);\n  }\n}\n","/**\n * {@link ModelDevice} — a public, structurally-immutable view of one device. It\n * groups the device's {@link ModelChannel}s and exposes by-channel and\n * by-(channel, parameter) lookups plus a flattened data-point listing. Identity\n * and structure are fixed at construction; the data points carry live state.\n */\n\nimport type { ModelChannel } from './channel.js';\nimport type { GenericDataPoint } from './data-point.js';\n\n/** Construction inputs for a {@link ModelDevice}. */\nexport interface ModelDeviceInit {\n  readonly address: string;\n  readonly type: string;\n  readonly interfaceId: string;\n  readonly name?: string;\n  readonly rooms?: readonly string[];\n  readonly functions?: readonly string[];\n  /** Installed firmware version, e.g. `1.18.24`. */\n  readonly firmware?: string;\n  /** Latest firmware available for this device, e.g. `1.18.24`. */\n  readonly availableFirmware?: string;\n  /** Whether a firmware update can be installed for this device. */\n  readonly updatable?: boolean;\n  /** Firmware update lifecycle state, e.g. `UP_TO_DATE`. */\n  readonly firmwareUpdateState?: string;\n  readonly channels: readonly ModelChannel[];\n}\n\nexport class ModelDevice {\n  public readonly address: string;\n  public readonly type: string;\n  public readonly interfaceId: string;\n  public readonly name?: string;\n  public readonly rooms?: readonly string[];\n  public readonly functions?: readonly string[];\n  public readonly firmware?: string;\n  public readonly availableFirmware?: string;\n  public readonly updatable?: boolean;\n  public readonly firmwareUpdateState?: string;\n  public readonly channels: readonly ModelChannel[];\n\n  readonly #byAddress: ReadonlyMap<string, ModelChannel>;\n\n  public constructor(init: ModelDeviceInit) {\n    this.address = init.address;\n    this.type = init.type;\n    this.interfaceId = init.interfaceId;\n    if (init.name !== undefined) {\n      this.name = init.name;\n    }\n    if (init.rooms !== undefined) {\n      this.rooms = init.rooms;\n    }\n    if (init.functions !== undefined) {\n      this.functions = init.functions;\n    }\n    if (init.firmware !== undefined) {\n      this.firmware = init.firmware;\n    }\n    if (init.availableFirmware !== undefined) {\n      this.availableFirmware = init.availableFirmware;\n    }\n    if (init.updatable !== undefined) {\n      this.updatable = init.updatable;\n    }\n    if (init.firmwareUpdateState !== undefined) {\n      this.firmwareUpdateState = init.firmwareUpdateState;\n    }\n    this.channels = init.channels;\n    this.#byAddress = new Map(init.channels.map((ch) => [ch.address, ch]));\n  }\n\n  /** Resolve a channel by its full channel address (e.g. `VCU0000001:1`). */\n  public channel(channelAddress: string): ModelChannel | undefined {\n    return this.#byAddress.get(channelAddress);\n  }\n\n  /** Resolve a data point by channel address and parameter name. */\n  public dataPoint(channelAddress: string, parameter: string): GenericDataPoint | undefined {\n    return this.channel(channelAddress)?.dataPoint(parameter);\n  }\n\n  /** All data points across every channel, flattened into a single array. */\n  public allDataPoints(): GenericDataPoint[] {\n    return this.channels.flatMap((ch) => [...ch.dataPoints]);\n  }\n}\n","/**\n * Build the public domain model ({@link ModelDevice}[]) from the raw, typed\n * device graph ({@link DeviceNode}[], Phase 2).\n *\n * For each channel, every parameter that has a VALUES {@link ParameterSpec}\n * which is readable OR event-emitting OR writable becomes a live\n * {@link GenericDataPoint}. Writable-only ACTION params (e.g. `STOP` on covers,\n * `LOCK_TARGET_LEVEL` on locks) are command targets and must exist as data\n * points so custom-entity commands can reach them. Pure-internal VALUES params\n * with none of read/event/write are excluded. MASTER-only parameters are config\n * and are handled separately (Task 7), so they never become data points here.\n */\n\nimport type { DeviceNode, ChannelNode } from '../central/graph.js';\nimport { ParamsetKey } from '../support/constants.js';\nimport { makeDpk } from '../support/dpk.js';\nimport { GenericDataPoint, type InterfaceFamily } from './data-point.js';\nimport { ModelChannel } from './channel.js';\nimport { ModelDevice } from './device.js';\n\n/**\n * Classify an interface id into its family. The heuristic: the id contains\n * `HmIP` (case-insensitive) → `HMIP`, otherwise `HM`.\n */\nexport function interfaceFamilyOf(interfaceId: string): InterfaceFamily {\n  return interfaceId.toLowerCase().includes('hmip') ? 'HMIP' : 'HM';\n}\n\n/** Build the {@link ModelChannel}s + {@link GenericDataPoint}s for one channel. */\nfunction buildChannel(\n  channel: ChannelNode,\n  interfaceId: string,\n  family: InterfaceFamily,\n): ModelChannel {\n  const dataPoints: GenericDataPoint[] = [];\n  for (const [parameter, specs] of channel.parameters) {\n    const spec = specs.VALUES;\n    if (spec === undefined || (!spec.readable && !spec.hasEvents && !spec.writable)) {\n      continue;\n    }\n    dataPoints.push(\n      new GenericDataPoint({\n        dpk: makeDpk(interfaceId, channel.address, ParamsetKey.VALUES, parameter),\n        spec,\n        interfaceFamily: family,\n      }),\n    );\n  }\n  return new ModelChannel({\n    address: channel.address,\n    index: channel.index,\n    ...(channel.type !== undefined ? { type: channel.type } : {}),\n    ...(channel.name !== undefined ? { name: channel.name } : {}),\n    dataPoints,\n  });\n}\n\n/** Build a single {@link ModelDevice} from a raw {@link DeviceNode}. */\nexport function buildDevice(node: DeviceNode): ModelDevice {\n  const family = interfaceFamilyOf(node.interfaceId);\n  const channels = node.channels.map((ch) => buildChannel(ch, node.interfaceId, family));\n  return new ModelDevice({\n    address: node.address,\n    type: node.type,\n    interfaceId: node.interfaceId,\n    ...(node.name !== undefined ? { name: node.name } : {}),\n    ...(node.rooms !== undefined ? { rooms: node.rooms } : {}),\n    ...(node.functions !== undefined ? { functions: node.functions } : {}),\n    ...(node.firmware !== undefined ? { firmware: node.firmware } : {}),\n    ...(node.availableFirmware !== undefined ? { availableFirmware: node.availableFirmware } : {}),\n    ...(node.updatable !== undefined ? { updatable: node.updatable } : {}),\n    ...(node.firmwareUpdateState !== undefined\n      ? { firmwareUpdateState: node.firmwareUpdateState }\n      : {}),\n    channels,\n  });\n}\n\n/** Build the full model: one {@link ModelDevice} per {@link DeviceNode}. */\nexport function buildModel(nodes: readonly DeviceNode[]): ModelDevice[] {\n  return nodes.map((node) => buildDevice(node));\n}\n","/**\n * Central-link protocol, taken from aiohomematic (SukramJ/aiohomematic, devel).\n *\n * Create / remove — `Channel.create_central_link` and `Channel.remove_central_link`\n * in `aiohomematic/model/device.py` call `CcuBackend.report_value_usage`\n * (`aiohomematic/client/backends/ccu.py`), which sends one XML-RPC call on the\n * channel's interface (HmIP-RF and BidCos-RF use the same method; there is no\n * `addLink` to a central address):\n *\n *   reportValueUsage(channelAddress, \"PRESS_SHORT\", refCounter)\n *\n * `refCounter` is `1` to create and `0` to remove. The value id and the metadata\n * key are `REPORT_VALUE_USAGE_VALUE_ID` / `REPORT_VALUE_USAGE_DATA` in\n * `aiohomematic/const.py` (`\"PRESS_SHORT\"` / `\"reportValueUsageData\"`).\n *\n * \"Has a central link\" is `Channel._has_central_link` in the same file: XML-RPC\n * `getMetadata(address, \"reportValueUsageData\")` and the integer `PRESS_SHORT`\n * entry is `> 0`. A metadata fault is treated as \"no central link\". It is not\n * inferred from `getLinks`.\n *\n * Direct links are `LinkCoordinator.get_device_links`\n * (`aiohomematic/central/coordinators/link.py`): XML-RPC\n * `getLinks(channelAddress, 0)`, an array of structs with `SENDER`, `RECEIVER`\n * and `NAME`.\n *\n * aiohomematic's `remove_central_link` also skips the XML-RPC call when JSON-RPC\n * `Channel.hasProgramIds` (`client/json_rpc.py` `has_program_ids`) is true.\n * `removeCentralLink` does not consult programs: a central link is cleared\n * whenever the metadata counter is `> 0`.\n */\n\nimport type { XmlRpcValue } from '../transport/xmlrpc/types.js';\nimport type { HmChannelLink } from './types.js';\n\n/** `getMetadata` data id. aiohomematic `const.REPORT_VALUE_USAGE_DATA`. */\nexport const REPORT_VALUE_USAGE_DATA = 'reportValueUsageData';\n\n/** Value id passed to `reportValueUsage`. aiohomematic `const.REPORT_VALUE_USAGE_VALUE_ID`. */\nexport const REPORT_VALUE_USAGE_VALUE_ID = 'PRESS_SHORT';\n\n/** `getLinks` flags. aiohomematic `LinkCoordinator.get_device_links` passes `0`. */\nexport const GET_LINKS_FLAGS = 0;\n\n/** `reportValueUsage` ref counter that creates a central link. */\nexport const REPORT_VALUE_USAGE_REF_CREATE = 1;\n\n/** `reportValueUsage` ref counter that removes a central link. */\nexport const REPORT_VALUE_USAGE_REF_REMOVE = 0;\n\nfunction isStruct(value: XmlRpcValue): value is { [key: string]: XmlRpcValue } {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    !Array.isArray(value) &&\n    !(value instanceof Date) &&\n    !(value instanceof Uint8Array)\n  );\n}\n\nfunction structString(struct: { [key: string]: XmlRpcValue }, key: string): string | undefined {\n  const value = struct[key];\n  return typeof value === 'string' && value !== '' ? value : undefined;\n}\n\n/**\n * Narrow a `getLinks` result to direct links. A non-array (aiohomematic skips\n * those) or an entry without `SENDER`/`RECEIVER` is dropped. A missing `NAME`\n * is `\"\"` — never the address.\n */\nexport function parseChannelLinks(value: XmlRpcValue): HmChannelLink[] {\n  if (!Array.isArray(value)) return [];\n  const links: HmChannelLink[] = [];\n  for (const entry of value) {\n    if (!isStruct(entry)) continue;\n    const sender = structString(entry, 'SENDER');\n    const receiver = structString(entry, 'RECEIVER');\n    if (sender === undefined || receiver === undefined) continue;\n    const name = entry.NAME;\n    links.push({ sender, receiver, name: typeof name === 'string' ? name : '' });\n  }\n  return links;\n}\n\n/**\n * True when `getMetadata(..., \"reportValueUsageData\")` reports `PRESS_SHORT > 0`\n * (`Channel._has_central_link`).\n */\nexport function metadataHasCentralLink(value: XmlRpcValue): boolean {\n  if (!isStruct(value)) return false;\n  const counter = value[REPORT_VALUE_USAGE_VALUE_ID];\n  return typeof counter === 'number' && counter > 0;\n}\n","/**\n * Read-only diagnosis of \"why does a HmIP key not deliver PRESS_SHORT to this\n * client?\". It only reads; every section is read on its own and a failure is\n * reported in that section (`{ ok: false, error }`), never thrown.\n *\n * What it asks, and where each call comes from:\n * - Central link: XML-RPC `getMetadata(ch, \"reportValueUsageData\")`, the\n *   `PRESS_SHORT` counter (`central-link.ts`, aiohomematic\n *   `Channel._has_central_link`).\n * - Direct links: `getLinks(ch, 0)` (`central-link.ts`).\n * - Current values and key settings: `getParamset(ch, \"VALUES\")` and\n *   `getParamset(ch, \"MASTER\")`, raw.\n * - Device health: the maintenance channel `:0` VALUES `CONFIG_PENDING`,\n *   `UNREACH`, `RSSI_DEVICE`, `RSSI_PEER`, `UPDATE_PENDING`.\n * - ReGa (`../central/rega/key-diagnosis.ts`): the channel objects, their key\n *   data points with `Value()` / `Timestamp()` / `LastTimestamp()`, and the\n *   programs that reference those data points. It needs WebUI credentials;\n *   without them `rega` is `{ available: false, reason }`.\n * - This client: the last time each data point of the key channels and of `:0`\n *   received an event (`GenericDataPoint.lastUpdatedAt`, stamped from the\n *   callback router's `receivedAt`), and per interface the connection state,\n *   the latest event of any kind and whether the callback is considered alive\n *   (`ConnectionStateTracker`).\n *\n * Key channels are the channels of a key type ({@link KEY_CHANNEL_TYPES}) and\n * every channel whose VALUES paramset has `PRESS_SHORT`.\n */\nimport { interfaceNameOf } from '../central/management/ccu-key-programs.js';\nimport { KEY_DIAGNOSIS_PARAMETERS } from '../central/rega/key-diagnosis.js';\nimport type { ConnectionInfo } from '../central/central-unit.js';\nimport type { ModelChannel } from '../model/channel.js';\nimport type { ModelDevice } from '../model/device.js';\nimport { ParamsetKey } from '../support/constants.js';\nimport type { ParameterData, XmlRpcValue } from '../transport/xmlrpc/types.js';\nimport {\n  GET_LINKS_FLAGS,\n  REPORT_VALUE_USAGE_DATA,\n  metadataHasCentralLink,\n  parseChannelLinks,\n} from './central-link.js';\nimport type {\n  HmDiagnosisSection,\n  HmKeyCentralLink,\n  HmKeyChannelClientState,\n  HmKeyChannelDiagnosis,\n  HmKeyChannelXmlRpc,\n  HmKeyDeviceMaintenance,\n  HmKeyEventDiagnosis,\n  HmKeyRegaDiagnosis,\n  HmKeyRegaState,\n  HmParamsetValues,\n} from './types.js';\n\n/** Channel types that carry key presses (`KEY_TRANSCEIVER` is the HmIP / HM key channel). */\nexport const KEY_CHANNEL_TYPES: ReadonlySet<string> = new Set([\n  'KEY_TRANSCEIVER',\n  'KEY',\n  'VIRTUAL_KEY',\n]);\n\n/** The reads the diagnosis needs; {@link CentralUnit} and the management service provide them. */\nexport interface KeyDiagnosisSource {\n  getMetadata(interfaceId: string, address: string, dataId: string): Promise<XmlRpcValue>;\n  getLinks(interfaceId: string, address: string, flags: number): Promise<XmlRpcValue>;\n  readParamset(\n    interfaceId: string,\n    address: string,\n    paramsetKey: ParamsetKey,\n  ): Promise<Record<string, unknown>>;\n  getParamsetSpec(\n    interfaceId: string,\n    address: string,\n    paramsetKey: ParamsetKey,\n  ): Record<string, ParameterData> | undefined;\n  getConnectionInfo(interfaceId: string): ConnectionInfo;\n  /** The ReGa read; throws when ReGa is unavailable (no WebUI credentials, script failure). */\n  readRega(interfaceName: string, channelAddresses: readonly string[]): Promise<HmKeyRegaState>;\n  now(): number;\n}\n\nfunction messageOf(err: unknown): string {\n  return err instanceof Error ? err.message : String(err);\n}\n\nasync function section<T>(read: () => Promise<T>): Promise<HmDiagnosisSection<T>> {\n  try {\n    return { ok: true, data: await read() };\n  } catch (err: unknown) {\n    return { ok: false, error: messageOf(err) };\n  }\n}\n\nfunction pressShortCount(metadata: XmlRpcValue): number | null {\n  if (\n    typeof metadata !== 'object' ||\n    metadata === null ||\n    Array.isArray(metadata) ||\n    metadata instanceof Date ||\n    metadata instanceof Uint8Array\n  ) {\n    return null;\n  }\n  const counter = metadata['PRESS_SHORT'];\n  return typeof counter === 'number' ? counter : null;\n}\n\n/** Whether `channel` is a key channel: a key type, or a VALUES paramset with `PRESS_SHORT`. */\nfunction isKeyChannel(\n  source: KeyDiagnosisSource,\n  device: ModelDevice,\n  channel: ModelChannel,\n): boolean {\n  if (channel.type !== undefined && KEY_CHANNEL_TYPES.has(channel.type)) return true;\n  if (channel.dataPoint('PRESS_SHORT') !== undefined) return true;\n  const spec = source.getParamsetSpec(device.interfaceId, channel.address, ParamsetKey.VALUES);\n  return spec !== undefined && 'PRESS_SHORT' in spec;\n}\n\nfunction clientState(\n  channel: ModelChannel | undefined,\n  address: string,\n  withPress: boolean,\n): HmKeyChannelClientState {\n  const known = new Map((channel?.dataPoints ?? []).map((dp) => [dp.parameter, dp]));\n  const press = withPress ? KEY_DIAGNOSIS_PARAMETERS : [];\n  const rest = [...known.keys()].filter((parameter) => !press.includes(parameter));\n  return {\n    channelAddress: address,\n    parameters: [...press, ...rest].map((parameter) => {\n      const dp = known.get(parameter);\n      return {\n        parameter,\n        known: dp !== undefined,\n        lastEventAt: dp?.lastUpdatedAt ?? null,\n        value: dp?.value ?? null,\n      };\n    }),\n  };\n}\n\nasync function readChannelXmlRpc(\n  source: KeyDiagnosisSource,\n  interfaceId: string,\n  address: string,\n): Promise<HmKeyChannelXmlRpc> {\n  const [centralLink, directLinks, values, master] = await Promise.all([\n    section<HmKeyCentralLink>(async () => {\n      const metadata = await source.getMetadata(interfaceId, address, REPORT_VALUE_USAGE_DATA);\n      return {\n        pressShortCount: pressShortCount(metadata),\n        active: metadataHasCentralLink(metadata),\n      };\n    }),\n    section(async () =>\n      parseChannelLinks(await source.getLinks(interfaceId, address, GET_LINKS_FLAGS)),\n    ),\n    section<HmParamsetValues>(() => source.readParamset(interfaceId, address, ParamsetKey.VALUES)),\n    section<HmParamsetValues>(() => source.readParamset(interfaceId, address, ParamsetKey.MASTER)),\n  ]);\n  return { centralLink, directLinks, values, master };\n}\n\nasync function readMaintenance(\n  source: KeyDiagnosisSource,\n  interfaceId: string,\n  address: string,\n): Promise<HmDiagnosisSection<HmKeyDeviceMaintenance>> {\n  return section(async () => {\n    const values = await source.readParamset(interfaceId, address, ParamsetKey.VALUES);\n    return {\n      channelAddress: address,\n      configPending: values['CONFIG_PENDING'] ?? null,\n      unreach: values['UNREACH'] ?? null,\n      rssiDevice: values['RSSI_DEVICE'] ?? null,\n      rssiPeer: values['RSSI_PEER'] ?? null,\n      updatePending: values['UPDATE_PENDING'] ?? null,\n    };\n  });\n}\n\nasync function readRega(\n  source: KeyDiagnosisSource,\n  device: ModelDevice,\n  keyAddresses: readonly string[],\n): Promise<HmKeyRegaDiagnosis> {\n  if (keyAddresses.length === 0) return { available: true, state: { channels: [], programs: [] } };\n  try {\n    const state = await source.readRega(interfaceNameOf(device.interfaceId), keyAddresses);\n    return { available: true, state };\n  } catch (err: unknown) {\n    return { available: false, reason: messageOf(err) };\n  }\n}\n\n/** Diagnose the key events of `device`; see the file comment. Never throws for a section. */\nexport async function diagnoseKeyEvents(\n  source: KeyDiagnosisSource,\n  device: ModelDevice,\n): Promise<HmKeyEventDiagnosis> {\n  const keyChannels = device.channels.filter((channel) => isKeyChannel(source, device, channel));\n  const maintenanceAddress = `${device.address}:0`;\n  const [maintenance, channels, rega] = await Promise.all([\n    readMaintenance(source, device.interfaceId, maintenanceAddress),\n    Promise.all(\n      keyChannels.map(async (channel): Promise<HmKeyChannelDiagnosis> => ({\n        address: channel.address,\n        type: channel.type ?? null,\n        xmlRpc: await readChannelXmlRpc(source, device.interfaceId, channel.address),\n        client: clientState(channel, channel.address, true),\n      })),\n    ),\n    readRega(\n      source,\n      device,\n      keyChannels.map((channel) => channel.address),\n    ),\n  ]);\n  const info = source.getConnectionInfo(device.interfaceId);\n  return {\n    deviceAddress: device.address,\n    interfaceId: device.interfaceId,\n    takenAt: source.now(),\n    maintenance,\n    maintenanceClient: clientState(device.channel(maintenanceAddress), maintenanceAddress, false),\n    channels,\n    rega,\n    interfaceClient: {\n      interfaceId: device.interfaceId,\n      state: String(info.state),\n      lastEventAt: info.lastEventAt,\n      callbackAlive: info.callbackAlive,\n    },\n  };\n}\n","/**\n * Direct links and the switch-actuator link profile catalogue.\n *\n * Protocol (HomeMatic XML-RPC, as forwarded by the WebUI in eq-3/occu\n * `WebUI/www/api/methods/interface/addlink.tcl` and `removelink.tcl`):\n *\n *   addLink(sender, receiver, name, description)\n *   removeLink(sender, receiver)\n *   getLinks(address, 0)            → [{SENDER, RECEIVER, NAME, DESCRIPTION, FLAGS, …}]\n *   getParamset(receiver, sender)   → the RECEIVER's link paramset for that sender\n *   putParamset(receiver, sender, values)\n *\n * The argument order of the link paramset was checked on a real CCU (HmIP-RF):\n * `getParamset(receiver, sender)` returns the `SHORT_*` / `LONG_*` parameters,\n * `getParamset(sender, receiver)` an empty struct.\n *\n * Catalogue source: eq-3/occu\n * `WebUI/www/config/easymodes/SWITCH_VIRTUAL_RECEIVER/KEY_TRANSCEIVER.tcl` —\n * the WebUI's easy-mode profiles for a `KEY_TRANSCEIVER` sender linked to a\n * HmIP `SWITCH_VIRTUAL_RECEIVER`: `PROFILE_1` switch on, `PROFILE_2` switch\n * off, `PROFILE_3` switch on/off (toggle). Each value below is the FIRST entry\n * of that file's list, i.e. the value the WebUI writes; enum indices are the\n * CCU's own `VALUE_LIST` order (`getParamsetDescription(receiver, \"LINK\")`):\n * jump targets `NOP 0, ON_DELAY 1, RAMP_ON 2, ON 3, OFF_DELAY 4, RAMP_OFF 5,\n * OFF 6`; `PROFILE_ACTION_TYPE` `INACTIVE 0, JUMP 1, TOGGLE 2`.\n *\n * `none` is `<PREFIX>_PROFILE_ACTION_TYPE = 0` (`PROFILE_ACTION_TYPE_INACTIVE`)\n * and nothing else. For the long press this is what the WebUI writes when the\n * long key press is switched off (`getDeactivateLongKeypress`, eq-3/occu\n * `WebUI/www/config/easymodes/etc/uiElements.tcl`, `optionDisable 0`). No\n * easy-mode deactivates the SHORT press; short `none` uses the same\n * `PROFILE_ACTION_TYPE_INACTIVE` value from the CCU's `VALUE_LIST`.\n *\n * Matching is EXACT: a press half is a catalogue action only when every\n * parameter equals the value that action writes. The WebUI's matcher\n * (`get_cur_profile2`, eq-3/occu `WebUI/www/config/ic_common.tcl`) also accepts\n * alternatives (`{1 3 5}`, any time in a `range`); those read `custom` here, so\n * a timer or an alternative jump table is never silently overwritten — and the\n * exact match keeps the three actions disjoint (with the alternatives, the long\n * half of the CCU's default toggle link would also match `off`).\n */\n\nimport type { XmlRpcValue } from '../transport/xmlrpc/types.js';\nimport type { HmLinkPressAction, HmLinkProfile, HmSwitchLinkActions } from './types.js';\n\n/** `getLinks` row narrowed to what the facade exposes, before profile resolution. */\nexport interface ParsedLink {\n  readonly sender: string;\n  readonly receiver: string;\n  readonly name: string;\n  readonly description: string;\n}\n\n/** Sender channel type the catalogue covers (file name in the easymode dir). */\nexport const SWITCH_LINK_SENDER_TYPE = 'KEY_TRANSCEIVER';\n/** Receiver channel type the catalogue covers (the easymode dir name). */\nexport const SWITCH_LINK_RECEIVER_TYPE = 'SWITCH_VIRTUAL_RECEIVER';\n\ntype LinkParamValue = number | boolean;\ntype HalfValues = Readonly<Record<string, LinkParamValue>>;\ntype PressPrefix = 'SHORT' | 'LONG';\ntype ActiveAction = Exclude<HmLinkPressAction, 'none'>;\n\nconst ACTION_TYPE = 'PROFILE_ACTION_TYPE';\nconst ACTION_TYPE_INACTIVE = 0;\nconst ACTION_TYPE_JUMP = 1;\n\n/**\n * Parameters every KEY_TRANSCEIVER.tcl profile writes with the same value\n * (first list entry): conditions, condition thresholds, delays 0, on/off time\n * `BASE_1_H` (7) × 31 (the \"permanent\" choice), absolute time mode, JUMP.\n */\nconst COMMON: HalfValues = {\n  COND_VALUE_HI: 150,\n  COND_VALUE_LO: 50,\n  CT_OFF: 0,\n  CT_OFFDELAY: 0,\n  CT_ON: 0,\n  CT_ONDELAY: 0,\n  OFFDELAY_TIME_BASE: 0,\n  OFFDELAY_TIME_FACTOR: 0,\n  OFF_TIME_BASE: 7,\n  OFF_TIME_FACTOR: 31,\n  OFF_TIME_MODE: 0,\n  ONDELAY_TIME_BASE: 0,\n  ONDELAY_TIME_FACTOR: 0,\n  ON_TIME_BASE: 7,\n  ON_TIME_FACTOR: 31,\n  ON_TIME_MODE: 0,\n  MULTIEXECUTE: false,\n  [ACTION_TYPE]: ACTION_TYPE_JUMP,\n};\n\n/**\n * Per action, per press: the jump table. Short and long are listed apart\n * because KEY_TRANSCEIVER.tcl lists them apart; the written (first) values\n * happen to coincide.\n *\n * - on     PROFILE_1: JT_OFF {1 3 5}, JT_OFFDELAY {3 5}, JT_ON {1 3}, JT_ONDELAY {3 1}\n * - off    PROFILE_2: SHORT JT_OFF 6, JT_OFFDELAY 6, JT_ON {4 6}, JT_ONDELAY 6;\n *                     LONG  JT_OFF {6 1}, JT_OFFDELAY 6, JT_ON {4 6}, JT_ONDELAY {6 3}\n * - toggle PROFILE_3: JT_OFF {1 3}, JT_OFFDELAY {6 5}, JT_ON {4 6}, JT_ONDELAY {3 2}\n */\nconst JUMP_TABLES: Readonly<Record<ActiveAction, Readonly<Record<PressPrefix, HalfValues>>>> = {\n  on: {\n    SHORT: { JT_OFF: 1, JT_OFFDELAY: 3, JT_ON: 1, JT_ONDELAY: 3 },\n    LONG: { JT_OFF: 1, JT_OFFDELAY: 3, JT_ON: 1, JT_ONDELAY: 3 },\n  },\n  off: {\n    SHORT: { JT_OFF: 6, JT_OFFDELAY: 6, JT_ON: 4, JT_ONDELAY: 6 },\n    LONG: { JT_OFF: 6, JT_OFFDELAY: 6, JT_ON: 4, JT_ONDELAY: 6 },\n  },\n  toggle: {\n    SHORT: { JT_OFF: 1, JT_OFFDELAY: 6, JT_ON: 4, JT_ONDELAY: 3 },\n    LONG: { JT_OFF: 1, JT_OFFDELAY: 6, JT_ON: 4, JT_ONDELAY: 3 },\n  },\n};\n\n/** Checked in this order; the exact values make them disjoint. */\nconst ACTIVE_ACTIONS: readonly ActiveAction[] = ['toggle', 'on', 'off'];\n\nfunction halfValues(\n  prefix: PressPrefix,\n  action: HmLinkPressAction,\n): Record<string, LinkParamValue> {\n  if (action === 'none') return { [`${prefix}_${ACTION_TYPE}`]: ACTION_TYPE_INACTIVE };\n  const out: Record<string, LinkParamValue> = {};\n  for (const [param, value] of Object.entries({ ...COMMON, ...JUMP_TABLES[action][prefix] })) {\n    out[`${prefix}_${param}`] = value;\n  }\n  return out;\n}\n\n/**\n * The exact `putParamset(receiver, sender, …)` values for a short + long\n * action pair: the full KEY_TRANSCEIVER.tcl half for an active action, only\n * `PROFILE_ACTION_TYPE = 0` for `none`.\n */\nexport function switchLinkValues(actions: HmSwitchLinkActions): Record<string, LinkParamValue> {\n  return { ...halfValues('SHORT', actions.short), ...halfValues('LONG', actions.long) };\n}\n\n/** XML-RPC booleans and 0/1 integers compare equal; anything else must be identical. */\nfunction sameValue(actual: unknown, expected: LinkParamValue): boolean {\n  const normalised = typeof actual === 'boolean' ? (actual ? 1 : 0) : actual;\n  const want = typeof expected === 'boolean' ? (expected ? 1 : 0) : expected;\n  return normalised === want;\n}\n\nfunction classifyHalf(\n  paramset: Readonly<Record<string, unknown>>,\n  prefix: PressPrefix,\n): HmLinkPressAction | undefined {\n  const actionType = paramset[`${prefix}_${ACTION_TYPE}`];\n  if (actionType === undefined) return undefined;\n  if (sameValue(actionType, ACTION_TYPE_INACTIVE)) return 'none';\n  return ACTIVE_ACTIONS.find((action) =>\n    Object.entries(halfValues(prefix, action)).every(([param, value]) =>\n      sameValue(paramset[param], value),\n    ),\n  );\n}\n\n/** Classify a receiver link paramset into the switch catalogue, or `custom`. */\nexport function classifyLinkParamset(paramset: Readonly<Record<string, unknown>>): HmLinkProfile {\n  const short = classifyHalf(paramset, 'SHORT');\n  const long = classifyHalf(paramset, 'LONG');\n  if (short === undefined || long === undefined) return { kind: 'custom' };\n  return { kind: 'switch', short, long };\n}\n\n/** True when the catalogue applies to a sender / receiver channel type pair. */\nexport function isSwitchLinkPair(\n  senderType: string | undefined,\n  receiverType: string | undefined,\n): boolean {\n  return senderType === SWITCH_LINK_SENDER_TYPE && receiverType === SWITCH_LINK_RECEIVER_TYPE;\n}\n\nfunction isStruct(value: XmlRpcValue): value is { [key: string]: XmlRpcValue } {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    !Array.isArray(value) &&\n    !(value instanceof Date) &&\n    !(value instanceof Uint8Array)\n  );\n}\n\nfunction nonEmptyString(value: XmlRpcValue | undefined): string | undefined {\n  return typeof value === 'string' && value !== '' ? value : undefined;\n}\n\n/**\n * Narrow a `getLinks` result. A non-array is no links; an entry without\n * `SENDER` / `RECEIVER` is dropped; a missing `NAME` / `DESCRIPTION` is `\"\"`.\n */\nexport function parseLinks(value: XmlRpcValue): ParsedLink[] {\n  if (!Array.isArray(value)) return [];\n  const links: ParsedLink[] = [];\n  for (const entry of value) {\n    if (!isStruct(entry)) continue;\n    const sender = nonEmptyString(entry['SENDER']);\n    const receiver = nonEmptyString(entry['RECEIVER']);\n    if (sender === undefined || receiver === undefined) continue;\n    const name = entry['NAME'];\n    const description = entry['DESCRIPTION'];\n    links.push({\n      sender,\n      receiver,\n      name: typeof name === 'string' ? name : '',\n      description: typeof description === 'string' ? description : '',\n    });\n  }\n  return links;\n}\n","/**\n * {@link DeviceProfileRegistry} — maps a device TYPE to the custom-entity\n * configuration(s) it should produce. Matching is data-driven: the model name\n * is normalised (lowercased, `hb-`→`hm-`), then matched EXACTLY first and by\n * PREFIX second. A single model may aggregate multiple configs (e.g. lock plus\n * button-lock), and results are collected across all matching registrations.\n */\n\nimport type { CustomEntity, CustomEntityInit } from './base.js';\nimport type { DeviceProfile } from './profile.js';\n\n/** Constructor type for the custom-entity base class. */\nexport type CustomEntityCtor = new (init: CustomEntityInit) => CustomEntity;\n\n/**\n * One custom-entity recipe: which class to instantiate, against which profile,\n * for which absolute base channel(s) of the device.\n */\nexport interface DeviceConfig {\n  readonly entityClass: CustomEntityCtor;\n  readonly profile: DeviceProfile;\n  readonly channels: readonly number[];\n}\n\n/** Normalise a model name: lowercase and fold the `hb-` vendor prefix to `hm-`. */\nfunction normalizeModel(model: string): string {\n  return model.toLowerCase().replace('hb-', 'hm-');\n}\n\nexport class DeviceProfileRegistry {\n  readonly #byModel = new Map<string, DeviceConfig[]>();\n\n  /** Register one config under a model key (stored normalised). */\n  public register(model: string, config: DeviceConfig): void {\n    this.registerMultiple(model, [config]);\n  }\n\n  /** Register several configs under a model key, aggregating with any existing. */\n  public registerMultiple(model: string, configs: DeviceConfig[]): void {\n    const key = normalizeModel(model);\n    const existing = this.#byModel.get(key);\n    if (existing === undefined) {\n      this.#byModel.set(key, [...configs]);\n      return;\n    }\n    this.#byModel.set(key, [...existing, ...configs]);\n  }\n\n  /**\n   * Resolve the configs for a device type. Exact normalised match takes\n   * precedence; otherwise every registered key that is a PREFIX of the\n   * normalised model contributes. Returns `[]` when nothing matches.\n   */\n  public getConfigs(model: string): DeviceConfig[] {\n    const normalized = normalizeModel(model);\n\n    const exact = this.#byModel.get(normalized);\n    if (exact !== undefined) {\n      return [...exact];\n    }\n\n    const matches: DeviceConfig[] = [];\n    for (const [key, configs] of this.#byModel) {\n      if (normalized.startsWith(key)) {\n        matches.push(...configs);\n      }\n    }\n    return matches;\n  }\n}\n\n/** Process-wide singleton registry shared by the family registrations. */\nexport const deviceProfileRegistry = new DeviceProfileRegistry();\n","/**\n * Profile configuration — declarative description of how a device profile lays\n * its {@link Field}s out across channels. A {@link ChannelGroupConfig} is keyed\n * relative to a base channel; {@link resolve} rebases the relative offsets onto\n * the device's absolute channel indices.\n */\n\nimport { Field, type FieldMapping } from './fields.js';\n\n/**\n * Describes the field layout of one profile, relative to a base channel.\n *\n * @property primaryChannel — RELATIVE offset of the entity's primary channel\n *   from the base channel. Defaults to `0`.\n * @property secondaryChannels — additional relative channel offsets that belong\n *   to the same logical entity.\n * @property stateChannelOffset — relative offset of the channel carrying the\n *   primary state (used by some cover/lock profiles).\n * @property fields — field mappings resolved on the primary channel (plus their\n *   own `channelOffset`).\n * @property channelFields — extra field mappings keyed by RELATIVE channel\n *   offset (e.g. heating groups expose LEVEL on offset 0 and STATE on offset 3).\n * @property includeDefaultDataPoints — whether ch0 default data points (battery,\n *   RSSI…) apply. Groups set this to `false`.\n */\nexport interface ChannelGroupConfig {\n  readonly primaryChannel?: number;\n  readonly secondaryChannels?: readonly number[];\n  readonly stateChannelOffset?: number;\n  readonly fields: readonly FieldMapping[];\n  readonly channelFields?: Readonly<Record<number, readonly FieldMapping[]>>;\n  readonly includeDefaultDataPoints?: boolean;\n}\n\n/** A profile config is, for now, a single channel-group config. */\nexport type ProfileConfig = ChannelGroupConfig;\n\n/** Known device profiles. The value mirrors the key as a stable string. */\nexport enum DeviceProfile {\n  IP_SWITCH = 'IP_SWITCH',\n  RF_SWITCH = 'RF_SWITCH',\n  IP_DIMMER = 'IP_DIMMER',\n  RF_DIMMER = 'RF_DIMMER',\n  IP_COVER = 'IP_COVER',\n  RF_COVER = 'RF_COVER',\n  IP_BLIND = 'IP_BLIND',\n  IP_THERMOSTAT = 'IP_THERMOSTAT',\n  IP_THERMOSTAT_GROUP = 'IP_THERMOSTAT_GROUP',\n  RF_THERMOSTAT = 'RF_THERMOSTAT',\n  IP_LOCK = 'IP_LOCK',\n  RF_LOCK = 'RF_LOCK',\n}\n\n/**\n * Static profile → config table. Populated incrementally by the families. Task 2\n * seeds the switch profiles; later tasks add the rest.\n *\n * STATE lives on the entity's primary channel itself (channelOffset 0), so the\n * mapping is the same for IP and RF switches; the registration's base channel\n * selects the right physical channel.\n */\nexport const PROFILE_CONFIGS: Partial<Record<DeviceProfile, ChannelGroupConfig>> = {\n  [DeviceProfile.IP_SWITCH]: {\n    primaryChannel: 0,\n    fields: [{ field: Field.STATE, parameter: 'STATE' }],\n  },\n  [DeviceProfile.RF_SWITCH]: {\n    primaryChannel: 0,\n    fields: [{ field: Field.STATE, parameter: 'STATE' }],\n  },\n  [DeviceProfile.IP_THERMOSTAT]: {\n    primaryChannel: 0,\n    includeDefaultDataPoints: true,\n    fields: [\n      { field: Field.SETPOINT, parameter: 'SET_POINT_TEMPERATURE' },\n      { field: Field.TEMPERATURE, parameter: 'ACTUAL_TEMPERATURE', visible: true },\n      { field: Field.HUMIDITY, parameter: 'HUMIDITY', visible: true },\n      { field: Field.SET_POINT_MODE, parameter: 'SET_POINT_MODE' },\n      { field: Field.CONTROL_MODE, parameter: 'CONTROL_MODE' },\n      { field: Field.BOOST_MODE, parameter: 'BOOST_MODE' },\n      { field: Field.ACTIVE_PROFILE, parameter: 'ACTIVE_PROFILE' },\n    ],\n  },\n  [DeviceProfile.IP_THERMOSTAT_GROUP]: {\n    primaryChannel: 0,\n    includeDefaultDataPoints: false,\n    fields: [\n      { field: Field.SETPOINT, parameter: 'SET_POINT_TEMPERATURE' },\n      { field: Field.TEMPERATURE, parameter: 'ACTUAL_TEMPERATURE', visible: true },\n      { field: Field.HUMIDITY, parameter: 'HUMIDITY', visible: true },\n      { field: Field.SET_POINT_MODE, parameter: 'SET_POINT_MODE' },\n      { field: Field.CONTROL_MODE, parameter: 'CONTROL_MODE' },\n      { field: Field.BOOST_MODE, parameter: 'BOOST_MODE' },\n      { field: Field.ACTIVE_PROFILE, parameter: 'ACTIVE_PROFILE' },\n    ],\n    // Heating groups expose valve telemetry on channels relative to the base:\n    // offset 0 → LEVEL (valve %), offset 3 → STATE (valve open).\n    channelFields: {\n      0: [{ field: Field.LEVEL, parameter: 'LEVEL' }],\n      3: [{ field: Field.STATE, parameter: 'STATE' }],\n    },\n  },\n\n  // --- Light / Dimmer ---\n  // brightness (0..255) maps to the LEVEL float (0..1) on the primary channel.\n  [DeviceProfile.IP_DIMMER]: {\n    primaryChannel: 0,\n    fields: [{ field: Field.LEVEL, parameter: 'LEVEL', visible: true }],\n  },\n  [DeviceProfile.RF_DIMMER]: {\n    primaryChannel: 0,\n    fields: [{ field: Field.LEVEL, parameter: 'LEVEL', visible: true }],\n  },\n\n  // --- Cover / Blind ---\n  // position (0..100) maps to LEVEL; STOP is an action; DIRECTION reports travel.\n  // The DIRECTION field maps to ACTIVITY_STATE on HmIP and DIRECTION on RF, so\n  // only the parameter string differs between the IP and RF profiles.\n  // HmIP splits a cover across two channels and the difference is not\n  // cosmetic. Measured on a live CCU, HmIP-BROLL `00111BE992A8E5`:\n  //\n  //   :3 SHUTTER_TRANSMITTER       LEVEL 0.475  R-E   ← where the cover IS\n  //   :4 SHUTTER_VIRTUAL_RECEIVER  LEVEL 1.0    RWE   ← where you COMMAND it\n  //\n  // The transmitter is the actuator reporting itself, and its LEVEL refuses\n  // writes. The virtual receivers (:4, :5, :6) are link/group targets holding\n  // the last commanded extreme. Reading the receiver — which this profile used\n  // to do — gives 0 or 100 and nothing between, and is simply wrong whenever\n  // the cover rests part-way: it read 100 with the slat at 47.5 %.\n  //\n  // `readChannelOffset: -1` is that one channel down, relative to the\n  // registered base (4 → 3). Writes stay where the CCU accepts them.\n  [DeviceProfile.IP_COVER]: {\n    primaryChannel: 0,\n    fields: [\n      { field: Field.LEVEL, parameter: 'LEVEL', visible: true, readChannelOffset: -1 },\n      { field: Field.STOP, parameter: 'STOP' },\n      {\n        field: Field.DIRECTION,\n        parameter: 'ACTIVITY_STATE',\n        visible: true,\n        readChannelOffset: -1,\n      },\n    ],\n  },\n  [DeviceProfile.RF_COVER]: {\n    primaryChannel: 0,\n    fields: [\n      { field: Field.LEVEL, parameter: 'LEVEL', visible: true },\n      { field: Field.STOP, parameter: 'STOP' },\n      { field: Field.DIRECTION, parameter: 'DIRECTION', visible: true },\n    ],\n  },\n  // Blind extends cover with slat tilt (LEVEL_2). HmIP blinds carry both LEVEL\n  // and LEVEL_2 on the same combined channel.\n  // Same split as IP_COVER — see there. A blind's slat tilt (`LEVEL_2`) lives\n  // on the transmitter beside its position, for the same reason.\n  [DeviceProfile.IP_BLIND]: {\n    primaryChannel: 0,\n    fields: [\n      { field: Field.LEVEL, parameter: 'LEVEL', visible: true, readChannelOffset: -1 },\n      { field: Field.LEVEL_2, parameter: 'LEVEL_2', visible: true, readChannelOffset: -1 },\n      { field: Field.STOP, parameter: 'STOP' },\n      {\n        field: Field.DIRECTION,\n        parameter: 'ACTIVITY_STATE',\n        visible: true,\n        readChannelOffset: -1,\n      },\n    ],\n  },\n\n  // --- Lock ---\n  // HmIP locks report LOCK_STATE and are commanded via LOCK_TARGET_LEVEL.\n  [DeviceProfile.IP_LOCK]: {\n    primaryChannel: 0,\n    fields: [\n      { field: Field.LOCK_STATE, parameter: 'LOCK_STATE', visible: true },\n      { field: Field.LOCK_TARGET_LEVEL, parameter: 'LOCK_TARGET_LEVEL' },\n    ],\n  },\n  // Classic RF locks report a boolean STATE and expose a separate OPEN action.\n  [DeviceProfile.RF_LOCK]: {\n    primaryChannel: 0,\n    fields: [\n      { field: Field.STATE, parameter: 'STATE', visible: true },\n      { field: Field.OPEN, parameter: 'OPEN' },\n    ],\n  },\n};\n\n/** Resolve a profile config, throwing if the profile has no registered config. */\nexport function getProfileConfig(profile: DeviceProfile): ChannelGroupConfig {\n  const config = PROFILE_CONFIGS[profile];\n  if (config === undefined) {\n    throw new Error(`No profile config registered for profile: ${profile}`);\n  }\n  return config;\n}\n","/**\n * {@link CustomEntity} — a typed domain view aggregating several\n * {@link GenericDataPoint}s of one device by their {@link Field} role.\n *\n * A custom entity owns no value state of its own: high-level getters read the\n * underlying data points' live values, and commands route through an injected\n * {@link CustomEntityWriter} (the single validated write path). This keeps the\n * model the source of truth and the network concern out of the entity.\n */\n\nimport { DescriptionNotFoundError } from '../../support/errors.js';\nimport type { HmValue } from '../converter.js';\nimport type { GenericDataPoint } from '../data-point.js';\nimport { Field } from './fields.js';\n\n/**\n * Command sink injected into every custom entity. Implementations resolve the\n * data point for `(channelAddress, parameter)` and perform validate + convert +\n * send (the same path as `Homematic.setValue`). Tests inject a recording fake.\n */\nexport type CustomEntityWriter = (\n  channelAddress: string,\n  parameter: string,\n  value: HmValue,\n) => Promise<void>;\n\n/** Construction inputs for a {@link CustomEntity}. */\nexport interface CustomEntityInit {\n  readonly deviceAddress: string;\n  readonly primaryChannelAddress: string;\n  readonly type: string;\n  readonly dataPoints: Map<Field, GenericDataPoint>;\n  /**\n   * READ bindings that differ from the command binding, by field.\n   *\n   * Most fields are one data point: you read it and you write it. A few are\n   * not, and a cover is the case that forced this — measured on a live CCU,\n   * HmIP-BROLL `00111BE992A8E5`:\n   *\n   *   :3 SHUTTER_TRANSMITTER       LEVEL 0.475  R-E   ← where it IS\n   *   :4 SHUTTER_VIRTUAL_RECEIVER  LEVEL 1.0    RWE   ← where you COMMAND\n   *\n   * The transmitter is the device reporting itself and its LEVEL is not\n   * writable; the virtual receiver is the link/group target and holds the last\n   * commanded extreme. Binding both to the receiver — which is what this\n   * library did — reports 0 or 100 and nothing between, and is simply WRONG\n   * whenever the shutter rests part-way: 100 while the slat sat at 47.5 %.\n   *\n   * Absent for a field ⇒ read and write are the same data point, as before.\n   */\n  readonly readDataPoints?: Map<Field, GenericDataPoint>;\n  readonly writer: CustomEntityWriter;\n}\n\nexport abstract class CustomEntity {\n  public readonly deviceAddress: string;\n  public readonly primaryChannelAddress: string;\n  public readonly type: string;\n\n  /** Discriminator for the public union (e.g. `switch`, `climate`). */\n  public abstract readonly kind: string;\n\n  readonly #dataPoints: ReadonlyMap<Field, GenericDataPoint>;\n  readonly #readDataPoints: ReadonlyMap<Field, GenericDataPoint>;\n  readonly #writer: CustomEntityWriter;\n\n  public constructor(init: CustomEntityInit) {\n    this.deviceAddress = init.deviceAddress;\n    this.primaryChannelAddress = init.primaryChannelAddress;\n    this.type = init.type;\n    this.#dataPoints = new Map(init.dataPoints);\n    this.#readDataPoints = new Map(init.readDataPoints ?? []);\n    this.#writer = init.writer;\n  }\n\n  /**\n   * The data point a field is READ from — its read binding when it has one,\n   * the command binding otherwise.\n   *\n   * Every getter goes through here; {@link write} deliberately does not, so a\n   * field whose status lives on another channel is still commanded where the\n   * CCU accepts writes.\n   */\n  protected dp(field: Field): GenericDataPoint | undefined {\n    return this.#readDataPoints.get(field) ?? this.#dataPoints.get(field);\n  }\n\n  /** The data point a field is WRITTEN to. Never the read binding. */\n  protected writeDp(field: Field): GenericDataPoint | undefined {\n    return this.#dataPoints.get(field);\n  }\n\n  /** The resolved data point for a field; throws if it was not resolved. */\n  protected requireDp(field: Field): GenericDataPoint {\n    const dp = this.dp(field);\n    if (dp === undefined) {\n      throw new DescriptionNotFoundError(\n        `Field ${field} is not available on ${this.kind} entity ${this.primaryChannelAddress}`,\n      );\n    }\n    return dp;\n  }\n\n  /** Resolve the data point for a field and route a converted write to it. */\n  protected async write(field: Field, value: HmValue): Promise<void> {\n    // The COMMAND binding, never the read one: a transmitter channel reports\n    // the truth and refuses writes (`OPERATIONS` R-E), so routing a command\n    // there would fail on the CCU while looking right here.\n    const dp = this.writeDp(field);\n    if (dp === undefined) {\n      throw new DescriptionNotFoundError(\n        `Field ${field} is not writable on ${this.kind} entity ${this.primaryChannelAddress}`,\n      );\n    }\n    await this.#writer(dp.dpk.channelAddress, dp.parameter, value);\n  }\n\n  /**\n   * Every channel this entity touches — command bindings and read bindings —\n   * de-duplicated, in a stable order.\n   *\n   * A consumer that watches events per channel needs this: an HmIP cover reads\n   * its position on the transmitter and is commanded on the virtual receiver,\n   * so filtering events by {@link primaryChannelAddress} alone drops exactly\n   * the reports the entity exists to expose. That happened downstream and cost\n   * an evening — the library resolved the right channel and the consumer threw\n   * its events away.\n   */\n  public get channelAddresses(): readonly string[] {\n    const seen = new Set<string>();\n    for (const dp of [...this.#dataPoints.values(), ...this.#readDataPoints.values()]) {\n      seen.add(dp.dpk.channelAddress);\n    }\n    return [...seen];\n  }\n\n  /**\n   * The channels this entity READS from, when those differ from where it is\n   * commanded. Empty when every field is read where it is written.\n   *\n   * Separate from {@link channelAddresses} because knowing the union is not\n   * enough for a consumer that watches raw parameter events: an HmIP cover\n   * carries `LEVEL` on BOTH the transmitter and the virtual receiver, so\n   * accepting both and taking the last arrival is a coin toss that the\n   * receiver wins — 100 % against a slat at 47.5 %. A parameter available on a\n   * status channel must be taken from THERE and nowhere else.\n   */\n  public get statusChannelAddresses(): readonly string[] {\n    const seen = new Set<string>();\n    for (const dp of this.#readDataPoints.values()) seen.add(dp.dpk.channelAddress);\n    return [...seen];\n  }\n\n  /** True when at least one underlying data point was resolved. */\n  public get available(): boolean {\n    return this.#dataPoints.size > 0;\n  }\n\n  /**\n   * Subscribe to changes of every underlying data point. Returns a single\n   * unsubscribe function that detaches all of them.\n   */\n  public subscribe(cb: () => void): () => void {\n    const unsubscribers: Array<() => void> = [];\n    // BOTH maps, de-duplicated. A field whose status lives on another channel\n    // changes THERE, so subscribing to the command bindings alone would leave\n    // a consumer never woken by the value it actually reads — the fix above\n    // would be invisible to anybody watching.\n    const seen = new Set<GenericDataPoint>();\n    for (const dp of [...this.#dataPoints.values(), ...this.#readDataPoints.values()]) {\n      if (seen.has(dp)) continue;\n      seen.add(dp);\n      unsubscribers.push(dp.subscribe(() => cb()));\n    }\n    return () => {\n      for (const unsubscribe of unsubscribers) {\n        unsubscribe();\n      }\n    };\n  }\n}\n","/**\n * {@link SwitchEntity} — the reference custom-entity family. A simple on/off\n * switch whose state is the `STATE` boolean data point on its primary channel.\n */\n\nimport { CustomEntity } from './base.js';\nimport { Field } from './fields.js';\n\nexport class SwitchEntity extends CustomEntity {\n  public readonly kind = 'switch';\n\n  /** True when the underlying STATE data point reads `true`. */\n  public get isOn(): boolean {\n    return this.dp(Field.STATE)?.value === true;\n  }\n\n  /** Turn the switch on. */\n  public async turnOn(): Promise<void> {\n    await this.write(Field.STATE, true);\n  }\n\n  /** Turn the switch off. */\n  public async turnOff(): Promise<void> {\n    await this.write(Field.STATE, false);\n  }\n}\n","/**\n * {@link ClimateEntity} — the climate custom-entity family, covering HmIP\n * thermostats (eTRV / wall thermostats / temperature+humidity sensors) and the\n * HmIP-HEATING groups, which share the same IP-thermostat semantics.\n *\n * Like every {@link CustomEntity} it owns no value state: getters read the\n * underlying {@link GenericDataPoint}s by {@link Field} role, and commands route\n * converted writes through the injected writer. Fields:\n *   SETPOINT → SET_POINT_TEMPERATURE, TEMPERATURE → ACTUAL_TEMPERATURE,\n *   HUMIDITY → HUMIDITY, SET_POINT_MODE (0 AUTO / 1 MANU / 2 AWAY),\n *   CONTROL_MODE (the write/action mode dp: 0 AUTO / 1 MANU), BOOST_MODE,\n *   ACTIVE_PROFILE (week-program index), LEVEL (valve %), STATE (valve open).\n */\n\nimport { CustomEntity } from './base.js';\nimport { Field } from './fields.js';\n\n/** Temperature below which the thermostat is considered off. */\nconst OFF_TEMPERATURE = 4.5;\n/** Fallback minimum target temperature when dp metadata is absent. */\nconst FALLBACK_MIN_TEMP = 4.5;\n/** Fallback maximum target temperature when dp metadata is absent. */\nconst FALLBACK_MAX_TEMP = 30.5;\n/** SET_POINT_MODE: manual operation. */\nconst SET_POINT_MODE_MANU = 1;\n/** SET_POINT_MODE: away/holiday operation. */\nconst SET_POINT_MODE_AWAY = 2;\n/** CONTROL_MODE write value selecting automatic (week-program) operation. */\nconst CONTROL_MODE_AUTO = 0;\n/** CONTROL_MODE write value selecting manual operation. */\nconst CONTROL_MODE_MANU = 1;\n\n/** Supported high-level operating modes. */\nexport type ClimateMode = 'auto' | 'heat' | 'off';\n/** Supported presets. */\nexport type ClimatePreset = 'boost' | 'away' | 'week_program' | 'none';\n/** Current heating activity. */\nexport type ClimateActivity = 'heating' | 'idle' | 'off';\n\nexport class ClimateEntity extends CustomEntity {\n  public readonly kind = 'climate';\n\n  /** Fixed step for target temperature adjustments. */\n  public readonly targetTemperatureStep = 0.5;\n\n  /** The temperature unit reported by climate entities. */\n  public readonly temperatureUnit = '°C';\n\n  /** The set of modes this entity supports. */\n  public readonly modes: readonly ClimateMode[] = ['auto', 'heat', 'off'];\n\n  /** The measured room temperature, or `null` when unavailable. */\n  public get currentTemperature(): number | null {\n    return this.#numValue(Field.TEMPERATURE);\n  }\n\n  /** The configured target temperature, or `null` when unavailable. */\n  public get targetTemperature(): number | null {\n    return this.#numValue(Field.SETPOINT);\n  }\n\n  /** The measured humidity, or `null` when unavailable. */\n  public get currentHumidity(): number | null {\n    return this.#numValue(Field.HUMIDITY);\n  }\n\n  /** The minimum settable target temperature (from dp metadata, with fallback). */\n  public get minTemp(): number {\n    const min = this.dp(Field.SETPOINT)?.min;\n    return typeof min === 'number' ? min : FALLBACK_MIN_TEMP;\n  }\n\n  /** The maximum settable target temperature (from dp metadata, with fallback). */\n  public get maxTemp(): number {\n    const max = this.dp(Field.SETPOINT)?.max;\n    return typeof max === 'number' ? max : FALLBACK_MAX_TEMP;\n  }\n\n  /**\n   * The high-level operating mode: `off` when the target is at/below the off\n   * temperature, `heat` when SET_POINT_MODE is manual, otherwise `auto`.\n   */\n  public get mode(): ClimateMode {\n    const target = this.targetTemperature;\n    if (target !== null && target <= OFF_TEMPERATURE) {\n      return 'off';\n    }\n    return this.#numValue(Field.SET_POINT_MODE) === SET_POINT_MODE_MANU ? 'heat' : 'auto';\n  }\n\n  /**\n   * The active preset: `boost` while boosting, `away` while in away mode,\n   * `week_program` when a week program is active, otherwise `none`.\n   */\n  public get preset(): ClimatePreset {\n    if (this.dp(Field.BOOST_MODE)?.value === true) {\n      return 'boost';\n    }\n    if (this.#numValue(Field.SET_POINT_MODE) === SET_POINT_MODE_AWAY) {\n      return 'away';\n    }\n    const profile = this.#numValue(Field.ACTIVE_PROFILE);\n    return profile !== null && profile > 0 ? 'week_program' : 'none';\n  }\n\n  /**\n   * Current heating activity: `off` when the mode is off, `heating` when the\n   * valve LEVEL is positive or the valve STATE is open, otherwise `idle`.\n   */\n  public get activity(): ClimateActivity {\n    if (this.mode === 'off') {\n      return 'off';\n    }\n    const level = this.#numValue(Field.LEVEL);\n    if (level !== null && level > 0) {\n      return 'heating';\n    }\n    if (this.dp(Field.STATE)?.value === true) {\n      return 'heating';\n    }\n    return 'idle';\n  }\n\n  /** Set the target temperature, clamped to `[minTemp, maxTemp]`. */\n  public async setTemperature(temperature: number): Promise<void> {\n    const clamped = Math.min(Math.max(temperature, this.minTemp), this.maxTemp);\n    await this.write(Field.SETPOINT, clamped);\n  }\n\n  /**\n   * Switch operating mode. `auto`/`heat` set CONTROL_MODE; `off` switches to\n   * manual then drops the target to the off temperature.\n   */\n  public async setMode(mode: ClimateMode): Promise<void> {\n    if (mode === 'auto') {\n      await this.write(Field.CONTROL_MODE, CONTROL_MODE_AUTO);\n      return;\n    }\n    if (mode === 'heat') {\n      await this.write(Field.CONTROL_MODE, CONTROL_MODE_MANU);\n      return;\n    }\n    // off: switch to manual, then set the off temperature.\n    await this.write(Field.CONTROL_MODE, CONTROL_MODE_MANU);\n    await this.write(Field.SETPOINT, OFF_TEMPERATURE);\n  }\n\n  /** Enable or disable boost mode. */\n  public async setBoost(on: boolean): Promise<void> {\n    await this.write(Field.BOOST_MODE, on);\n  }\n\n  /** Select the active week-program index. */\n  public async setProfile(index: number): Promise<void> {\n    await this.write(Field.ACTIVE_PROFILE, index);\n  }\n\n  /** Read a field's numeric value, or `null` when absent/non-numeric. */\n  #numValue(field: Field): number | null {\n    const value = this.dp(field)?.value;\n    return typeof value === 'number' ? value : null;\n  }\n}\n","/**\n * Pure numeric conversions between user-facing scales (brightness 0..255,\n * position 0..100) and the CCU `LEVEL` domain (0..1 float). Inputs are clamped\n * to their valid range; the reverse conversions round to an integer.\n */\n\n/** Clamp `n` to the inclusive `[min, max]` range. */\nfunction clamp(n: number, min: number, max: number): number {\n  if (n < min) return min;\n  if (n > max) return max;\n  return n;\n}\n\n/** Brightness 0..255 → LEVEL 0..1 (clamped). */\nexport function brightnessToLevel(brightness: number): number {\n  return clamp(brightness, 0, 255) / 255;\n}\n\n/** LEVEL 0..1 → brightness 0..255 (clamped, rounded to int). */\nexport function levelToBrightness(level: number): number {\n  return Math.round(clamp(level, 0, 1) * 255);\n}\n\n/** Position 0..100 → LEVEL 0..1 (clamped). */\nexport function positionToLevel(position: number): number {\n  return clamp(position, 0, 100) / 100;\n}\n\n/** LEVEL 0..1 → position 0..100 (clamped, rounded to int). */\nexport function levelToPosition(level: number): number {\n  return Math.round(clamp(level, 0, 1) * 100);\n}\n","/**\n * {@link DimmerEntity} — the dimmable-light custom-entity family. A dimmer's\n * brightness is the `LEVEL` float (0..1) on its primary channel; user-facing\n * brightness is 0..255. Like every {@link CustomEntity} it owns no value state:\n * the getters read the underlying `LEVEL` data point and commands route\n * converted writes through the injected writer.\n */\n\nimport { CustomEntity } from './base.js';\nimport { Field } from './fields.js';\nimport { brightnessToLevel, levelToBrightness } from './helpers.js';\n\n/** Default brightness used by {@link DimmerEntity.turnOn} (full on). */\nconst FULL_BRIGHTNESS = 255;\n\nexport class DimmerEntity extends CustomEntity {\n  public readonly kind = 'light';\n\n  /** User-facing brightness 0..255 from LEVEL, or `null` when unavailable. */\n  public get brightness(): number | null {\n    const level = this.#level;\n    return level === null ? null : levelToBrightness(level);\n  }\n\n  /** True when the dimmer LEVEL is positive. */\n  public get isOn(): boolean {\n    const level = this.#level;\n    return level !== null && level > 0;\n  }\n\n  /** Turn the light on at `brightness` (0..255), full on by default. */\n  public async turnOn(brightness: number = FULL_BRIGHTNESS): Promise<void> {\n    await this.write(Field.LEVEL, brightnessToLevel(brightness));\n  }\n\n  /** Turn the light off (LEVEL 0). */\n  public async turnOff(): Promise<void> {\n    await this.write(Field.LEVEL, 0);\n  }\n\n  /** Set the brightness (0..255) by writing the converted LEVEL. */\n  public async setBrightness(brightness: number): Promise<void> {\n    await this.write(Field.LEVEL, brightnessToLevel(brightness));\n  }\n\n  /** The current LEVEL (0..1), or `null` when absent/non-numeric. */\n  get #level(): number | null {\n    const value = this.dp(Field.LEVEL)?.value;\n    return typeof value === 'number' ? value : null;\n  }\n}\n","/**\n * {@link CoverEntity} and {@link BlindEntity} — the cover/blind custom-entity\n * family. A cover's position is the `LEVEL` float (0..1) on its primary channel;\n * user-facing position is 0..100. `STOP` is an action and `DIRECTION` reports\n * the current travel ('UP'/'DOWN'/…). A blind additionally exposes slat tilt via\n * a second `LEVEL_2` float.\n *\n * Like every {@link CustomEntity} these own no value state: getters read the\n * underlying data points and commands route converted writes through the writer.\n */\n\nimport { CustomEntity } from './base.js';\nimport { Field } from './fields.js';\nimport { levelToPosition, positionToLevel } from './helpers.js';\n\n/**\n * What a cover's travel data point says.\n *\n * `stable` and `unknown` are deliberately NOT the same answer. HmIP's\n * `ACTIVITY_STATE` carries both and means different things by them — measured\n * on a live CCU, channel 4 of an HmIP-BROLL:\n *\n *     ACTIVITY_STATE  TYPE=ENUM  VALUE_LIST = UNKNOWN|UP|DOWN|STABLE\n *\n * `STABLE` is \"it has come to rest\"; `UNKNOWN` is the parameter's DEFAULT and\n * means the CCU has no opinion yet. A consumer that folds the two together\n * ends a move on a report that never claimed it ended.\n */\nexport type CoverTravel = 'opening' | 'closing' | 'stable' | 'unknown';\n\n/**\n * The travel members, by NAME, across both families.\n *\n * Matched by name rather than by index because the two value lists differ in\n * their MEMBERS and not merely their order: RF `DIRECTION` is\n * `NONE|UP|DOWN|UNDEFINED`, HmIP `ACTIVITY_STATE` is `UNKNOWN|UP|DOWN|STABLE`.\n * An index mapping would be a guess about a list that is right there in the\n * data point's own spec.\n */\nconst TRAVEL_BY_NAME: Readonly<Record<string, CoverTravel>> = {\n  UP: 'opening',\n  DOWN: 'closing',\n  STABLE: 'stable',\n  NONE: 'stable',\n  UNKNOWN: 'unknown',\n  UNDEFINED: 'unknown',\n};\n\nexport class CoverEntity extends CustomEntity {\n  public readonly kind: string = 'cover';\n\n  /** Current position 0..100 from LEVEL, or `null` when unavailable. */\n  public get currentPosition(): number | null {\n    const level = this.level;\n    return level === null ? null : levelToPosition(level);\n  }\n\n  /**\n   * True when the cover is fully closed (LEVEL 0).\n   *\n   * `false` here covers BOTH \"open\" and \"LEVEL has not been read yet\" — check\n   * {@link currentPosition} for `null` to tell them apart. Kept as a plain\n   * boolean because narrowing it would change every caller's type.\n   */\n  public get isClosed(): boolean {\n    return this.level === 0;\n  }\n\n  /**\n   * What the cover is doing, from its travel data point.\n   *\n   * The data point is `ACTIVITY_STATE` on HmIP and `DIRECTION` on RF; the\n   * profile maps whichever one the device has onto {@link Field.DIRECTION}, so\n   * this getter never needs to know which family it is looking at.\n   *\n   * The ENUM arrives already converted to its value-list member (the inbound\n   * converter resolves the CCU's index), so this reads names. A numeric value\n   * means the list could not be resolved: index 0 is the non-travelling member\n   * in both families, 1 is up and 2 is down.\n   */\n  public get travel(): CoverTravel {\n    const value = this.dp(Field.DIRECTION)?.value;\n    if (typeof value === 'string') {\n      return TRAVEL_BY_NAME[value.toUpperCase()] ?? 'unknown';\n    }\n    if (typeof value === 'number') {\n      if (value === 0) return 'stable';\n      if (value === 1) return 'opening';\n      if (value === 2) return 'closing';\n    }\n    return 'unknown';\n  }\n\n  /** True while the cover is travelling open. */\n  public get isOpening(): boolean {\n    return this.travel === 'opening';\n  }\n\n  /** True while the cover is travelling closed. */\n  public get isClosing(): boolean {\n    return this.travel === 'closing';\n  }\n\n  /** Open the cover fully (LEVEL 1). */\n  public async open(): Promise<void> {\n    await this.write(Field.LEVEL, 1);\n  }\n\n  /** Close the cover fully (LEVEL 0). */\n  public async close(): Promise<void> {\n    await this.write(Field.LEVEL, 0);\n  }\n\n  /** Stop the cover where it is. */\n  public async stop(): Promise<void> {\n    await this.write(Field.STOP, true);\n  }\n\n  /** Move the cover to `position` (0..100) via the converted LEVEL. */\n  public async setPosition(position: number): Promise<void> {\n    await this.write(Field.LEVEL, positionToLevel(position));\n  }\n\n  /** The current LEVEL (0..1), or `null` when absent/non-numeric. */\n  protected get level(): number | null {\n    const value = this.dp(Field.LEVEL)?.value;\n    return typeof value === 'number' ? value : null;\n  }\n}\n\nexport class BlindEntity extends CoverEntity {\n  public override readonly kind: string = 'blind';\n\n  /** Current slat tilt 0..100 from LEVEL_2, or `null` when unavailable. */\n  public get currentTiltPosition(): number | null {\n    const value = this.dp(Field.LEVEL_2)?.value;\n    return typeof value === 'number' ? levelToPosition(value) : null;\n  }\n\n  /**\n   * Move the blind to `position` (0..100), and when `tilt` (0..100) is given,\n   * also set the slat tilt via LEVEL_2. LEVEL is written first.\n   */\n  public override async setPosition(position: number, tilt?: number): Promise<void> {\n    await this.write(Field.LEVEL, positionToLevel(position));\n    if (tilt !== undefined) {\n      await this.write(Field.LEVEL_2, positionToLevel(tilt));\n    }\n  }\n}\n","/**\n * {@link IpLockEntity} and {@link RfLockEntity} — the lock custom-entity family.\n *\n * HmIP locks (IP_LOCK) report state via the `LOCK_STATE` string ('LOCKED' /\n * 'UNLOCKED') and are commanded via `LOCK_TARGET_LEVEL` ('LOCKED' / 'UNLOCKED' /\n * 'OPEN'). Classic RF locks (RF_LOCK) report a boolean `STATE` (false = locked,\n * true = unlocked) and expose a separate `OPEN` action.\n *\n * Like every {@link CustomEntity} these own no value state: getters read the\n * underlying data points and commands route writes through the injected writer.\n */\n\nimport { CustomEntity } from './base.js';\nimport { Field } from './fields.js';\n\n/** LOCK_STATE / LOCK_TARGET_LEVEL value: locked. */\nconst LOCK_LOCKED = 'LOCKED';\n/** LOCK_TARGET_LEVEL value: unlocked. */\nconst LOCK_UNLOCKED = 'UNLOCKED';\n/** LOCK_TARGET_LEVEL value: open (latch released). */\nconst LOCK_OPEN = 'OPEN';\n\nexport class IpLockEntity extends CustomEntity {\n  public readonly kind = 'lock';\n\n  /** True when LOCK_STATE reads 'LOCKED'. */\n  public get isLocked(): boolean {\n    return this.dp(Field.LOCK_STATE)?.value === LOCK_LOCKED;\n  }\n\n  /** Lock the door (LOCK_TARGET_LEVEL = 'LOCKED'). */\n  public async lock(): Promise<void> {\n    await this.write(Field.LOCK_TARGET_LEVEL, LOCK_LOCKED);\n  }\n\n  /** Unlock the door (LOCK_TARGET_LEVEL = 'UNLOCKED'). */\n  public async unlock(): Promise<void> {\n    await this.write(Field.LOCK_TARGET_LEVEL, LOCK_UNLOCKED);\n  }\n\n  /** Release the latch (LOCK_TARGET_LEVEL = 'OPEN'). */\n  public async open(): Promise<void> {\n    await this.write(Field.LOCK_TARGET_LEVEL, LOCK_OPEN);\n  }\n}\n\nexport class RfLockEntity extends CustomEntity {\n  public readonly kind = 'lock';\n\n  /** True when the boolean STATE is not `true` (false = locked). */\n  public get isLocked(): boolean {\n    return this.dp(Field.STATE)?.value !== true;\n  }\n\n  /** Lock the door (STATE = false). */\n  public async lock(): Promise<void> {\n    await this.write(Field.STATE, false);\n  }\n\n  /** Unlock the door (STATE = true). */\n  public async unlock(): Promise<void> {\n    await this.write(Field.STATE, true);\n  }\n\n  /** Release the latch (OPEN action). */\n  public async open(): Promise<void> {\n    await this.write(Field.OPEN, true);\n  }\n}\n","/**\n * {@link buildCustomEntities} — turns a {@link ModelDevice} into the typed\n * {@link CustomEntity} views declared for its type in the registry.\n *\n * For each matching {@link DeviceConfig}, and for each absolute base channel it\n * targets, the profile config's field mappings are rebased from relative\n * channel offsets onto the device's absolute channel addresses, resolved to the\n * device's live {@link GenericDataPoint}s, and handed to the entity class. A\n * config that resolves no data points is skipped (defensive).\n */\n\nimport type { ModelDevice } from '../device.js';\nimport type { GenericDataPoint } from '../data-point.js';\nimport type { CustomEntity, CustomEntityWriter } from './base.js';\nimport { Field, type FieldMapping } from './fields.js';\nimport { getProfileConfig, type ChannelGroupConfig } from './profile.js';\nimport { deviceProfileRegistry, type DeviceConfig } from './registry.js';\n\n/** Build a channel address from a device address and an absolute channel index. */\nfunction channelAddress(deviceAddress: string, channel: number): string {\n  return `${deviceAddress}:${channel}`;\n}\n\n/**\n * Resolve a set of field mappings against the device, at `baseChannel` plus each\n * mapping's relative `channelOffset`, accumulating into `target`.\n */\nfunction resolveFields(\n  device: ModelDevice,\n  baseChannel: number,\n  mappings: readonly FieldMapping[],\n  defaultOffset: number,\n  target: Map<Field, GenericDataPoint>,\n  readTarget: Map<Field, GenericDataPoint>,\n): void {\n  for (const mapping of mappings) {\n    const offset = mapping.channelOffset ?? defaultOffset;\n    const address = channelAddress(device.address, baseChannel + offset);\n    const dp = device.dataPoint(address, mapping.parameter);\n    if (dp !== undefined) {\n      target.set(mapping.field, dp);\n    }\n    // A field READ somewhere else than it is commanded (see\n    // `FieldMapping.readChannelOffset`). Resolved independently: a device\n    // whose transmitter channel is missing still gets its command binding,\n    // and vice versa — one absent half must not cost the other.\n    if (mapping.readChannelOffset === undefined) continue;\n    const readAddress = channelAddress(device.address, baseChannel + mapping.readChannelOffset);\n    const readDp = device.dataPoint(readAddress, mapping.parameter);\n    if (readDp !== undefined) {\n      readTarget.set(mapping.field, readDp);\n    }\n  }\n}\n\n/** Build the Field→GenericDataPoint map for one config at one base channel. */\nfunction buildDataPoints(\n  device: ModelDevice,\n  baseChannel: number,\n  profileConfig: ChannelGroupConfig,\n): { dataPoints: Map<Field, GenericDataPoint>; readDataPoints: Map<Field, GenericDataPoint> } {\n  const dataPoints = new Map<Field, GenericDataPoint>();\n  const readDataPoints = new Map<Field, GenericDataPoint>();\n\n  resolveFields(device, baseChannel, profileConfig.fields, 0, dataPoints, readDataPoints);\n\n  if (profileConfig.channelFields !== undefined) {\n    for (const [offsetKey, mappings] of Object.entries(profileConfig.channelFields)) {\n      const offset = Number(offsetKey);\n      resolveFields(device, baseChannel, mappings, offset, dataPoints, readDataPoints);\n    }\n  }\n\n  return { dataPoints, readDataPoints };\n}\n\n/** Build all custom entities declared for `device`, wired to `writer`. */\nexport function buildCustomEntities(\n  device: ModelDevice,\n  writer: CustomEntityWriter,\n): CustomEntity[] {\n  const configs: DeviceConfig[] = deviceProfileRegistry.getConfigs(device.type);\n  const entities: CustomEntity[] = [];\n\n  for (const config of configs) {\n    const profileConfig = getProfileConfig(config.profile);\n    const primaryOffset = profileConfig.primaryChannel ?? 0;\n\n    for (const baseChannel of config.channels) {\n      const { dataPoints, readDataPoints } = buildDataPoints(device, baseChannel, profileConfig);\n      if (dataPoints.size === 0) {\n        continue;\n      }\n      const primaryChannelAddress = channelAddress(device.address, baseChannel + primaryOffset);\n      entities.push(\n        new config.entityClass({\n          deviceAddress: device.address,\n          primaryChannelAddress,\n          type: device.type,\n          dataPoints,\n          readDataPoints,\n          writer,\n        }),\n      );\n    }\n  }\n\n  return entities;\n}\n","/**\n * Custom-entity public surface + family registrations. Importing this module\n * registers the built-in families with the singleton registry as a side effect.\n *\n * Each registration declares the absolute base channel(s) the entity occupies:\n * HmIP switch state lives on a dedicated channel (PS=3, BSM=4), while classic RF\n * switches expose STATE on channel 1.\n */\n\nimport { deviceProfileRegistry } from './registry.js';\nimport { DeviceProfile } from './profile.js';\nimport { SwitchEntity } from './switch.js';\nimport { ClimateEntity } from './climate.js';\nimport { DimmerEntity } from './light.js';\nimport { CoverEntity, BlindEntity } from './cover.js';\nimport { IpLockEntity, RfLockEntity } from './lock.js';\n\ndeviceProfileRegistry.register('HmIP-PS', {\n  entityClass: SwitchEntity,\n  profile: DeviceProfile.IP_SWITCH,\n  channels: [3],\n});\n\n// AUDIT, 2026-09-24, against this CCU's own `listDevices`: the\n// TRANSMITTER / VIRTUAL_RECEIVER split is the HmIP convention across every\n// family, not a cover quirk.\n//\n//   HmIP-BROLL   3:SHUTTER_TRANSMITTER   4,5,6:SHUTTER_VIRTUAL_RECEIVER\n//   HmIP-BSM     3:SWITCH_TRANSMITTER    4,5,6:SWITCH_VIRTUAL_RECEIVER\n//   HmIP-BS2     3,7:SWITCH_TRANSMITTER  4,5,6 + 8,9,10:SWITCH_VIRTUAL_RECEIVER\n//   HmIP-BWTH    9:SWITCH_TRANSMITTER    10,11,12:SWITCH_VIRTUAL_RECEIVER\n//\n// The switch registrations below therefore READ the receiver too. Measured on\n// five live relays (BS2 ×2 incl. its second circuit, BSM ×2), transmitter and\n// receiver agreed on every one: a relay is instantaneous, so the commanded\n// value and the reported value converge and the misalignment is INVISIBLE.\n// It is not absent — a relay switched at the wall, or one that fails to\n// follow, is known to the transmitter and not to the receiver — but it is not\n// something this checkout can demonstrate, so the registrations are left as\n// they are rather than changed on a symmetry argument.\n//\n// The DIMMER case is the one to watch: `HmIP-BDT` is registered on channel 4\n// and a dimmer's LEVEL ramps exactly as a cover's does, so it is likely wrong\n// in the same measurable way. There is no BDT on this CCU to prove it on.\ndeviceProfileRegistry.register('HmIP-BSM', {\n  entityClass: SwitchEntity,\n  profile: DeviceProfile.IP_SWITCH,\n  channels: [4],\n});\n\n// HmIP-BS2: dual brand-switch actuator. Live layout (real CCU): ch1-2\n// KEY_TRANSCEIVER, ch3/ch7 SWITCH_TRANSMITTER read-back, ch4-6/ch8-10\n// SWITCH_VIRTUAL_RECEIVER — one relay per group, primary = the first\n// VIRTUAL_RECEIVER of each (4 and 8).\ndeviceProfileRegistry.register('HmIP-BS2', {\n  entityClass: SwitchEntity,\n  profile: DeviceProfile.IP_SWITCH,\n  channels: [4, 8],\n});\n\ndeviceProfileRegistry.register('HM-LC-Sw', {\n  entityClass: SwitchEntity,\n  profile: DeviceProfile.RF_SWITCH,\n  channels: [1],\n});\n\n// --- Climate (IP thermostats + heating groups) ---\n\n// HmIP-HEATING: virtual heating group. Same IP-thermostat semantics, but the\n// group profile reads valve LEVEL/STATE from channels relative to base 1\n// (offset 0 → ch1 LEVEL, offset 3 → ch4 STATE) and has no ch0 default points.\ndeviceProfileRegistry.register('HmIP-HEATING', {\n  entityClass: ClimateEntity,\n  profile: DeviceProfile.IP_THERMOSTAT_GROUP,\n  channels: [1],\n});\n\n// Radiator thermostats.\ndeviceProfileRegistry.register('HmIP-eTRV', {\n  entityClass: ClimateEntity,\n  profile: DeviceProfile.IP_THERMOSTAT,\n  channels: [1],\n});\n\n// Wall thermostats.\ndeviceProfileRegistry.register('HmIP-WTH', {\n  entityClass: ClimateEntity,\n  profile: DeviceProfile.IP_THERMOSTAT,\n  channels: [1],\n});\ndeviceProfileRegistry.register('HmIP-BWTH', {\n  entityClass: ClimateEntity,\n  profile: DeviceProfile.IP_THERMOSTAT,\n  channels: [1],\n});\n\n// Temperature/humidity room thermostats. `HmIP-STH` is a prefix of `HmIP-STHD`\n// (and `HmIP-STHO` etc.), so a single registration covers the whole STH family\n// without producing duplicate entities for the longer variants.\ndeviceProfileRegistry.register('HmIP-STH', {\n  entityClass: ClimateEntity,\n  profile: DeviceProfile.IP_THERMOSTAT,\n  channels: [1],\n});\n\n// TODO: valve actuator family — HmIP-FALMOT-C12 is a multi-channel valve\n// actuator (12 channels), NOT a single thermostat. Registering it as a\n// ClimateEntity would mis-resolve, so it intentionally stays generic for now.\n\n// --- Light / Dimmer ---\n// HmIP dimmers carry LEVEL on a dedicated virtual-receiver channel: brand-mount\n// dimmer (BDT) ch4, flush-mount (FDT) ch2, plug dimmer (PDT) ch3.\ndeviceProfileRegistry.register('HmIP-BDT', {\n  entityClass: DimmerEntity,\n  profile: DeviceProfile.IP_DIMMER,\n  channels: [4],\n});\ndeviceProfileRegistry.register('HmIP-FDT', {\n  entityClass: DimmerEntity,\n  profile: DeviceProfile.IP_DIMMER,\n  channels: [2],\n});\ndeviceProfileRegistry.register('HmIP-PDT', {\n  entityClass: DimmerEntity,\n  profile: DeviceProfile.IP_DIMMER,\n  channels: [3],\n});\n// Classic RF dimmers expose LEVEL on channel 1.\ndeviceProfileRegistry.register('HM-LC-Dim', {\n  entityClass: DimmerEntity,\n  profile: DeviceProfile.RF_DIMMER,\n  channels: [1],\n});\n\n// --- Cover / Blind ---\n// HmIP roller shutters (BROLL/FROLL) and blinds (BBL/FBL) are COMMANDED on the\n// virtual-receiver channel 4 and REPORT on the transmitter channel 3. The\n// profile carries that split (`readChannelOffset`); the registration names the\n// command channel, which is the one a write must reach.\ndeviceProfileRegistry.register('HmIP-BROLL', {\n  entityClass: CoverEntity,\n  profile: DeviceProfile.IP_COVER,\n  channels: [4],\n});\ndeviceProfileRegistry.register('HmIP-FROLL', {\n  entityClass: CoverEntity,\n  profile: DeviceProfile.IP_COVER,\n  channels: [4],\n});\ndeviceProfileRegistry.register('HmIP-BBL', {\n  entityClass: BlindEntity,\n  profile: DeviceProfile.IP_BLIND,\n  channels: [4],\n});\ndeviceProfileRegistry.register('HmIP-FBL', {\n  entityClass: BlindEntity,\n  profile: DeviceProfile.IP_BLIND,\n  channels: [4],\n});\n// Classic RF blind/shutter actuators expose the cover on channel 1.\ndeviceProfileRegistry.register('HM-LC-Bl1', {\n  entityClass: CoverEntity,\n  profile: DeviceProfile.RF_COVER,\n  channels: [1],\n});\n\n// --- Lock ---\n// HmIP door-lock drive (DLD) carries LOCK_STATE/LOCK_TARGET_LEVEL on channel 1.\ndeviceProfileRegistry.register('HmIP-DLD', {\n  entityClass: IpLockEntity,\n  profile: DeviceProfile.IP_LOCK,\n  channels: [1],\n});\n// Classic RF key/lock (HM-Sec-Key) exposes STATE/OPEN on channel 1.\ndeviceProfileRegistry.register('HM-Sec-Key', {\n  entityClass: RfLockEntity,\n  profile: DeviceProfile.RF_LOCK,\n  channels: [1],\n});\n\nexport { Field } from './fields.js';\nexport { CustomEntity, type CustomEntityWriter, type CustomEntityInit } from './base.js';\nexport { buildCustomEntities } from './resolve.js';\nexport { SwitchEntity } from './switch.js';\nexport {\n  ClimateEntity,\n  type ClimateMode,\n  type ClimatePreset,\n  type ClimateActivity,\n} from './climate.js';\nexport { DimmerEntity } from './light.js';\nexport { CoverEntity, BlindEntity } from './cover.js';\nexport { IpLockEntity, RfLockEntity } from './lock.js';\nexport { DeviceProfile, getProfileConfig } from './profile.js';\nexport { deviceProfileRegistry, type DeviceConfig } from './registry.js';\n","/**\n * A minimal, dependency-free, type-safe event emitter.\n *\n * Generic over an event map `TMap` (event name → payload type). Listeners are\n * stored in a `Map<key, Set<listener>>`, which gives O(1) add/remove and\n * preserves insertion order on iteration. A listener that throws is isolated:\n * its error is routed to the optional `onError` handler (or swallowed) so it\n * never prevents the remaining listeners from running.\n *\n * Void payloads: an event whose payload type is `void` (e.g. `ready`) is\n * emitted with no second argument — `emit('ready')` — thanks to the\n * variadic-rest signature that resolves to `[]` for `void` payloads.\n */\n\n/** A listener for a payload of type `P`. */\ntype Listener<P> = (payload: P) => void;\n\n/** Maps a payload type to the trailing args of `emit` (`[]` when `void`). */\ntype EmitArgs<P> = P extends void ? [] : [payload: P];\n\nexport class TypedEventEmitter<TMap extends Record<string, unknown>> {\n  readonly #listeners = new Map<keyof TMap, Set<Listener<unknown>>>();\n  readonly #onError?: (error: unknown) => void;\n\n  /**\n   * @param onError Optional handler invoked when a listener throws. When\n   * omitted, listener errors are swallowed.\n   */\n  public constructor(onError?: (error: unknown) => void) {\n    if (onError !== undefined) {\n      this.#onError = onError;\n    }\n  }\n\n  /** Subscribe to `event`. Returns an unsubscribe function. */\n  public on<K extends keyof TMap>(event: K, listener: Listener<TMap[K]>): () => void {\n    const set = this.#listeners.get(event) ?? new Set<Listener<unknown>>();\n    set.add(listener as Listener<unknown>);\n    this.#listeners.set(event, set);\n    return () => {\n      this.off(event, listener);\n    };\n  }\n\n  /**\n   * Subscribe to `event` for a single delivery. Returns an unsubscribe function\n   * that also cancels the pending one-shot before it fires.\n   */\n  public once<K extends keyof TMap>(event: K, listener: Listener<TMap[K]>): () => void {\n    const wrapper: Listener<TMap[K]> = (payload) => {\n      off();\n      listener(payload);\n    };\n    const off = this.on(event, wrapper);\n    return off;\n  }\n\n  /** Remove a previously-registered listener for `event`. */\n  public off<K extends keyof TMap>(event: K, listener: Listener<TMap[K]>): void {\n    const set = this.#listeners.get(event);\n    if (set === undefined) return;\n    set.delete(listener as Listener<unknown>);\n    if (set.size === 0) {\n      this.#listeners.delete(event);\n    }\n  }\n\n  /**\n   * Emit `event` to all its listeners. For void-payload events, call with no\n   * payload argument: `emit('ready')`. A throwing listener is isolated and its\n   * error routed to `onError` (or swallowed); remaining listeners still run.\n   */\n  public emit<K extends keyof TMap>(event: K, ...args: EmitArgs<TMap[K]>): void {\n    const set = this.#listeners.get(event);\n    if (set === undefined) return;\n    const payload = args[0] as TMap[K];\n    // Snapshot so once()-driven mutation during iteration is safe.\n    for (const listener of [...set]) {\n      try {\n        (listener as Listener<TMap[K]>)(payload);\n      } catch (error: unknown) {\n        this.#onError?.(error);\n      }\n    }\n  }\n}\n","/**\n * {@link Homematic} — the public, transport-agnostic facade of the library.\n *\n * It wraps the internal {@link CentralUnit} (Phase 1 transport + Phase 2 device\n * graph + reconnection) and exposes a clean, event-driven surface: a global\n * `valueChanged` stream, lifecycle events, immutable device snapshots, a\n * validated `setValue`, and device-configuration (MASTER paramset) building\n * blocks. No transport/central/model types leak through its signatures.\n *\n * On {@link Homematic.start} it builds the domain model from the central's\n * registry, indexes every {@link GenericDataPoint} by id, and subscribes to the\n * central's {@link EventBus}, re-emitting each internal event as a typed public\n * event through the {@link TypedEventEmitter}.\n */\n\nimport { CentralUnit, type JsonRpcClientLike } from '../central/central-unit.js';\nimport type { HubFetcher } from '../central/hub/hub-fetcher.js';\nimport type { CcuManagement } from '../central/management/ccu-management.js';\nimport type { SystemVariable } from '../central/hub/sysvar.js';\nimport type { HmProgramRecord } from '../central/hub/program.js';\nimport type { InterfaceClient } from '../transport/interface-client.js';\nimport type { StorageBackend } from '../central/store/storage-backend.js';\nimport type { DeviceNode } from '../central/graph.js';\nimport type { ParameterData } from '../transport/xmlrpc/types.js';\nimport { Interface, ParameterType, ParamsetKey, isWritable } from '../support/constants.js';\nimport {\n  BaseHomematicError,\n  ClientError,\n  ValidationError,\n  DescriptionNotFoundError,\n} from '../support/errors.js';\nimport { makeDpk, dpkToUniqueId, type DataPointKey } from '../support/dpk.js';\nimport { buildModel, buildDevice, interfaceFamilyOf } from '../model/model-builder.js';\nimport { GenericDataPoint } from '../model/data-point.js';\nimport { convertFromCcu, convertToCcu } from '../model/converter.js';\nimport { parameterSpecFromData } from '../central/graph.js';\nimport type { ModelDevice } from '../model/device.js';\nimport { diagnoseKeyEvents } from './key-event-diagnosis.js';\nimport {\n  GET_LINKS_FLAGS,\n  REPORT_VALUE_USAGE_DATA,\n  REPORT_VALUE_USAGE_REF_CREATE,\n  REPORT_VALUE_USAGE_REF_REMOVE,\n  REPORT_VALUE_USAGE_VALUE_ID,\n  metadataHasCentralLink,\n  parseChannelLinks,\n} from './central-link.js';\nimport {\n  classifyLinkParamset,\n  isSwitchLinkPair,\n  parseLinks,\n  switchLinkValues,\n  type ParsedLink,\n} from './link-profile.js';\nimport type { CcuTopology } from '../central/management/ccu-topology.js';\nimport { interfaceNameOf } from '../central/management/ccu-key-programs.js';\nimport {\n  buildCustomEntities,\n  CustomEntity,\n  ClimateEntity,\n  SwitchEntity,\n  DimmerEntity,\n  CoverEntity,\n  BlindEntity,\n  IpLockEntity,\n  RfLockEntity,\n  type CustomEntityWriter,\n  type ClimateMode,\n} from '../model/custom/index.js';\nimport { TypedEventEmitter } from './emitter.js';\nimport type { HomematicEventMap } from './events.js';\nimport type {\n  DataPointRef,\n  HmCcuInfo,\n  HmChannel,\n  HmChannelLinkState,\n  HmDeviceRename,\n  HmLink,\n  HmLinkPressAction,\n  HmLinkProfile,\n  HmNamedObject,\n  HmRenameDeviceOptions,\n  HmRoom,\n  HmSwitchLinkActions,\n  HmConfigParam,\n  HmCustomEntity,\n  HmDataPoint,\n  HmDevice,\n  HmGroup,\n  HmGroupCreate,\n  HmGroupUpdate,\n  HmInstallModeRequest,\n  HmKeyEventDiagnosis,\n  HmKeyProgramReference,\n  HmKeyEventProgram,\n  HmKeyEventProgramInput,\n  HmKeyEventProgramResult,\n  HmInterfaceInfo,\n  HmProgram,\n  HmServiceMessage,\n  HmSysVar,\n  HmValue,\n} from './types.js';\n\n/** Local callback-server binding for the facade. */\nexport interface HomematicCallback {\n  readonly host: string;\n  readonly port: number;\n}\n\n/** WebUI credentials for JSON-RPC name/room metadata. */\nexport interface HomematicCredentials {\n  readonly username: string;\n  readonly password: string;\n}\n\n/** Cache directory / toggle. */\nexport interface HomematicCache {\n  readonly dir?: string;\n  readonly enabled?: boolean;\n}\n\n/** Construction options for {@link Homematic}. */\nexport interface HomematicOptions {\n  /** CCU host name or IP. */\n  readonly host: string;\n  /** Interface names, e.g. `'HmIP-RF'`, `'BidCos-RF'`. */\n  readonly interfaces: readonly string[];\n  readonly credentials?: HomematicCredentials;\n  readonly callback: HomematicCallback;\n  readonly cache?: HomematicCache;\n  readonly tls?: boolean;\n  /** Logical central name; defaults to `'nodehomematic'`. */\n  readonly centralName?: string;\n}\n\nconst DEFAULT_CENTRAL_NAME = 'nodehomematic';\n\n/**\n * Module-level symbol marking the INTERNAL test-construction path. It is NOT\n * exported from the package entrypoint (`src/index.ts`), so it never reaches\n * the published surface; tests import it directly from this module.\n */\nexport const HOMEMATIC_TEST_INIT: unique symbol = Symbol('nodehomematic.test-init');\n\n/**\n * Test-only injectables, forwarded into the {@link CentralUnit} the facade\n * builds. Never exported from the package entrypoint — referencing internal\n * transport/central types here would otherwise bleed them into the public\n * `.d.ts`. CRUCIAL: this type is referenced ONLY by the (non-exported)\n * {@link createHomematicForTest} free function, never by a member of the\n * {@link Homematic} class, so it cannot leak the internal type graph into the\n * published declaration of `Homematic`.\n */\nexport interface HomematicTestInjectables {\n  /**\n   * Inject a fully-constructed {@link CentralUnit}. When supplied it is used\n   * verbatim and the other CCU options are ignored; only `interfaces` is still\n   * validated so an empty/unknown configuration fails fast.\n   */\n  readonly central?: CentralUnit;\n  readonly storageBackend?: StorageBackend;\n  readonly makeInterfaceClient?: (iface: Interface) => InterfaceClient;\n  readonly jsonClient?: JsonRpcClientLike;\n}\n\n/**\n * Module-private channel handing test injectables to the next {@link Homematic}\n * constructor call. Kept off the class so the published `Homematic` type never\n * references the internal {@link HomematicTestInjectables} graph. Marked with\n * {@link HOMEMATIC_TEST_INIT} as a defensive sanity check.\n */\nlet pendingTestInjectables:\n  | { readonly [HOMEMATIC_TEST_INIT]: true; readonly injectables: HomematicTestInjectables }\n  | undefined;\n\n/**\n * INTERNAL test-construction helper. Builds a {@link Homematic} wiring its\n * {@link CentralUnit} from the supplied {@link HomematicTestInjectables}. NOT\n * exported from the package entrypoint; tests import it directly from this\n * module. The injectables travel through a module-private variable rather than\n * the public constructor signature, so the published `Homematic` declaration\n * stays free of internal types.\n */\nexport function createHomematicForTest(\n  options: HomematicOptions,\n  injectables: HomematicTestInjectables,\n): Homematic {\n  pendingTestInjectables = { [HOMEMATIC_TEST_INIT]: true, injectables };\n  try {\n    return new Homematic(options);\n  } finally {\n    pendingTestInjectables = undefined;\n  }\n}\n\n/** Map a public interface string to the internal {@link Interface} enum. */\nfunction toInterface(name: string): Interface {\n  const match = (Object.values(Interface) as string[]).includes(name)\n    ? (name as Interface)\n    : undefined;\n  if (match === undefined) {\n    throw new ValidationError(`Unknown interface \"${name}\".`);\n  }\n  return match;\n}\n\n/** Device address owning a channel address (`DEV:idx` → `DEV`). */\nconst CHANNEL_ADDRESS_PATTERN = /^[0-9A-Za-z_-]+:\\d+$/;\nconst PRESS_ACTIONS: ReadonlySet<string> = new Set<HmLinkPressAction>([\n  'toggle',\n  'on',\n  'off',\n  'none',\n]);\n\n/** Throw unless `address` is shaped like a channel address (`DEVICE:index`). */\nfunction requireChannelAddress(address: string): void {\n  if (!CHANNEL_ADDRESS_PATTERN.test(address)) {\n    throw new ValidationError(`Invalid channel address \"${address}\".`);\n  }\n}\n\n/** Throw unless `action` is a catalogue press action (callers may be untyped JS). */\nfunction requirePressAction(action: string): void {\n  if (!PRESS_ACTIONS.has(action)) {\n    throw new ValidationError(`Unknown press action \"${action}\".`);\n  }\n}\n\nfunction deviceAddressOf(channelAddress: string): string {\n  const colon = channelAddress.lastIndexOf(':');\n  return colon === -1 ? channelAddress : channelAddress.slice(0, colon);\n}\n\n/**\n * Build the {@link CentralUnit} backing a facade. Validates `interfaces`, then\n * either reuses an injected central (tests) or constructs a real one, forwarding\n * any test injectables. Injectables are empty for public construction.\n */\nfunction buildCentral(\n  options: HomematicOptions,\n  injectables: HomematicTestInjectables,\n): CentralUnit {\n  const interfaces = options.interfaces.map(toInterface);\n  if (interfaces.length === 0) {\n    throw new ValidationError('At least one interface is required.');\n  }\n  if (injectables.central !== undefined) {\n    return injectables.central;\n  }\n  return new CentralUnit({\n    centralName: options.centralName ?? DEFAULT_CENTRAL_NAME,\n    host: options.host,\n    interfaces,\n    callback: options.callback,\n    ...(options.credentials !== undefined ? { credentials: options.credentials } : {}),\n    ...(options.cache !== undefined ? { cache: options.cache } : {}),\n    ...(options.tls !== undefined ? { tls: options.tls } : {}),\n    ...(injectables.storageBackend !== undefined\n      ? { storageBackend: injectables.storageBackend }\n      : {}),\n    ...(injectables.makeInterfaceClient !== undefined\n      ? { makeInterfaceClient: injectables.makeInterfaceClient }\n      : {}),\n    ...(injectables.jsonClient !== undefined ? { jsonClient: injectables.jsonClient } : {}),\n  });\n}\n\nexport class Homematic {\n  readonly #central: CentralUnit;\n  readonly #emitter: TypedEventEmitter<HomematicEventMap>;\n  /** Guard against re-entrant error emission when an `error` listener throws. */\n  #emittingError = false;\n\n  /** dpId (lowercased unique id) → live data point. */\n  readonly #dataPointsById = new Map<string, GenericDataPoint>();\n  /** Device address → model device. */\n  readonly #devicesByAddress = new Map<string, ModelDevice>();\n\n  /** Every live custom entity, in build order. */\n  #customEntityList: CustomEntity[] = [];\n  /** `device:channel` → live custom entity, for command routing. */\n  readonly #customEntitiesByKey = new Map<string, CustomEntity>();\n\n  readonly #unsubscribers: Array<() => void> = [];\n  #started = false;\n\n  // --- hub layer (Phase 5) ---------------------------------------------------\n  /** Bound hub fetcher, or undefined when no JSON-RPC client is available. */\n  #hub: HubFetcher | undefined;\n  /** CCU-management service, built on first use, cleared at stop(). */\n  #management: CcuManagement | undefined;\n  /** Snapshot of system variables, refreshed on start / refreshHub. */\n  #sysvars: SystemVariable[] = [];\n  /** Snapshot of programs, refreshed on start / refreshHub. */\n  #programs: HmProgramRecord[] = [];\n  /** Device address → its aggregated room names (union of its channels'). */\n  #roomsByDevice = new Map<string, string[]>();\n  /** Device address → its aggregated function names (union of its channels'). */\n  #functionsByDevice = new Map<string, string[]>();\n  /** Device/channel address → the name a rename on this facade made the CCU store. */\n  readonly #renamedNames = new Map<string, string>();\n\n  /**\n   * Build a facade that owns a real {@link CentralUnit} for `options`. (Tests\n   * inject a pre-built central / transport stubs through the non-exported\n   * {@link createHomematicForTest}, which never widens this public signature.)\n   */\n  public constructor(options: HomematicOptions) {\n    const injectables = pendingTestInjectables?.injectables ?? {};\n    this.#central = buildCentral(options, injectables);\n    this.#emitter = new TypedEventEmitter<HomematicEventMap>((error) =>\n      this.#onListenerError(error),\n    );\n  }\n\n  // --- public event API -----------------------------------------------------\n\n  /** Subscribe to a public event. Returns an unsubscribe function. */\n  public on<K extends keyof HomematicEventMap>(\n    event: K,\n    listener: (payload: HomematicEventMap[K]) => void,\n  ): () => void {\n    return this.#emitter.on(event, listener);\n  }\n\n  /** Subscribe to a public event for a single delivery. */\n  public once<K extends keyof HomematicEventMap>(\n    event: K,\n    listener: (payload: HomematicEventMap[K]) => void,\n  ): () => void {\n    return this.#emitter.once(event, listener);\n  }\n\n  /** Remove a previously-registered public event listener. */\n  public off<K extends keyof HomematicEventMap>(\n    event: K,\n    listener: (payload: HomematicEventMap[K]) => void,\n  ): void {\n    this.#emitter.off(event, listener);\n  }\n\n  // --- lifecycle ------------------------------------------------------------\n\n  /** Start the central, build the model from its registry, and subscribe. */\n  public async start(): Promise<void> {\n    if (this.#started) return;\n    this.#started = true;\n    try {\n      await this.#central.start();\n      this.#rebuildModel(this.#central.registry.getAll());\n      this.#subscribe();\n      // Initial values may have been seeded by the central during start(),\n      // before the facade built its model / subscribed. Backfill those data\n      // points from the central's value cache so devices() shows values\n      // immediately. Live pushes flow through the valueReceived subscription.\n      this.#backfillSeededValues();\n      await this.#initHub();\n    } catch (error: unknown) {\n      // Roll back so a failed start does not wedge the facade: a subsequent\n      // start() attempt is allowed (and will call central.start() again).\n      this.#started = false;\n      throw error;\n    }\n  }\n\n  /** Stop the central and clear all subscriptions and the model index. */\n  public async stop(): Promise<void> {\n    if (!this.#started) return;\n    this.#started = false;\n    for (const off of this.#unsubscribers) off();\n    this.#unsubscribers.length = 0;\n    await this.#central.stop();\n    this.#dataPointsById.clear();\n    this.#devicesByAddress.clear();\n    this.#customEntityList = [];\n    this.#customEntitiesByKey.clear();\n    this.#hub = undefined;\n    this.#management = undefined;\n    this.#sysvars = [];\n    this.#programs = [];\n    this.#roomsByDevice.clear();\n    this.#functionsByDevice.clear();\n    this.#renamedNames.clear();\n  }\n\n  // --- public read surface --------------------------------------------------\n\n  /**\n   * An immutable snapshot of every known device. The `rooms`/`functions` carried\n   * by each device are the union of the model's own metadata and the hub's\n   * channel-address-keyed ReGa mapping (Phase 5), aggregated to the device.\n   */\n  public devices(): HmDevice[] {\n    return [...this.#devicesByAddress.values()].map((device) =>\n      toHmDevice(\n        device,\n        this.#roomsByDevice.get(device.address),\n        this.#functionsByDevice.get(device.address),\n        this.#renamedNames,\n      ),\n    );\n  }\n\n  /**\n   * Re-read device and channel names from the CCU WebUI, so a rename made on\n   * the CCU (or a name given after pairing) shows in `devices()`. Keeps the\n   * names it has when there are no WebUI credentials or the read fails.\n   */\n  public async refreshNames(): Promise<void> {\n    const details = await this.#central.refreshDetails();\n    if (details === undefined) return;\n    this.#renamedNames.clear();\n    for (const [address, name] of details.nameByAddress) this.#renamedNames.set(address, name);\n  }\n\n  /** Current value of a data point (resolving the ref). */\n  public getValue(ref: DataPointRef): HmValue {\n    return this.#resolveDataPoint(ref).value;\n  }\n\n  /**\n   * Validate + convert `value` against the data point's metadata (throwing\n   * BEFORE any network call on an invalid value), then write it to the CCU.\n   */\n  public async setValue(ref: DataPointRef, value: HmValue): Promise<void> {\n    const dp = this.#resolveDataPoint(ref);\n    const ccu = dp.prepareWrite(value);\n    await this.#central.setValue(dp.dpk, ccu);\n  }\n\n  /**\n   * Trigger a firmware update for a device by its address (e.g. `001B9D89A09163`).\n   *\n   * Resolves the interface owning the device (the same routing used by\n   * {@link Homematic.setValue}) and dispatches the standard XML-RPC\n   * `installFirmware(address)` command on it. The promise resolves once the CCU\n   * accepts the request — the actual flash runs asynchronously on the device and\n   * its progress is reflected later by the descriptor's `firmwareUpdateState`.\n   * Throws {@link ValidationError} for an unknown device, or a typed transport\n   * error (e.g. `ClientError`) if the CCU/interface rejects the call (which the\n   * caller can surface as \"firmware update not supported\").\n   */\n  public async installFirmware(deviceAddress: string): Promise<void> {\n    const device = this.#devicesByAddress.get(deviceAddress);\n    if (device === undefined) {\n      throw new ValidationError(`Unknown device \"${deviceAddress}\".`);\n    }\n    await this.#central.installFirmware(device.interfaceId, deviceAddress);\n  }\n\n  /**\n   * Direct links of one channel, plus whether it has a central link.\n   *\n   * `links` is XML-RPC `getLinks(address, 0)` (`SENDER`, `RECEIVER`, `NAME`),\n   * as read by aiohomematic `LinkCoordinator.get_device_links`\n   * (`aiohomematic/central/coordinators/link.py`). `central` is\n   * `Channel._has_central_link` (`aiohomematic/model/device.py`):\n   * `getMetadata(address, \"reportValueUsageData\")` with `PRESS_SHORT > 0`.\n   * A metadata fault yields `central: false` and does not fail the call; a\n   * `getLinks` fault is a {@link ClientError}.\n   */\n  public async getChannelLinkState(channelAddress: string): Promise<HmChannelLinkState> {\n    const device = this.#requireKnownChannel(channelAddress);\n    const raw = await this.#central.getLinks(device.interfaceId, channelAddress, GET_LINKS_FLAGS);\n    const central = await this.#hasCentralLink(device.interfaceId, channelAddress);\n    return { central, links: parseChannelLinks(raw) };\n  }\n\n  /**\n   * Create the central link for one channel so the CCU pushes `PRESS_*` to\n   * this client. Idempotent: when a central link already exists this returns\n   * without a second call.\n   *\n   * Protocol: aiohomematic `Channel.create_central_link`\n   * (`aiohomematic/model/device.py`) → `CcuBackend.report_value_usage`\n   * (`aiohomematic/client/backends/ccu.py`) sends\n   * `reportValueUsage(channelAddress, \"PRESS_SHORT\", 1)` on that channel's\n   * interface. HmIP-RF and BidCos-RF use this same call; it is not `addLink`\n   * to a central address. The value id and ref counter are\n   * `REPORT_VALUE_USAGE_VALUE_ID` (`\"PRESS_SHORT\"`) and `1` in\n   * `aiohomematic/const.py`. A `false` result or an XML-RPC fault is a\n   * {@link ClientError}.\n   *\n   * aiohomematic only does this for channels with key-press events. This\n   * method does it for any known channel address.\n   */\n  public async createCentralLink(channelAddress: string): Promise<void> {\n    const device = this.#requireKnownChannel(channelAddress);\n    if (await this.#hasCentralLink(device.interfaceId, channelAddress)) return;\n    const accepted = await this.#central.reportValueUsage(\n      device.interfaceId,\n      channelAddress,\n      REPORT_VALUE_USAGE_VALUE_ID,\n      REPORT_VALUE_USAGE_REF_CREATE,\n    );\n    if (!accepted) {\n      throw new ClientError(`reportValueUsage refused for channel \"${channelAddress}\".`);\n    }\n  }\n\n  /**\n   * Remove the central link for one channel. Idempotent: when none exists this\n   * returns without a call.\n   *\n   * Protocol: aiohomematic `Channel.remove_central_link`\n   * (`aiohomematic/model/device.py`) sends\n   * `reportValueUsage(channelAddress, \"PRESS_SHORT\", 0)`. That method also\n   * skips the call when JSON-RPC `Channel.hasProgramIds` is true\n   * (`client/json_rpc.py` `has_program_ids`); this method does not, and clears\n   * the link whenever the metadata counter is `> 0`. A `false` result or an\n   * XML-RPC fault is a {@link ClientError}.\n   */\n  public async removeCentralLink(channelAddress: string): Promise<void> {\n    const device = this.#requireKnownChannel(channelAddress);\n    if (!(await this.#hasCentralLink(device.interfaceId, channelAddress))) return;\n    const accepted = await this.#central.reportValueUsage(\n      device.interfaceId,\n      channelAddress,\n      REPORT_VALUE_USAGE_VALUE_ID,\n      REPORT_VALUE_USAGE_REF_REMOVE,\n    );\n    if (!accepted) {\n      throw new ClientError(`reportValueUsage refused for channel \"${channelAddress}\".`);\n    }\n  }\n\n  // --- key event program (HmIP) -------------------------------------------------\n\n  /**\n   * Make the CCU USE the given keys so a HmIP device sends their presses to the\n   * access point: create the program `input.name`, or rewrite its conditions to\n   * exactly `channelAddresses` x `parameters` (default short and long press).\n   * Idempotent by name. The program has no destination; it exists only so the\n   * CCU subscribes to the key data points (ReGa scripts and their eq-3/occu\n   * sources: `central/rega/key-event-program.ts`). All channels must be on one\n   * interface and the CCU must have their data points; a missing one is a\n   * {@link ValidationError} naming it. Two programs with the same name are a\n   * {@link ValidationError} listing their ids (`deleteProgram(id)` removes one).\n   * Needs WebUI credentials.\n   */\n  public async ensureKeyEventProgram(\n    input: HmKeyEventProgramInput,\n  ): Promise<HmKeyEventProgramResult> {\n    if (input.channelAddresses.length === 0) {\n      throw new ValidationError('ensureKeyEventProgram needs at least one channel.');\n    }\n    const interfaces = new Set(\n      input.channelAddresses.map((address) =>\n        interfaceNameOf(this.#requireKnownChannel(address).interfaceId),\n      ),\n    );\n    const [iface] = [...interfaces];\n    if (interfaces.size !== 1 || iface === undefined) {\n      throw new ValidationError('The key channels of one program must share an interface.');\n    }\n    return this.#requireManagement().keyPrograms().ensure(iface, input);\n  }\n\n  /** Delete the key event program `name`; `removed: false` when it does not exist. A duplicate name is a {@link ValidationError}. Needs WebUI credentials. */\n  public async removeKeyEventProgram(name: string): Promise<{ removed: boolean }> {\n    return this.#requireManagement().keyPrograms().remove(name);\n  }\n\n  /**\n   * Delete one CCU program by its ReGa id (digits only). `removed: false` when\n   * the id is missing or is not a program — nothing is deleted then. This is\n   * the way out of two programs that share a name. Needs WebUI credentials.\n   */\n  public async deleteProgram(programId: string): Promise<{ removed: boolean }> {\n    return this.#requireManagement().keyPrograms().delete(programId);\n  }\n\n  /** The key event program `name` and the channels it listens to, or `null`. A duplicate name is a {@link ValidationError}. Needs WebUI credentials. */\n  public async getKeyEventProgram(name: string): Promise<HmKeyEventProgram | null> {\n    return this.#requireManagement().keyPrograms().get(name);\n  }\n\n  /**\n   * The CCU programs whose conditions reference a key data point of any of\n   * `keyAddresses` (`PRESS_SHORT` / `PRESS_LONG` / `PRESS_LONG_RELEASE`), in\n   * ONE ReGa scan of all programs (chunked at 100 channels). It covers a\n   * program written by hand on the CCU as well as one this library created.\n   * Rejects (never answers `[]`) when the CCU cannot be read, so a caller can\n   * tell \"unknown\" from \"none\". An address of no known device is a\n   * {@link ValidationError}. Needs WebUI credentials.\n   */\n  public async keyProgramReferences(\n    keyAddresses: readonly string[],\n  ): Promise<HmKeyProgramReference[]> {\n    const management = this.#requireManagement();\n    const channels = [...new Set(keyAddresses)].map((address) => {\n      const device = this.#devicesByAddress.get(address.split(':')[0] ?? '');\n      if (device === undefined) throw new ValidationError(`Unknown channel \"${address}\".`);\n      return { interfaceName: interfaceNameOf(device.interfaceId), address };\n    });\n    if (channels.length === 0) return [];\n    return management.keyDiagnosis().programReferences(channels);\n  }\n\n  /**\n   * Read-only diagnosis of \"why does a key of this device not deliver\n   * `PRESS_SHORT` to this client?\": for the device's key channels it collects\n   * the XML-RPC side (central link, direct links, VALUES, MASTER, and the\n   * maintenance channel `:0`), the ReGa side (channel and key data point\n   * objects with their last update, and the programs that reference them;\n   * needs WebUI credentials, otherwise `rega.available` is `false`) and what\n   * this client itself received. Each section fails on its own with\n   * `{ ok: false, error }`. Sources and semantics: `key-event-diagnosis.ts`.\n   * Throws {@link ValidationError} for an unknown device or before `start()`.\n   */\n  public async diagnoseKeyEvents(deviceAddress: string): Promise<HmKeyEventDiagnosis> {\n    const management = this.#requireManagement();\n    const device = this.#devicesByAddress.get(deviceAddress);\n    if (device === undefined) {\n      throw new ValidationError(`Unknown device \"${deviceAddress}\".`);\n    }\n    return diagnoseKeyEvents(\n      {\n        getMetadata: (iface, address, dataId) => this.#central.getMetadata(iface, address, dataId),\n        getLinks: (iface, address, flags) => this.#central.getLinks(iface, address, flags),\n        readParamset: (iface, address, key) => this.#central.readParamset(iface, address, key),\n        getParamsetSpec: (iface, address, key) =>\n          this.#central.getParamsetSpec(iface, address, key),\n        getConnectionInfo: (iface) => this.#central.getConnectionInfo(iface),\n        readRega: (iface, addresses) => management.keyDiagnosis().read(iface, addresses),\n        now: () => Date.now(),\n      },\n      device,\n    );\n  }\n\n  // --- direct links + switch link profiles ------------------------------------\n\n  /**\n   * Create a direct link from `sender` to `receiver` (XML-RPC\n   * `addLink(sender, receiver, name, description)` on the sender's interface,\n   * as eq-3/occu `WebUI/www/api/methods/interface/addlink.tcl` forwards it).\n   * Idempotent: when `getLinks(sender)` already lists the pair this returns\n   * without a call and leaves the existing name and description unchanged.\n   * The sender must be a known channel; a fault is a {@link ClientError}.\n   */\n  public async addLink(\n    sender: string,\n    receiver: string,\n    name: string = '',\n    description: string = '',\n  ): Promise<void> {\n    const device = this.#requireKnownChannel(sender);\n    requireChannelAddress(receiver);\n    if ((await this.#findLink(device.interfaceId, sender, receiver)) !== undefined) return;\n    await this.#central.addLink(device.interfaceId, sender, receiver, name, description);\n  }\n\n  /**\n   * Remove the direct link from `sender` to `receiver` (XML-RPC\n   * `removeLink(sender, receiver)`, eq-3/occu `interface/removelink.tcl`).\n   * Idempotent: when `getLinks(sender)` does not list the pair this returns\n   * without a call — removing a link that does not exist is not an error.\n   */\n  public async removeLink(sender: string, receiver: string): Promise<void> {\n    const device = this.#requireKnownChannel(sender);\n    requireChannelAddress(receiver);\n    if ((await this.#findLink(device.interfaceId, sender, receiver)) === undefined) return;\n    await this.#central.removeLink(device.interfaceId, sender, receiver);\n  }\n\n  /**\n   * Every direct link of a device or channel (XML-RPC `getLinks(address, 0)`;\n   * a device address lists the links of all its channels) with `name`,\n   * `description` and the resolved switch `profile`. The profile is read with\n   * `getParamset(receiver, sender)` for each `KEY_TRANSCEIVER` →\n   * `SWITCH_VIRTUAL_RECEIVER` link between known channels and is `null` for any\n   * other link (see {@link Homematic.getLinkProfile}). A failed read is a\n   * {@link ClientError}.\n   */\n  public async listLinks(deviceOrChannelAddress: string): Promise<HmLink[]> {\n    const device = this.#requireKnownAddress(deviceOrChannelAddress);\n    const raw = await this.#central.getLinks(\n      device.interfaceId,\n      deviceOrChannelAddress,\n      GET_LINKS_FLAGS,\n    );\n    const links: HmLink[] = [];\n    for (const link of parseLinks(raw)) {\n      links.push({ ...link, profile: await this.#readLinkProfile(link) });\n    }\n    return links;\n  }\n\n  /**\n   * The switch profile of one existing link: short and long press each\n   * `toggle | on | off | none`, or `{ kind: 'custom' }` when the receiver\n   * paramset matches no catalogue entry exactly (catalogue and sources:\n   * `src/api/link-profile.ts`, from eq-3/occu\n   * `WebUI/www/config/easymodes/SWITCH_VIRTUAL_RECEIVER/KEY_TRANSCEIVER.tcl`).\n   * `null` when the link is not `KEY_TRANSCEIVER` → `SWITCH_VIRTUAL_RECEIVER`.\n   * An unknown link is a {@link ValidationError}.\n   */\n  public async getLinkProfile(sender: string, receiver: string): Promise<HmLinkProfile | null> {\n    const device = this.#requireKnownChannel(sender);\n    const link = await this.#findLink(device.interfaceId, sender, receiver);\n    if (link === undefined) {\n      throw new ValidationError(`No link from \"${sender}\" to \"${receiver}\".`);\n    }\n    return this.#readLinkProfile(link);\n  }\n\n  /**\n   * Write a catalogue profile to a key → switch link: ONE\n   * `putParamset(receiver, sender, values)` with exactly the parameters the\n   * two actions define (`none` writes only `PROFILE_ACTION_TYPE = 0`). Refused\n   * with a {@link ValidationError}, before any write, when the link does not\n   * exist, is not `KEY_TRANSCEIVER` → `SWITCH_VIRTUAL_RECEIVER`, or currently\n   * reads `custom` — a custom link is never rewritten.\n   */\n  public async setLinkProfile(\n    sender: string,\n    receiver: string,\n    actions: HmSwitchLinkActions,\n  ): Promise<void> {\n    requirePressAction(actions.short);\n    requirePressAction(actions.long);\n    const senderDevice = this.#requireKnownChannel(sender);\n    const receiverDevice = this.#requireKnownChannel(receiver);\n    const link = await this.#findLink(senderDevice.interfaceId, sender, receiver);\n    if (link === undefined) {\n      throw new ValidationError(`No link from \"${sender}\" to \"${receiver}\".`);\n    }\n    const current = await this.#readLinkProfile(link);\n    if (current === null) {\n      throw new ValidationError(\n        `The link \"${sender}\" → \"${receiver}\" is not a key → switch actuator link.`,\n      );\n    }\n    if (current.kind === 'custom') {\n      throw new ValidationError(\n        `The link \"${sender}\" → \"${receiver}\" has a custom profile; it is not rewritten.`,\n      );\n    }\n    await this.#central.writeParamset(\n      receiverDevice.interfaceId,\n      receiver,\n      sender,\n      switchLinkValues(actions),\n    );\n  }\n\n  // --- names and rooms (WebUI credentials) -------------------------------------\n\n  /**\n   * Rename a device and, with `renameChannels`, every channel of it to\n   * `<name>:<channelIndex>` (the CCU's own channel-name pattern). ReGa script\n   * over `ReGa.runScript` doing what JSON-RPC `Device.setName` /\n   * `Channel.setName` do (eq-3/occu `WebUI/www/api/methods/device/setname.tcl`).\n   * Resolves with the names the CCU stored (it keeps names unique); `devices()`\n   * shows them from then on. Needs WebUI credentials.\n   */\n  public async renameDevice(\n    address: string,\n    name: string,\n    options: HmRenameDeviceOptions,\n  ): Promise<HmDeviceRename> {\n    this.#requireKnownDevice(address);\n    const result = await this.#requireTopology().renameDevice(\n      address,\n      name,\n      options.renameChannels,\n    );\n    this.#rememberNames([result.device, ...result.channels]);\n    return result;\n  }\n\n  /** Rename one channel (as JSON-RPC `Channel.setName`); resolves with the stored name. Needs WebUI credentials. */\n  public async renameChannel(address: string, name: string): Promise<HmNamedObject> {\n    this.#requireKnownChannel(address);\n    const result = await this.#requireTopology().renameChannel(address, name);\n    this.#rememberNames([result]);\n    return result;\n  }\n\n  /**\n   * Every CCU room with its member channel addresses, read live (ReGa walk of\n   * `ID_ROOMS`, as JSON-RPC `Room.getAll`). `HmDevice.rooms` is the snapshot\n   * taken at `start()`. Needs WebUI credentials.\n   */\n  public async listRooms(): Promise<HmRoom[]> {\n    return this.#requireTopology().rooms();\n  }\n\n  /** Create an empty room (eq-3/occu `rega/esp/rooms.fn` `createRoomRetId`); a duplicate name is refused. Needs WebUI credentials. */\n  public async createRoom(name: string): Promise<HmRoom> {\n    return this.#requireTopology().createRoom(name);\n  }\n\n  /** Rename a room by its id (`rooms.fn` `changeRoomName`). Needs WebUI credentials. */\n  public async renameRoom(roomId: string, name: string): Promise<void> {\n    await this.#requireTopology().renameRoom(roomId, name);\n  }\n\n  /** Delete a room by its id (`rega/esp/system.fn` `DeleteObject`). Needs WebUI credentials. */\n  public async deleteRoom(roomId: string): Promise<void> {\n    await this.#requireTopology().deleteRoom(roomId);\n  }\n\n  /** Add a channel to a room (as JSON-RPC `Room.addChannel`, by address). Needs WebUI credentials. */\n  public async addChannelToRoom(roomId: string, channelAddress: string): Promise<void> {\n    await this.#requireTopology().addChannelToRoom(roomId, channelAddress);\n  }\n\n  /** Remove a channel from a room (as JSON-RPC `Room.removeChannel`, by address). Needs WebUI credentials. */\n  public async removeChannelFromRoom(roomId: string, channelAddress: string): Promise<void> {\n    await this.#requireTopology().removeChannelFromRoom(roomId, channelAddress);\n  }\n\n  // --- CCU management ---------------------------------------------------------\n\n  /**\n   * Every interface the CCU offers (BidCos-RF, HmIP-RF, VirtualDevices, ...)\n   * with connection state, duty cycle, firmware and type where the CCU reports\n   * them. A value the CCU did not answer is `null`, never `0`. Needs a started\n   * facade.\n   *\n   * CCU methods: JSON-RPC `Interface.listInterfaces` / `Interface.isPresent`\n   * (eq-3/occu `WebUI/www/api/methods/interface/`), XML-RPC\n   * `listBidcosInterfaces` on BidCos-RF, JSON-RPC `Interface.getDutyCycle`\n   * (RaspberryMatic / OpenCCU only) for the HmIP access point.\n   */\n  public async listInterfaces(): Promise<HmInterfaceInfo[]> {\n    return this.#requireManagement().listInterfaces();\n  }\n\n  /**\n   * Open (default 60 s, 1..3600) or close the pairing window of a configured\n   * interface. XML-RPC `setInstallMode`; `mode: 'secure'` (BidCos only) also\n   * teaches the HomeMatic Secure key.\n   */\n  public async setInstallMode(request: HmInstallModeRequest): Promise<void> {\n    await this.#requireManagement().setInstallMode(request);\n  }\n\n  /** Seconds left of an interface's pairing window (`null` when the CCU's answer was unusable). XML-RPC `getInstallMode`. */\n  public async getInstallMode(interfaceName: string): Promise<number | null> {\n    return this.#requireManagement().getInstallMode(interfaceName);\n  }\n\n  /**\n   * Remove a device from its interface (XML-RPC `deleteDevice`). `flags` is an OR\n   * of {@link HM_DELETE_FLAGS}: `RESET` (0x01, factory reset), `FORCE` (0x02,\n   * remove even when unreachable), `DEFER` (0x04, remove when next reachable);\n   * `0` is a plain removal. The model drops the device once the CCU reports it\n   * through the `deleteDevices` callback. Throws {@link ValidationError} for an\n   * unknown device or invalid flags.\n   */\n  public async deleteDevice(deviceAddress: string, flags: number = 0): Promise<void> {\n    this.#requireManagement();\n    const device = this.#devicesByAddress.get(deviceAddress);\n    if (device === undefined) {\n      throw new ValidationError(`Unknown device \"${deviceAddress}\".`);\n    }\n    if (!Number.isInteger(flags) || flags < 0 || flags > 7) {\n      throw new ValidationError(\n        `Invalid delete flags ${String(flags)} (expected an integer 0..7).`,\n      );\n    }\n    await this.#central.deleteDevice(device.interfaceId, deviceAddress, flags);\n  }\n\n  /**\n   * The CCU's active service messages (UNREACH, LOWBAT, CONFIG_PENDING,\n   * STICKY_UNREACH, ...). Needs WebUI credentials. ReGa script over\n   * `ReGa.runScript` (eq-3/occu `WebUI/www/rega/esp/system.fn`, `ID_SERVICES`).\n   */\n  public async serviceMessages(): Promise<HmServiceMessage[]> {\n    return this.#requireManagement().serviceMessages();\n  }\n\n  /** Acknowledge a service message by its `id` (ReGa `AlReceipt`, as the WebUI does). Needs WebUI credentials. */\n  public async acknowledgeServiceMessage(id: string): Promise<void> {\n    await this.#requireManagement().acknowledgeServiceMessage(id);\n  }\n\n  /**\n   * Version, product (CCU3 / RaspberryMatic / OpenCCU), serial and hostname.\n   * Needs WebUI credentials. JSON-RPC `CCU.getVersion`, `CCU.getSerial`\n   * (eq-3/occu `WebUI/www/api/methods/ccu/`) plus a ReGa read of `/VERSION`.\n   */\n  public async ccuInfo(): Promise<HmCcuInfo> {\n    return this.#requireManagement().ccuInfo();\n  }\n\n  /**\n   * The CCU's heating groups (\"Gruppen\"): HmIP heating groups and HomeMatic\n   * heating groups with their member channels. Writes are separate and\n   * undocumented: {@link Homematic.createGroup}, `updateGroup`, `deleteGroup`.\n   * JSON-RPC `CCU.getHeatingGroupList` (eq-3/occu\n   * `WebUI/www/api/methods/ccu/getheatinggrouplist.tcl`). Needs WebUI credentials.\n   */\n  public async groups(): Promise<HmGroup[]> {\n    return this.#requireManagement().groups();\n  }\n\n  /**\n   * Create a heating group (`type` e.g. `hmip.heating.group`, `members` channel\n   * addresses). Resolves with the group as read back from the CCU; a write the\n   * read-back does not show rejects with `GroupWriteVerificationError`.\n   *\n   * UNDOCUMENTED and firmware-dependent: no CCU API exists for this, so the call\n   * reproduces the WebUI's own HMServer page requests (eq-3/occu\n   * `HMserver/opt/HMServer/pages/GroupEditPage.ftl`, `GroupListPage.ftl`).\n   * Needs WebUI credentials.\n   */\n  public async createGroup(input: HmGroupCreate): Promise<HmGroup> {\n    return this.#requireManagement().createGroup(input);\n  }\n\n  /** Rename a group and/or replace its member list (same caveats as {@link Homematic.createGroup}). */\n  public async updateGroup(id: number, patch: HmGroupUpdate): Promise<HmGroup> {\n    return this.#requireManagement().updateGroup(id, patch);\n  }\n\n  /** Delete a group, verified by the read-back (same caveats as {@link Homematic.createGroup}). */\n  public async deleteGroup(id: number): Promise<void> {\n    await this.#requireManagement().deleteGroup(id);\n  }\n\n  // --- device configuration (MASTER paramset) -------------------------------\n\n  /**\n   * The MASTER configuration parameters of a channel, with the metadata needed\n   * to render a form. Empty array when nothing is known for the channel.\n   */\n  public getConfigParams(channelAddress: string): HmConfigParam[] {\n    const interfaceId = this.#interfaceIdForChannel(channelAddress);\n    const spec = this.#central.getParamsetSpec(interfaceId, channelAddress, ParamsetKey.MASTER);\n    if (spec === undefined) return [];\n    return Object.entries(spec).map(([parameter, data]) => toConfigParam(parameter, data));\n  }\n\n  /** Read and convert the current MASTER configuration values of a channel. */\n  public async getConfig(channelAddress: string): Promise<Record<string, HmValue>> {\n    const interfaceId = this.#interfaceIdForChannel(channelAddress);\n    const spec = this.#central.getParamsetSpec(interfaceId, channelAddress, ParamsetKey.MASTER);\n    if (spec === undefined) {\n      throw new DescriptionNotFoundError(\n        `No MASTER paramset description discovered for channel \"${channelAddress}\".`,\n      );\n    }\n    const raw = await this.#central.readParamset(interfaceId, channelAddress, ParamsetKey.MASTER);\n    const out: Record<string, HmValue> = {};\n    for (const [parameter, value] of Object.entries(raw)) {\n      const data = spec[parameter];\n      out[parameter] =\n        data === undefined\n          ? coerceUnknownToHmValue(value)\n          : convertFromCcu(parameterSpecFromData(data), value);\n    }\n    return out;\n  }\n\n  /**\n   * Validate + convert every value against its MASTER spec (throwing BEFORE any\n   * network call on an invalid/unknown parameter), then write them all in ONE\n   * `putParamset`.\n   */\n  public async setConfig(channelAddress: string, values: Record<string, HmValue>): Promise<void> {\n    const interfaceId = this.#interfaceIdForChannel(channelAddress);\n    const spec = this.#central.getParamsetSpec(interfaceId, channelAddress, ParamsetKey.MASTER);\n    const family = interfaceFamilyOf(interfaceId);\n    const enumAsIndex = family === 'HM';\n    const ccuValues: Record<string, boolean | number | string> = {};\n    for (const [parameter, value] of Object.entries(values)) {\n      const data = spec?.[parameter];\n      if (data === undefined) {\n        throw new ValidationError(\n          `Unknown MASTER parameter \"${parameter}\" for channel \"${channelAddress}\".`,\n        );\n      }\n      ccuValues[parameter] = convertToCcu(parameterSpecFromData(data), value, { enumAsIndex });\n    }\n    await this.#central.writeParamset(interfaceId, channelAddress, ParamsetKey.MASTER, ccuValues);\n  }\n\n  // --- hub: system variables + programs -------------------------------------\n\n  /**\n   * An immutable snapshot of every known system variable (empty when no hub /\n   * credentials). Refreshed at {@link Homematic.start} and {@link Homematic.refreshHub}.\n   */\n  public systemVariables(): HmSysVar[] {\n    return this.#sysvars.map(toHmSysVar);\n  }\n\n  /** Read a single system variable's current value by name. Throws if no hub. */\n  public async getSystemVariable(name: string): Promise<HmValue> {\n    return this.#requireHub().getSystemVariable(name);\n  }\n\n  /**\n   * Write a system variable by name. Validates against the snapshot BEFORE any\n   * network call: an unknown or read-only variable throws {@link ValidationError}\n   * (no write is attempted). Throws if no hub.\n   */\n  public async setSystemVariable(name: string, value: HmValue): Promise<void> {\n    const hub = this.#requireHub();\n    const sysvar = this.#sysvars.find((v) => v.name === name);\n    if (sysvar === undefined) {\n      throw new ValidationError(`Unknown system variable \"${name}\".`);\n    }\n    if (!sysvar.writable) {\n      throw new ValidationError(`System variable \"${name}\" is read-only.`);\n    }\n    await hub.setSystemVariable(name, value);\n  }\n\n  /**\n   * An immutable snapshot of every known program (empty when no hub). Refreshed\n   * at {@link Homematic.start} and {@link Homematic.refreshHub}.\n   */\n  public programs(): HmProgram[] {\n    return this.#programs.map(toHmProgram);\n  }\n\n  /** Execute a program, resolved by id or name from the snapshot. Throws if no hub. */\n  public async runProgram(idOrName: string): Promise<void> {\n    const hub = this.#requireHub();\n    await hub.runProgram(this.#resolveProgramId(idOrName));\n  }\n\n  /** Enable/disable a program, resolved by id or name. Throws if no hub. */\n  public async setProgramActive(idOrName: string, active: boolean): Promise<void> {\n    const hub = this.#requireHub();\n    await hub.setProgramActive(this.#resolveProgramId(idOrName), active);\n  }\n\n  /** Re-fetch the system-variable and program snapshots from the hub. Throws if no hub. */\n  public async refreshHub(): Promise<void> {\n    const hub = this.#requireHub();\n    this.#sysvars = await hub.fetchSystemVariables();\n    this.#programs = await hub.fetchPrograms();\n  }\n\n  // --- custom entities ------------------------------------------------------\n\n  /**\n   * An immutable snapshot of every live custom entity (Climate / Switch / Light\n   * / Cover / Lock), each mapped to its public {@link HmCustomEntity} shape by\n   * reading the entity's current getters. No functions leak into the snapshot;\n   * issue commands through the typed command methods below.\n   */\n  public customEntities(): HmCustomEntity[] {\n    return this.#customEntityList.map((entity) => toHmCustomEntity(entity));\n  }\n\n  /** Set a climate entity's target temperature (clamped to its range). */\n  public async climateSetTemperature(\n    device: string,\n    channel: string | number,\n    temperature: number,\n  ): Promise<void> {\n    await this.#climate(device, channel).setTemperature(temperature);\n  }\n\n  /** Set a climate entity's operating mode. */\n  public async climateSetMode(\n    device: string,\n    channel: string | number,\n    mode: ClimateMode,\n  ): Promise<void> {\n    await this.#climate(device, channel).setMode(mode);\n  }\n\n  /** Enable or disable a climate entity's boost mode. */\n  public async climateSetBoost(\n    device: string,\n    channel: string | number,\n    on: boolean,\n  ): Promise<void> {\n    await this.#climate(device, channel).setBoost(on);\n  }\n\n  /** Turn a switch entity on. */\n  public async switchTurnOn(device: string, channel: string | number): Promise<void> {\n    await this.#switch(device, channel).turnOn();\n  }\n\n  /** Turn a switch entity off. */\n  public async switchTurnOff(device: string, channel: string | number): Promise<void> {\n    await this.#switch(device, channel).turnOff();\n  }\n\n  /** Turn a light entity on (full brightness, or `brightness` 0..255 when given). */\n  public async lightTurnOn(\n    device: string,\n    channel: string | number,\n    brightness?: number,\n  ): Promise<void> {\n    const light = this.#light(device, channel);\n    await (brightness === undefined ? light.turnOn() : light.turnOn(brightness));\n  }\n\n  /** Turn a light entity off. */\n  public async lightTurnOff(device: string, channel: string | number): Promise<void> {\n    await this.#light(device, channel).turnOff();\n  }\n\n  /** Set a light entity's brightness (0..255). */\n  public async lightSetBrightness(\n    device: string,\n    channel: string | number,\n    brightness: number,\n  ): Promise<void> {\n    await this.#light(device, channel).setBrightness(brightness);\n  }\n\n  /** Open a cover entity fully. */\n  public async coverOpen(device: string, channel: string | number): Promise<void> {\n    await this.#cover(device, channel).open();\n  }\n\n  /** Close a cover entity fully. */\n  public async coverClose(device: string, channel: string | number): Promise<void> {\n    await this.#cover(device, channel).close();\n  }\n\n  /** Stop a cover entity where it is. */\n  public async coverStop(device: string, channel: string | number): Promise<void> {\n    await this.#cover(device, channel).stop();\n  }\n\n  /** Move a cover entity to `position` (0..100). */\n  public async coverSetPosition(\n    device: string,\n    channel: string | number,\n    position: number,\n  ): Promise<void> {\n    await this.#cover(device, channel).setPosition(position);\n  }\n\n  /** Lock a lock entity. */\n  public async lockLock(device: string, channel: string | number): Promise<void> {\n    await this.#lock(device, channel).lock();\n  }\n\n  /** Unlock a lock entity. */\n  public async lockUnlock(device: string, channel: string | number): Promise<void> {\n    await this.#lock(device, channel).unlock();\n  }\n\n  /** Release a lock entity's latch (open). */\n  public async lockOpen(device: string, channel: string | number): Promise<void> {\n    await this.#lock(device, channel).open();\n  }\n\n  // --- internals ------------------------------------------------------------\n\n  /**\n   * Resolve the live custom entity for `(device, channel)`, asserting its\n   * `kind`. `channel` may be a numeric index, a numeric string, or the full\n   * channel address (normalised like the {@link DataPointRef} resolver). Throws\n   * {@link ValidationError} when absent or of the wrong kind.\n   */\n  #entity(device: string, channel: string | number, expectedKind: string): CustomEntity {\n    const channelAddress =\n      typeof channel === 'string' && (channel.includes(':') || channel.startsWith(`${device}:`))\n        ? channel\n        : `${device}:${channel}`;\n    const entity = this.#customEntitiesByKey.get(`${device}:${channelAddress}`);\n    if (entity === undefined) {\n      throw new ValidationError(`No custom entity for \"${device}\" channel \"${channelAddress}\".`);\n    }\n    if (entity.kind !== expectedKind) {\n      throw new ValidationError(\n        `Custom entity \"${device}\" channel \"${channelAddress}\" is a ${entity.kind}, not a ${expectedKind}.`,\n      );\n    }\n    return entity;\n  }\n\n  #climate(device: string, channel: string | number): ClimateEntity {\n    const entity = this.#entity(device, channel, 'climate');\n    if (!(entity instanceof ClimateEntity)) {\n      throw new ValidationError(`Custom entity for \"${device}\" is not a climate entity.`);\n    }\n    return entity;\n  }\n\n  #switch(device: string, channel: string | number): SwitchEntity {\n    const entity = this.#entity(device, channel, 'switch');\n    if (!(entity instanceof SwitchEntity)) {\n      throw new ValidationError(`Custom entity for \"${device}\" is not a switch entity.`);\n    }\n    return entity;\n  }\n\n  #light(device: string, channel: string | number): DimmerEntity {\n    const entity = this.#entity(device, channel, 'light');\n    if (!(entity instanceof DimmerEntity)) {\n      throw new ValidationError(`Custom entity for \"${device}\" is not a light entity.`);\n    }\n    return entity;\n  }\n\n  #cover(device: string, channel: string | number): CoverEntity {\n    // Both 'cover' and 'blind' kinds are CoverEntity instances.\n    const channelAddress =\n      typeof channel === 'string' && (channel.includes(':') || channel.startsWith(`${device}:`))\n        ? channel\n        : `${device}:${channel}`;\n    const entity = this.#customEntitiesByKey.get(`${device}:${channelAddress}`);\n    if (entity === undefined || !(entity instanceof CoverEntity)) {\n      throw new ValidationError(\n        `No cover custom entity for \"${device}\" channel \"${channelAddress}\".`,\n      );\n    }\n    return entity;\n  }\n\n  #lock(device: string, channel: string | number): IpLockEntity | RfLockEntity {\n    const entity = this.#entity(device, channel, 'lock');\n    if (entity instanceof IpLockEntity || entity instanceof RfLockEntity) {\n      return entity;\n    }\n    throw new ValidationError(`Custom entity for \"${device}\" is not a lock entity.`);\n  }\n\n  /**\n   * Route an error thrown by a public-event listener to the `error` event so it\n   * is surfaced rather than swallowed. If the failing listener was itself an\n   * `error` listener (or another `error` listener throws while we re-emit), we\n   * fall back to `console.error` to avoid unbounded recursion.\n   */\n  #onListenerError(error: unknown): void {\n    if (this.#emittingError) {\n      console.error('nodehomematic: error event listener threw', error);\n      return;\n    }\n    this.#emittingError = true;\n    try {\n      this.#emitter.emit('error', error instanceof Error ? error : new Error(String(error)));\n    } finally {\n      this.#emittingError = false;\n    }\n  }\n\n  #rebuildModel(nodes: readonly DeviceNode[]): void {\n    this.#dataPointsById.clear();\n    this.#devicesByAddress.clear();\n    for (const device of buildModel(nodes)) {\n      this.#indexDevice(device);\n    }\n    this.#rebuildCustomEntities();\n  }\n\n  /**\n   * Rebuild the custom-entity views from the current model. Each entity is wired\n   * to {@link Homematic.#writeRaw} so commands flow through the same validated\n   * send path as {@link Homematic.setValue}.\n   */\n  #rebuildCustomEntities(): void {\n    const writer: CustomEntityWriter = (channelAddress, parameter, value) =>\n      this.#writeRaw(channelAddress, parameter, value);\n    const list: CustomEntity[] = [];\n    this.#customEntitiesByKey.clear();\n    for (const device of this.#devicesByAddress.values()) {\n      for (const entity of buildCustomEntities(device, writer)) {\n        list.push(entity);\n        this.#customEntitiesByKey.set(\n          `${entity.deviceAddress}:${entity.primaryChannelAddress}`,\n          entity,\n        );\n      }\n    }\n    this.#customEntityList = list;\n  }\n\n  /**\n   * Resolve the live data point for `(channelAddress, parameter)` and route a\n   * write through the SAME validate + convert + send path as\n   * {@link Homematic.setValue}: `dp.prepareWrite(value)` then `central.setValue`.\n   */\n  async #writeRaw(channelAddress: string, parameter: string, value: HmValue): Promise<void> {\n    const deviceAddress = deviceAddressOf(channelAddress);\n    const device = this.#devicesByAddress.get(deviceAddress);\n    if (device === undefined) {\n      throw new ValidationError(\n        `Unknown device \"${deviceAddress}\" for channel \"${channelAddress}\".`,\n      );\n    }\n    const dpId = dpkToUniqueId(\n      makeDpk(device.interfaceId, channelAddress, ParamsetKey.VALUES, parameter),\n    );\n    const dp = this.#dataPointsById.get(dpId);\n    if (dp === undefined) {\n      throw new ValidationError(\n        `Unknown data point ${channelAddress} ${parameter} on device \"${deviceAddress}\".`,\n      );\n    }\n    const ccu = dp.prepareWrite(value);\n    await this.#central.setValue(dp.dpk, ccu);\n  }\n\n  #indexDevice(device: ModelDevice): void {\n    this.#devicesByAddress.set(device.address, device);\n    for (const dp of device.allDataPoints()) {\n      this.#dataPointsById.set(dp.id, dp);\n    }\n  }\n\n  #removeDevice(address: string): void {\n    const device = this.#devicesByAddress.get(address);\n    if (device === undefined) return;\n    for (const dp of device.allDataPoints()) {\n      this.#dataPointsById.delete(dp.id);\n    }\n    this.#devicesByAddress.delete(address);\n  }\n\n  #subscribe(): void {\n    const bus = this.#central.eventBus;\n    this.#unsubscribers.push(\n      bus.subscribe({\n        type: 'valueReceived',\n        handler: (event) =>\n          this.#onValueReceived(event.dpk, event.value, event.receivedAt, event.origin === 'event'),\n      }),\n      bus.subscribe({\n        type: 'deviceAdded',\n        handler: (event) => this.#onDeviceAdded(event.address),\n      }),\n      bus.subscribe({\n        type: 'deviceRemoved',\n        handler: (event) => this.#onDeviceRemoved(event.address),\n      }),\n      bus.subscribe({\n        type: 'connectionStateChanged',\n        handler: (event) =>\n          this.#emitter.emit('connection', {\n            interfaceId: event.interfaceId,\n            state: event.state,\n          }),\n      }),\n      bus.subscribe({\n        type: 'systemError',\n        handler: (event) =>\n          this.#emitter.emit(\n            'error',\n            new Error(`[${event.interfaceId}] system error ${event.code}: ${event.message}`),\n          ),\n      }),\n      bus.subscribe({\n        type: 'ready',\n        handler: () => this.#emitter.emit('ready'),\n      }),\n    );\n  }\n\n  /**\n   * Apply any values the central has already cached (e.g. seeded at start before\n   * the facade subscribed) onto the freshly-built data points. Silent: this is a\n   * one-shot catch-up, not a live change, so it emits no `valueChanged`.\n   */\n  #backfillSeededValues(): void {\n    for (const dp of this.#dataPointsById.values()) {\n      const entry = this.#central.getValueEntry(dp.dpk);\n      if (entry === undefined) continue;\n      dp.applyCcuValue(entry.value, entry.at);\n    }\n  }\n\n  /**\n   * An ACTION parameter (`PRESS_SHORT`, `PRESS_LONG`, …) is an occurrence, not a\n   * state: every press arrives as the same `true`, so \"unchanged\" must not\n   * swallow it. A pushed event of an ACTION parameter is always emitted; a\n   * seeded read-back of one never is (it would replay an old press).\n   */\n  #onValueReceived(dpk: DataPointKey, value: unknown, receivedAt: number, pushed: boolean): void {\n    const dp = this.#dataPointsById.get(dpkToUniqueId(dpk));\n    if (dp === undefined) return;\n    const result = dp.applyCcuValue(value, receivedAt);\n    const occurrence = dp.type === ParameterType.ACTION;\n    if (occurrence ? !pushed : !result.changed) return;\n    const channel = dp.dpk.channelAddress;\n    this.#emitter.emit('valueChanged', {\n      dpId: dp.id,\n      device: deviceAddressOf(channel),\n      channel,\n      parameter: dp.parameter,\n      value: result.next,\n      prevValue: result.prev,\n      ts: receivedAt,\n    });\n  }\n\n  #onDeviceAdded(address: string): void {\n    const node = this.#central.registry.get(address);\n    if (node !== undefined) {\n      this.#removeDevice(address);\n      this.#indexDevice(buildDevice(node));\n    }\n    this.#rebuildCustomEntities();\n    this.#emitter.emit('deviceAdded', { device: address });\n  }\n\n  #onDeviceRemoved(address: string): void {\n    this.#removeDevice(address);\n    this.#rebuildCustomEntities();\n    this.#emitter.emit('deviceRemoved', { device: address });\n  }\n\n  /** Resolve a {@link DataPointRef} to its live {@link GenericDataPoint}. */\n  #resolveDataPoint(ref: DataPointRef): GenericDataPoint {\n    if (typeof ref === 'string') {\n      const dp = this.#dataPointsById.get(ref.toLowerCase());\n      if (dp === undefined) {\n        throw new ValidationError(`Unknown data point id \"${ref}\".`);\n      }\n      return dp;\n    }\n    // `channel` may be a numeric index, a numeric string, or already a full\n    // channel address (`DEV:idx`). Only concatenate when it is a bare index;\n    // otherwise use it verbatim to avoid producing `DEV:DEV:idx`.\n    const channel = ref.channel;\n    const channelAddress =\n      typeof channel === 'string' && (channel.includes(':') || channel.startsWith(`${ref.device}:`))\n        ? channel\n        : `${ref.device}:${channel}`;\n    const device = this.#devicesByAddress.get(ref.device);\n    if (device === undefined) {\n      throw new ValidationError(`Unknown device \"${ref.device}\".`);\n    }\n    const dpId = dpkToUniqueId(\n      makeDpk(device.interfaceId, channelAddress, ParamsetKey.VALUES, ref.parameter),\n    );\n    const dp = this.#dataPointsById.get(dpId);\n    if (dp === undefined) {\n      throw new ValidationError(\n        `Unknown data point ${channelAddress} ${ref.parameter} on device \"${ref.device}\".`,\n      );\n    }\n    return dp;\n  }\n\n  /**\n   * Best-effort hub initialisation, run at the end of {@link Homematic.start}.\n   * If a {@link HubFetcher} is available (credentials present), fetch the\n   * system-variable + program snapshots and the rooms/functions mapping. Every\n   * fetch is isolated: a failure on the real CCU (e.g. a ReGa script that errors\n   * on a given firmware) is logged and swallowed so it never wedges start().\n   */\n  async #initHub(): Promise<void> {\n    this.#hub = this.#central.getHubFetcher();\n    if (this.#hub === undefined) return;\n    const hub = this.#hub;\n    await this.#tryHub('system variables', async () => {\n      this.#sysvars = await hub.fetchSystemVariables();\n    });\n    await this.#tryHub('programs', async () => {\n      this.#programs = await hub.fetchPrograms();\n    });\n    await this.#tryHub('rooms/functions', async () => {\n      const { rooms, functions } = await hub.fetchRoomsFunctions();\n      this.#applyRoomsFunctions(rooms, functions);\n    });\n  }\n\n  /** Run a best-effort hub fetch; isolate + log any failure (never throws). */\n  async #tryHub(label: string, fn: () => Promise<void>): Promise<void> {\n    try {\n      await fn();\n    } catch (error: unknown) {\n      // Hub metadata is best-effort: a failure must not fail start(). Surface it\n      // for diagnostics without re-emitting it as a public `error` event.\n      console.warn(`nodehomematic: hub fetch \"${label}\" failed`, error);\n    }\n  }\n\n  /**\n   * Aggregate the channel-address-keyed rooms/functions maps to the DEVICE level\n   * (union of every channel's entries, plus any entry keyed by the bare device\n   * address) and store them for {@link Homematic.devices} to merge in. Replaces\n   * any previous mapping.\n   */\n  #applyRoomsFunctions(\n    rooms: ReadonlyMap<string, readonly string[]>,\n    functions: ReadonlyMap<string, readonly string[]>,\n  ): void {\n    this.#roomsByDevice = aggregateByDevice(rooms);\n    this.#functionsByDevice = aggregateByDevice(functions);\n  }\n\n  /** Resolve a program id-or-name to its id via the snapshot, or throw. */\n  #resolveProgramId(idOrName: string): string {\n    const byId = this.#programs.find((p) => p.id === idOrName);\n    if (byId !== undefined) return byId.id;\n    const byName = this.#programs.find((p) => p.name === idOrName);\n    if (byName !== undefined) return byName.id;\n    throw new ValidationError(`Unknown program \"${idOrName}\".`);\n  }\n\n  /** Return the management service (built on first use), or throw before start(). */\n  #requireManagement(): CcuManagement {\n    if (!this.#started) {\n      throw new ValidationError('Homematic is not started; call start() first.');\n    }\n    this.#management ??= this.#central.getManagement();\n    return this.#management;\n  }\n\n  /** Return the bound hub fetcher, or throw if none (no credentials). */\n  #requireHub(): HubFetcher {\n    if (this.#hub === undefined) {\n      throw new ValidationError('Hub is unavailable (no WebUI credentials configured).');\n    }\n    return this.#hub;\n  }\n\n  /** Throw unless `start()` has run and `address` is a known device. */\n  #requireKnownDevice(address: string): ModelDevice {\n    if (!this.#started) {\n      throw new ValidationError('Homematic is not started; call start() first.');\n    }\n    const device = this.#devicesByAddress.get(address);\n    if (device === undefined) throw new ValidationError(`Unknown device \"${address}\".`);\n    return device;\n  }\n\n  /** A known device address, or a known channel address (its device). */\n  #requireKnownAddress(address: string): ModelDevice {\n    return address.includes(':')\n      ? this.#requireKnownChannel(address)\n      : this.#requireKnownDevice(address);\n  }\n\n  /** Channel type from the model; `undefined` for an unknown channel. */\n  #channelType(channelAddress: string): string | undefined {\n    return this.#devicesByAddress.get(deviceAddressOf(channelAddress))?.channel(channelAddress)\n      ?.type;\n  }\n\n  /** The `getLinks(sender, 0)` row for one pair, if the CCU lists it. */\n  async #findLink(\n    interfaceId: string,\n    sender: string,\n    receiver: string,\n  ): Promise<ParsedLink | undefined> {\n    const raw = await this.#central.getLinks(interfaceId, sender, GET_LINKS_FLAGS);\n    return parseLinks(raw).find((link) => link.sender === sender && link.receiver === receiver);\n  }\n\n  /** `null` outside the catalogue's pair; else the receiver paramset, classified. */\n  async #readLinkProfile(link: ParsedLink): Promise<HmLinkProfile | null> {\n    if (!isSwitchLinkPair(this.#channelType(link.sender), this.#channelType(link.receiver))) {\n      return null;\n    }\n    const receiverDevice = this.#devicesByAddress.get(deviceAddressOf(link.receiver));\n    if (receiverDevice === undefined) return null;\n    const paramset = await this.#central.readParamset(\n      receiverDevice.interfaceId,\n      link.receiver,\n      link.sender,\n    );\n    return classifyLinkParamset(paramset);\n  }\n\n  /** The names/rooms service (needs `start()`; a script without credentials throws). */\n  #requireTopology(): CcuTopology {\n    return this.#requireManagement().topology();\n  }\n\n  /** Keep the names a rename made the CCU store, for `devices()`. */\n  #rememberNames(named: readonly HmNamedObject[]): void {\n    for (const entry of named) this.#renamedNames.set(entry.address, entry.name);\n  }\n\n  /** Throw unless `start()` has run and `channelAddress` is a known channel. */\n  #requireKnownChannel(channelAddress: string): ModelDevice {\n    if (!this.#started) {\n      throw new ValidationError('Homematic is not started; call start() first.');\n    }\n    const deviceAddress = deviceAddressOf(channelAddress);\n    const device = this.#devicesByAddress.get(deviceAddress);\n    if (device === undefined || device.channel(channelAddress) === undefined) {\n      throw new ValidationError(`Unknown channel \"${channelAddress}\".`);\n    }\n    return device;\n  }\n\n  /**\n   * `Channel._has_central_link`: metadata `PRESS_SHORT > 0`. A metadata fault\n   * is \"no central link\" (aiohomematic catches `BaseHomematicException` here).\n   */\n  async #hasCentralLink(interfaceId: string, channelAddress: string): Promise<boolean> {\n    try {\n      const metadata = await this.#central.getMetadata(\n        interfaceId,\n        channelAddress,\n        REPORT_VALUE_USAGE_DATA,\n      );\n      return metadataHasCentralLink(metadata);\n    } catch (err: unknown) {\n      if (err instanceof BaseHomematicError) return false;\n      throw err;\n    }\n  }\n\n  /** Find the interfaceId owning a channel via its parent device. */\n  #interfaceIdForChannel(channelAddress: string): string {\n    const deviceAddress = deviceAddressOf(channelAddress);\n    const device = this.#devicesByAddress.get(deviceAddress);\n    if (device === undefined) {\n      throw new ValidationError(\n        `Unknown device \"${deviceAddress}\" for channel \"${channelAddress}\".`,\n      );\n    }\n    return device.interfaceId;\n  }\n}\n\n/** Map a {@link ParameterData} to a public {@link HmConfigParam}. */\nfunction toConfigParam(parameter: string, data: ParameterData): HmConfigParam {\n  const operations = data.OPERATIONS ?? 0;\n  return {\n    parameter,\n    type: data.TYPE,\n    flags: data.FLAGS ?? 0,\n    writable: isWritable(operations),\n    ...(typeof data.MIN === 'number' ? { min: data.MIN } : {}),\n    ...(typeof data.MAX === 'number' ? { max: data.MAX } : {}),\n    ...(data.DEFAULT !== undefined ? { default: coerceUnknownToHmValue(data.DEFAULT) } : {}),\n    ...(data.UNIT !== undefined ? { unit: data.UNIT } : {}),\n    ...(data.VALUE_LIST !== undefined ? { valueList: data.VALUE_LIST } : {}),\n  };\n}\n\n/** Reduce an untrusted CCU scalar to an {@link HmValue}. */\nfunction coerceUnknownToHmValue(value: unknown): HmValue {\n  if (value === null || value === undefined) return null;\n  if (typeof value === 'boolean' || typeof value === 'number' || typeof value === 'string') {\n    return value;\n  }\n  if (typeof value === 'bigint') return Number(value);\n  try {\n    return JSON.stringify(value) ?? null;\n  } catch {\n    return null;\n  }\n}\n\n/** Map a {@link GenericDataPoint} to its public snapshot. */\nfunction toHmDataPoint(dp: GenericDataPoint): HmDataPoint {\n  const min = dp.min;\n  const max = dp.max;\n  return {\n    id: dp.id,\n    parameter: dp.parameter,\n    type: dp.type,\n    value: dp.value,\n    readable: dp.readable,\n    writable: dp.writable,\n    hasEvents: dp.hasEvents,\n    ...(dp.unit !== undefined ? { unit: dp.unit } : {}),\n    ...(dp.valueList !== undefined ? { valueList: dp.valueList } : {}),\n    ...(min !== undefined ? { min } : {}),\n    ...(max !== undefined ? { max } : {}),\n  };\n}\n\n/**\n * Map a live {@link CustomEntity} to its public {@link HmCustomEntity} snapshot\n * by reading its current getters. The discriminated union is keyed by `kind`.\n */\nfunction toHmCustomEntity(entity: CustomEntity): HmCustomEntity {\n  const device = entity.deviceAddress;\n  const channel = entity.primaryChannelAddress;\n  if (entity instanceof ClimateEntity) {\n    return {\n      kind: 'climate',\n      device,\n      channel,\n      currentTemperature: entity.currentTemperature,\n      targetTemperature: entity.targetTemperature,\n      currentHumidity: entity.currentHumidity,\n      minTemp: entity.minTemp,\n      maxTemp: entity.maxTemp,\n      targetTemperatureStep: entity.targetTemperatureStep,\n      mode: entity.mode,\n      preset: entity.preset,\n      activity: entity.activity,\n    };\n  }\n  if (entity instanceof SwitchEntity) {\n    return { kind: 'switch', device, channel, isOn: entity.isOn };\n  }\n  if (entity instanceof DimmerEntity) {\n    return { kind: 'light', device, channel, isOn: entity.isOn, brightness: entity.brightness };\n  }\n  if (entity instanceof CoverEntity) {\n    return {\n      kind: entity.kind === 'blind' ? 'blind' : 'cover',\n      device,\n      channel,\n      channels: entity.channelAddresses,\n      statusChannels: entity.statusChannelAddresses,\n      currentPosition: entity.currentPosition,\n      isClosed: entity.isClosed,\n      travel: entity.travel,\n      ...(entity instanceof BlindEntity ? { currentTiltPosition: entity.currentTiltPosition } : {}),\n    };\n  }\n  if (entity instanceof IpLockEntity || entity instanceof RfLockEntity) {\n    return { kind: 'lock', device, channel, isLocked: entity.isLocked };\n  }\n  throw new ValidationError(`Unsupported custom entity kind \"${entity.kind}\".`);\n}\n\n/**\n * Map a {@link ModelDevice} to its public snapshot, overlaying any hub-derived\n * `rooms`/`functions` (union with the model's own, de-duplicated, order-stable).\n */\nfunction toHmDevice(\n  device: ModelDevice,\n  hubRooms?: readonly string[],\n  hubFunctions?: readonly string[],\n  renamed?: ReadonlyMap<string, string>,\n): HmDevice {\n  const channels: HmChannel[] = device.channels.map((channel) => ({\n    address: channel.address,\n    index: channel.index,\n    ...(channel.type !== undefined ? { type: channel.type } : {}),\n    name: renamed?.get(channel.address) ?? channel.name ?? null,\n    dataPoints: channel.dataPoints.map(toHmDataPoint),\n  }));\n  const rooms = unionStrings(device.rooms, hubRooms);\n  const functions = unionStrings(device.functions, hubFunctions);\n  return {\n    address: device.address,\n    type: device.type,\n    name: renamed?.get(device.address) ?? device.name ?? null,\n    ...(rooms !== undefined ? { rooms } : {}),\n    ...(functions !== undefined ? { functions } : {}),\n    ...(device.firmware !== undefined ? { firmware: device.firmware } : {}),\n    ...(device.availableFirmware !== undefined\n      ? { availableFirmware: device.availableFirmware }\n      : {}),\n    ...(device.updatable !== undefined ? { updatable: device.updatable } : {}),\n    ...(device.firmwareUpdateState !== undefined\n      ? { firmwareUpdateState: device.firmwareUpdateState }\n      : {}),\n    channels,\n  };\n}\n\n/** Map a {@link SystemVariable} to its public {@link HmSysVar} snapshot. */\nfunction toHmSysVar(sysvar: SystemVariable): HmSysVar {\n  return {\n    id: sysvar.id,\n    name: sysvar.name,\n    type: sysvar.type,\n    value: sysvar.value,\n    writable: sysvar.writable,\n    isInternal: sysvar.isInternal,\n    ...(sysvar.unit !== undefined ? { unit: sysvar.unit } : {}),\n    ...(sysvar.valueList !== undefined ? { valueList: sysvar.valueList } : {}),\n    ...(sysvar.min !== undefined ? { min: sysvar.min } : {}),\n    ...(sysvar.max !== undefined ? { max: sysvar.max } : {}),\n  };\n}\n\n/** Map a {@link HmProgramRecord} to its public {@link HmProgram} snapshot. */\nfunction toHmProgram(program: HmProgramRecord): HmProgram {\n  return {\n    id: program.id,\n    name: program.name,\n    isActive: program.isActive,\n    isInternal: program.isInternal,\n    ...(program.lastExecuteTime !== undefined ? { lastExecuteTime: program.lastExecuteTime } : {}),\n  };\n}\n\n/**\n * Aggregate a channel-address-keyed map (`DEV:idx` → names) to the device level\n * (`DEV` → union of all its channels' names). An entry keyed by the bare device\n * address is included verbatim. Order-stable, de-duplicated.\n */\nfunction aggregateByDevice(\n  byChannel: ReadonlyMap<string, readonly string[]>,\n): Map<string, string[]> {\n  const out = new Map<string, string[]>();\n  for (const [address, names] of byChannel) {\n    const deviceAddress = deviceAddressOf(address);\n    const existing = out.get(deviceAddress) ?? [];\n    for (const name of names) {\n      if (!existing.includes(name)) existing.push(name);\n    }\n    out.set(deviceAddress, existing);\n  }\n  return out;\n}\n\n/**\n * Union two optional string lists into one (de-duplicated, order-stable: base\n * first, then any new extras). Returns `undefined` when both are empty so the\n * snapshot omits the field rather than carrying an empty array.\n */\nfunction unionStrings(\n  base: readonly string[] | undefined,\n  extra: readonly string[] | undefined,\n): readonly string[] | undefined {\n  if ((base === undefined || base.length === 0) && (extra === undefined || extra.length === 0)) {\n    return undefined;\n  }\n  const out: string[] = [];\n  for (const name of base ?? []) {\n    if (!out.includes(name)) out.push(name);\n  }\n  for (const name of extra ?? []) {\n    if (!out.includes(name)) out.push(name);\n  }\n  return out;\n}\n","/**\n * Public, transport-agnostic types exposed by the library's facade. No internal\n * transport/central types leak through these shapes: a consumer sees only\n * plain, serialisable data + the {@link HmValue} domain.\n */\n\nexport type { HmValue } from '../model/converter.js';\nimport type { HmValue } from '../model/converter.js';\n\n/** A public snapshot of a single data point. */\nexport interface HmDataPoint {\n  /** Stable unique id (the dpk encoded as a lowercased string). */\n  readonly id: string;\n  /** Parameter name, e.g. `STATE`. */\n  readonly parameter: string;\n  /** Parameter value type, e.g. `BOOL`, `FLOAT`, `ENUM`. */\n  readonly type: string;\n  /** Current value (`null` until the first event). */\n  readonly value: HmValue;\n  readonly unit?: string;\n  readonly readable: boolean;\n  readonly writable: boolean;\n  readonly hasEvents: boolean;\n  readonly valueList?: readonly string[];\n  readonly min?: number;\n  readonly max?: number;\n}\n\n/** A public snapshot of a single channel. */\nexport interface HmChannel {\n  readonly address: string;\n  readonly index: number;\n  readonly type?: string;\n  /**\n   * CCU user-given channel name from JSON-RPC `Device.listAllDetail`.\n   * `null` when the CCU has none or the name read failed — never the address.\n   */\n  readonly name: string | null;\n  readonly dataPoints: readonly HmDataPoint[];\n}\n\n/** One direct device link from XML-RPC `getLinks` (`SENDER` / `RECEIVER` / `NAME`). */\nexport interface HmChannelLink {\n  readonly sender: string;\n  readonly receiver: string;\n  readonly name: string;\n}\n\n/**\n * Central-link flag plus the direct links of one channel.\n * `central` is `getMetadata(\"reportValueUsageData\").PRESS_SHORT > 0`, not a\n * peer inside `links`.\n */\nexport interface HmChannelLinkState {\n  readonly central: boolean;\n  readonly links: readonly HmChannelLink[];\n}\n\n/**\n * What one key press does on a switch actuator link. `none` is\n * `PROFILE_ACTION_TYPE_INACTIVE` (the press is ignored).\n */\nexport type HmLinkPressAction = 'toggle' | 'on' | 'off' | 'none';\n\n/** The short and long press actions of a key → switch actuator link. */\nexport interface HmSwitchLinkActions {\n  readonly short: HmLinkPressAction;\n  readonly long: HmLinkPressAction;\n}\n\n/** A link whose receiver paramset matches the switch catalogue exactly. */\nexport interface HmSwitchLinkProfile extends HmSwitchLinkActions {\n  readonly kind: 'switch';\n}\n\n/**\n * A key → switch link whose receiver paramset matches no catalogue profile\n * (a timer, a delay, an expert setting). It is never rewritten by\n * `setLinkProfile`.\n */\nexport interface HmCustomLinkProfile {\n  readonly kind: 'custom';\n}\n\n/** The resolved profile of a key → switch actuator link. */\nexport type HmLinkProfile = HmSwitchLinkProfile | HmCustomLinkProfile;\n\n/** One direct link with its CCU name, description and resolved profile. */\nexport interface HmLink {\n  readonly sender: string;\n  readonly receiver: string;\n  /** `NAME` from `getLinks`; `\"\"` when the CCU sent none. */\n  readonly name: string;\n  /** `DESCRIPTION` from `getLinks` verbatim; `\"\"` when the CCU sent none. */\n  readonly description: string;\n  /**\n   * The switch profile, or `null` when the link is not a `KEY_TRANSCEIVER` →\n   * `SWITCH_VIRTUAL_RECEIVER` link between two known channels (no catalogue\n   * applies).\n   */\n  readonly profile: HmLinkProfile | null;\n}\n\n/** A device or channel address with the name the CCU now holds for it. */\nexport interface HmNamedObject {\n  readonly address: string;\n  readonly name: string;\n}\n\n/** Options of `renameDevice`. */\nexport interface HmRenameDeviceOptions {\n  /** Also rename every channel to `<name>:<channelIndex>`. */\n  readonly renameChannels: boolean;\n}\n\n/** The names the CCU applied after `renameDevice` (it may adjust them to stay unique). */\nexport interface HmDeviceRename {\n  readonly device: HmNamedObject;\n  /** Renamed channels; empty when `renameChannels` was `false`. */\n  readonly channels: readonly HmNamedObject[];\n}\n\n/** A CCU room with its member channels. */\nexport interface HmRoom {\n  /** ReGa object id of the room. */\n  readonly id: string;\n  readonly name: string;\n  /** Member channel addresses (`DEVICE:index`). */\n  readonly channels: readonly string[];\n}\n\n/** Key press parameters a key event program listens to. */\nexport type HmKeyEventParameter = 'PRESS_SHORT' | 'PRESS_LONG';\n\n/** Input of {@link Homematic.ensureKeyEventProgram}. */\nexport interface HmKeyEventProgramInput {\n  /** Program name; the program is found by it. */\n  readonly name: string;\n  /** Key channels (`DEV:1`), all on one interface. */\n  readonly channelAddresses: readonly string[];\n  /** Defaults to `PRESS_SHORT` and `PRESS_LONG`. */\n  readonly parameters?: readonly HmKeyEventParameter[];\n}\n\n/** Result of {@link Homematic.ensureKeyEventProgram}. */\nexport interface HmKeyEventProgramResult {\n  readonly programId: string;\n  /** `true` when the program did not exist before. */\n  readonly created: boolean;\n}\n\n/** A key event program as found on the CCU. */\nexport interface HmKeyEventProgram {\n  readonly programId: string;\n  readonly channelAddresses: string[];\n}\n\n// --- key event diagnosis -------------------------------------------------------\n\n/**\n * One section of {@link HmKeyEventDiagnosis}. A section that could not be read\n * is `{ ok: false, error }`; it never fails the whole diagnosis.\n */\nexport type HmDiagnosisSection<T> =\n  { readonly ok: true; readonly data: T } | { readonly ok: false; readonly error: string };\n\n/** A VALUES / MASTER paramset as the interface returned it (parameter name -> raw value). */\nexport type HmParamsetValues = Readonly<Record<string, unknown>>;\n\n/** Central link of one channel: XML-RPC `getMetadata(ch, \"reportValueUsageData\")`. */\nexport interface HmKeyCentralLink {\n  /** The `PRESS_SHORT` usage counter, or `null` when the metadata has none. */\n  readonly pressShortCount: number | null;\n  /** `pressShortCount > 0` (aiohomematic `Channel._has_central_link`). */\n  readonly active: boolean;\n}\n\n/** The device's maintenance channel (`:0`) values that tell whether it is reachable and configured. */\nexport interface HmKeyDeviceMaintenance {\n  /** Address of the maintenance channel, `<device>:0`. */\n  readonly channelAddress: string;\n  /** `null` when the parameter is absent from the answer. */\n  readonly configPending: unknown;\n  readonly unreach: unknown;\n  readonly rssiDevice: unknown;\n  readonly rssiPeer: unknown;\n  readonly updatePending: unknown;\n}\n\n/** What THIS client received for one parameter, from the library's own data points. */\nexport interface HmKeyParameterClientState {\n  readonly parameter: string;\n  /** Whether the library has a data point for it. */\n  readonly known: boolean;\n  /** Epoch ms of the last event applied to the data point, `null` when none arrived. */\n  readonly lastEventAt: number | null;\n  /** The data point's current value (`null` until the first event). */\n  readonly value: unknown;\n}\n\n/** Events THIS client received for one channel. */\nexport interface HmKeyChannelClientState {\n  readonly channelAddress: string;\n  /** `PRESS_SHORT`, `PRESS_LONG`, `PRESS_LONG_RELEASE` first, then every other data point. */\n  readonly parameters: readonly HmKeyParameterClientState[];\n}\n\n/** XML-RPC view of one key channel. */\nexport interface HmKeyChannelXmlRpc {\n  readonly centralLink: HmDiagnosisSection<HmKeyCentralLink>;\n  /** `getLinks(ch, 0)`. */\n  readonly directLinks: HmDiagnosisSection<readonly HmChannelLink[]>;\n  /** `getParamset(ch, \"VALUES\")`. */\n  readonly values: HmDiagnosisSection<HmParamsetValues>;\n  /** `getParamset(ch, \"MASTER\")`, raw: the key settings. */\n  readonly master: HmDiagnosisSection<HmParamsetValues>;\n}\n\n/** One key channel in {@link HmKeyEventDiagnosis}. */\nexport interface HmKeyChannelDiagnosis {\n  readonly address: string;\n  /** Channel type from the device description, e.g. `KEY_TRANSCEIVER`. */\n  readonly type: string | null;\n  readonly xmlRpc: HmKeyChannelXmlRpc;\n  readonly client: HmKeyChannelClientState;\n}\n\n/** One ReGa data point of a key channel (`<iface>.<addr>:<n>.PRESS_SHORT` ...). */\nexport interface HmKeyRegaDatapoint {\n  /** The ReGa name, `<interface>.<channel address>.<PARAM>`. */\n  readonly name: string;\n  /** Whether the CCU has such a data point; `false` is why no program can use it. */\n  readonly exists: boolean;\n  readonly id: string | null;\n  /** `Value()` as ReGa prints it (a boolean is `\"true\"` / `\"false\"`). */\n  readonly value: string | null;\n  /** `Timestamp()` as epoch ms: the last time the CCU UPDATED the data point (any event, even an unchanged value). */\n  readonly timestamp: number | null;\n  /** `LastTimestamp()` as epoch ms: the update before `timestamp`. */\n  readonly lastTimestamp: number | null;\n}\n\n/** The ReGa channel object of a key channel and its key data points. */\nexport interface HmKeyRegaChannel {\n  readonly address: string;\n  /** `false` when ReGa has no channel with that address. */\n  readonly found: boolean;\n  readonly id: string | null;\n  readonly name: string | null;\n  readonly visible: boolean | null;\n  /** `Enabled()`; `null` when ReGa answered nothing. */\n  readonly enabled: boolean | null;\n  /** `ReadyConfig()`; `null` when ReGa answered nothing. */\n  readonly readyConfig: boolean | null;\n  /** `LastDPActionTime`: the last time any data point of the channel was acted on, epoch ms. */\n  readonly lastActionAt: number | null;\n  readonly datapoints: readonly HmKeyRegaDatapoint[];\n}\n\n/** A CCU program whose condition references one of the key data points. */\nexport interface HmKeyRegaProgram {\n  readonly id: string;\n  readonly name: string;\n  readonly active: boolean | null;\n  /** `Internal()`: a system program the WebUI hides. */\n  readonly internal: boolean | null;\n  /** `ProgramLastExecuteTime`, epoch ms; `null` when it never ran. */\n  readonly lastExecutedAt: number | null;\n  /** The key data point names its conditions reference. */\n  readonly datapoints: readonly string[];\n}\n\n/** A CCU program whose conditions reference key channels, from {@link Homematic.keyProgramReferences}. */\nexport interface HmKeyProgramReference {\n  readonly id: string;\n  readonly name: string;\n  /** `Active()`; `null` when ReGa answered nothing. */\n  readonly active: boolean | null;\n  /** The key channel addresses (`<device>:<n>`) the conditions reference, each once. */\n  readonly channels: readonly string[];\n}\n\n/** What the CCU's ReGa knows about the key channels. */\nexport interface HmKeyRegaState {\n  readonly channels: readonly HmKeyRegaChannel[];\n  /** Empty when no program references a key data point. */\n  readonly programs: readonly HmKeyRegaProgram[];\n}\n\n/** The ReGa part of the diagnosis: unavailable (no WebUI credentials, script failure) or read. */\nexport type HmKeyRegaDiagnosis =\n  | { readonly available: true; readonly state: HmKeyRegaState }\n  | { readonly available: false; readonly reason: string };\n\n/** Connection health of the device's interface, from the library's own tracker. */\nexport interface HmKeyInterfaceClientState {\n  readonly interfaceId: string;\n  /** Connection state, e.g. `CONNECTED`. */\n  readonly state: string;\n  /** Epoch ms of the latest event of ANY kind received on the interface, `null` when none. */\n  readonly lastEventAt: number | null;\n  /** The callback is alive: no silence beyond the warn interval. */\n  readonly callbackAlive: boolean;\n}\n\n/** Result of {@link Homematic.diagnoseKeyEvents}. */\nexport interface HmKeyEventDiagnosis {\n  readonly deviceAddress: string;\n  readonly interfaceId: string;\n  /** Epoch ms the diagnosis was taken. */\n  readonly takenAt: number;\n  /** The maintenance channel `:0` over XML-RPC. */\n  readonly maintenance: HmDiagnosisSection<HmKeyDeviceMaintenance>;\n  /** Events this client received on the maintenance channel. */\n  readonly maintenanceClient: HmKeyChannelClientState;\n  /** Key channels found on the device (empty when it has none). */\n  readonly channels: readonly HmKeyChannelDiagnosis[];\n  /** ReGa data points and programs for the key channels. */\n  readonly rega: HmKeyRegaDiagnosis;\n  readonly interfaceClient: HmKeyInterfaceClientState;\n}\n\n/** A public snapshot of a single device. */\n\nexport interface HmDevice {\n  readonly address: string;\n  readonly type: string;\n  /**\n   * CCU user-given device name from JSON-RPC `Device.listAllDetail`.\n   * `null` when the CCU has none or the name read failed — never the address.\n   */\n  readonly name: string | null;\n  readonly rooms?: readonly string[];\n  readonly functions?: readonly string[];\n  /** Installed firmware version, e.g. `1.18.24` (CCU descriptor `FIRMWARE`). */\n  readonly firmware?: string;\n  /** Latest firmware available, e.g. `1.18.24` (CCU descriptor `AVAILABLE_FIRMWARE`). */\n  readonly availableFirmware?: string;\n  /** Whether a firmware update can be installed (CCU descriptor `UPDATABLE`). */\n  readonly updatable?: boolean;\n  /** Firmware update lifecycle state, e.g. `UP_TO_DATE` (CCU descriptor `FIRMWARE_UPDATE_STATE`). */\n  readonly firmwareUpdateState?: string;\n  readonly channels: readonly HmChannel[];\n}\n\n/**\n * A public snapshot of a CCU system variable (hub layer). Immutable; values are\n * parsed into the {@link HmValue} domain. `writable` reflects the `HAHM`\n * extended-sysvar marker — only writable variables may be set.\n */\nexport interface HmSysVar {\n  readonly id: string;\n  readonly name: string;\n  /** Normalised value type, e.g. `FLOAT`, `LOGIC`, `LIST`, `STRING`. */\n  readonly type: string;\n  readonly value: HmValue;\n  readonly unit?: string;\n  readonly writable: boolean;\n  readonly isInternal: boolean;\n  readonly valueList?: readonly string[];\n  readonly min?: number;\n  readonly max?: number;\n}\n\n/** A public snapshot of a CCU program (rule/automation). Immutable. */\nexport interface HmProgram {\n  readonly id: string;\n  readonly name: string;\n  readonly isActive: boolean;\n  readonly isInternal: boolean;\n  readonly lastExecuteTime?: string;\n}\n\n/**\n * A reference to a data point, accepted by the facade's read/write methods.\n * Either the stable string id, or a structured `{ device, channel, parameter }`\n * locator (channel as the numeric index or full channel address).\n */\nexport type DataPointRef =\n  | string\n  | { readonly device: string; readonly channel: number | string; readonly parameter: string };\n\n/**\n * A single device-configuration parameter (MASTER paramset), with the metadata\n * a configuration UI needs to render a form field for it.\n */\nexport interface HmConfigParam {\n  readonly parameter: string;\n  readonly type: string;\n  readonly min?: number;\n  readonly max?: number;\n  readonly default?: HmValue;\n  readonly unit?: string;\n  readonly valueList?: readonly string[];\n  /** Raw CCU `FLAGS` bitmask. */\n  readonly flags: number;\n  /** True when `OPERATIONS & WRITE` is set. */\n  readonly writable: boolean;\n}\n\n/** The MASTER configuration parameters of a single channel. */\nexport interface HmChannelConfig {\n  readonly channelAddress: string;\n  readonly params: HmConfigParam[];\n}\n\n// --- Custom entities (typed domain views over generic data points) ----------\n//\n// A custom entity aggregates several data points of one device into a typed\n// domain object (Climate / Switch / Light / Cover / Lock). These snapshot types\n// carry only plain, serialisable state — never functions; commands are issued\n// through the facade's ergonomic command methods (e.g. `climateSetTemperature`).\n\n/** A climate (thermostat / heating-group) snapshot. */\nexport interface HmClimate {\n  readonly kind: 'climate';\n  /** Owning device address, e.g. `VCU0000001`. */\n  readonly device: string;\n  /** Primary channel address, e.g. `VCU0000001:1`. */\n  readonly channel: string;\n  readonly currentTemperature: number | null;\n  readonly targetTemperature: number | null;\n  readonly currentHumidity: number | null;\n  readonly minTemp: number;\n  readonly maxTemp: number;\n  readonly targetTemperatureStep: number;\n  readonly mode: 'auto' | 'heat' | 'off';\n  readonly preset: 'boost' | 'away' | 'week_program' | 'none';\n  readonly activity: 'heating' | 'idle' | 'off';\n}\n\n/** An on/off switch snapshot. */\nexport interface HmSwitch {\n  readonly kind: 'switch';\n  readonly device: string;\n  readonly channel: string;\n  readonly isOn: boolean;\n}\n\n/** A dimmable light snapshot. */\nexport interface HmLight {\n  readonly kind: 'light';\n  readonly device: string;\n  readonly channel: string;\n  readonly isOn: boolean;\n  /** Brightness 0..255, or `null` when unavailable. */\n  readonly brightness: number | null;\n}\n\n/** A cover/blind snapshot. */\nexport interface HmCover {\n  readonly kind: 'cover' | 'blind';\n  readonly device: string;\n  /** The channel this entity is COMMANDED on. */\n  readonly channel: string;\n  /**\n   * Every channel the entity touches, command and status alike.\n   *\n   * An HmIP cover reports its position on the SHUTTER_TRANSMITTER channel and\n   * is commanded on a SHUTTER_VIRTUAL_RECEIVER, so a consumer filtering\n   * `valueChanged` by {@link channel} alone drops exactly the reports it wants.\n   */\n  readonly channels: readonly string[];\n  /**\n   * The subset of {@link channels} the entity READS from, when that differs\n   * from where it is commanded.\n   *\n   * A consumer watching raw parameter events needs this and not just the\n   * union: `LEVEL` exists on BOTH an HmIP cover's channels, so accepting both\n   * and taking the last arrival lets the receiver's commanded extreme\n   * overwrite the transmitter's real position. Take a parameter from a status\n   * channel when it is available there.\n   */\n  readonly statusChannels: readonly string[];\n  /** Position 0..100, or `null` when unavailable. */\n  readonly currentPosition: number | null;\n  readonly isClosed: boolean;\n  /** What the cover is doing right now, from its travel data point. */\n  readonly travel: 'opening' | 'closing' | 'stable' | 'unknown';\n  /** Slat tilt 0..100 (blinds only), or `null` when unavailable. */\n  readonly currentTiltPosition?: number | null;\n}\n\n/** A lock snapshot. */\nexport interface HmLock {\n  readonly kind: 'lock';\n  readonly device: string;\n  readonly channel: string;\n  readonly isLocked: boolean;\n}\n\n/**\n * A custom-entity snapshot — a discriminated union keyed by `kind`. An immutable\n * view of the entity's current state; issue commands through the facade methods.\n */\nexport type HmCustomEntity = HmClimate | HmSwitch | HmLight | HmCover | HmLock;\n\n// --- CCU management ---------------------------------------------------------\n//\n// Shapes for the facade's CCU-management API (interfaces & radio health,\n// pairing, device removal, service messages, CCU info, heating groups). A value\n// the CCU did not answer is `null`, never `0` / `false` / `''`.\n\n/** One radio gateway behind a BidCos interface (the CCU's own radio or a LAN gateway). */\nexport interface HmRadioGateway {\n  readonly address: string;\n  readonly description: string | null;\n  /** Duty cycle in percent (0..100), or `null` when not reported. */\n  readonly dutyCycle: number | null;\n  readonly connected: boolean | null;\n  readonly isDefault: boolean;\n  readonly firmware: string | null;\n  readonly type: string | null;\n}\n\n/** A CCU interface (BidCos-RF, HmIP-RF, VirtualDevices, ...) and its radio health. */\nexport interface HmInterfaceInfo {\n  /** Interface name as the CCU spells it, e.g. `HmIP-RF`. */\n  readonly name: string;\n  /** XML-RPC port of the interface service, or `null` when unknown. */\n  readonly port: number | null;\n  /** The CCU's short description of the interface, or `null`. */\n  readonly info: string | null;\n  /** Whether the interface service / radio is reachable; `null` when it could not be told. */\n  readonly connected: boolean | null;\n  /** Duty cycle in percent (0..100); `null` when the CCU did not report one. */\n  readonly dutyCycle: number | null;\n  readonly firmware: string | null;\n  readonly type: string | null;\n  /** Radio gateways (BidCos only; empty for other interfaces). */\n  readonly gateways: readonly HmRadioGateway[];\n}\n\n/** BidCos pairing flavour: `normal`, or `secure` (also teaches the HomeMatic Secure key). */\nexport type HmInstallModeKind = 'normal' | 'secure';\n\n/** Input of {@link Homematic.setInstallMode}. */\nexport interface HmInstallModeRequest {\n  /** Interface name, e.g. `HmIP-RF`. Must be one of the facade's configured interfaces. */\n  readonly interface: string;\n  readonly on: boolean;\n  /** Pairing window length in seconds (1..3600, default 60). Ignored when `on` is false. */\n  readonly seconds?: number;\n  /** BidCos only. Defaults to the CCU's own default (normal). */\n  readonly mode?: HmInstallModeKind;\n}\n\n/**\n * Bit flags of {@link Homematic.deleteDevice}. OR them together, e.g.\n * `HM_DELETE_FLAGS.RESET | HM_DELETE_FLAGS.FORCE`.\n */\nexport const HM_DELETE_FLAGS = {\n  /** 0x01: reset the device to factory settings while removing it. */\n  RESET: 0x01,\n  /** 0x02: remove it even when it is not reachable. */\n  FORCE: 0x02,\n  /** 0x04: remove it the next time it is reachable. */\n  DEFER: 0x04,\n} as const;\n\n/** A single active service message (`Servicemeldung`). */\nexport interface HmServiceMessage {\n  /** ReGa object id; pass to {@link Homematic.acknowledgeServiceMessage}. */\n  readonly id: string;\n  /** Name of the alarm object as the CCU shows it, or `null`. */\n  readonly name: string | null;\n  /** Device address (without the channel), or `null` when the message has no device. */\n  readonly address: string | null;\n  /** Channel index the message came from (`0` = maintenance), or `null`. */\n  readonly channel: number | null;\n  /** Message kind, e.g. `UNREACH`, `LOWBAT`, `CONFIG_PENDING`, `STICKY_UNREACH`. */\n  readonly type: string | null;\n  /** When it came in, epoch milliseconds, or `null` when the CCU reported none. */\n  readonly timestamp: number | null;\n  /** Whether the CCU lets an operator acknowledge it (sticky messages; the rest clear themselves). */\n  readonly acknowledgeable: boolean;\n}\n\n/** What the CCU says about itself. Each field is `null` when it did not answer. */\nexport interface HmCcuInfo {\n  /** Firmware version, e.g. `3.75.7`. */\n  readonly version: string | null;\n  /** Raw `PRODUCT=` of the CCU's `/VERSION`, e.g. `ccu3`, `raspberrymatic`, `ova` (OpenCCU as a VM). */\n  readonly product: string | null;\n  /** Derived family: `ccu3`, `openccu` (OpenCCU / RaspberryMatic, any platform) or `unknown`. */\n  readonly productFamily: 'ccu3' | 'openccu' | 'unknown';\n  /** Raw `PLATFORM=` of `/VERSION`, e.g. `ova`, `rpi4`. */\n  readonly platform: string | null;\n  readonly serial: string | null;\n  readonly hostname: string | null;\n}\n\n/** A channel that belongs to a {@link HmGroup}. */\nexport interface HmGroupMember {\n  /** Channel address, e.g. `000A9D89A7AF25:1`. */\n  readonly address: string;\n  /** Channel type, e.g. `WALLMOUNTED_THERMOSTAT`. */\n  readonly type: string;\n}\n\n/** A heating group as the WebUI's \"Gruppen\" page shows it (read-only here). */\nexport interface HmGroup {\n  readonly id: number;\n  readonly name: string;\n  /** Group type id: `hmip.heating.group` (HmIP) or `HomeMatic.heating`. */\n  readonly type: string;\n  readonly typeLabel: string | null;\n  /** The virtual device that operates the group (`INT0000001`), when named. */\n  readonly deviceAddress: string | null;\n  readonly forbidSingleOperation: boolean;\n  readonly members: readonly HmGroupMember[];\n}\n\n/** Input of {@link Homematic.createGroup}. */\nexport interface HmGroupCreate {\n  /** Group name (a `\"` is replaced by `'`, as the WebUI does). */\n  readonly name: string;\n  /** Group type id, e.g. `hmip.heating.group` or `HomeMatic.heating`. */\n  readonly type: string;\n  /** Member channel addresses, e.g. `000A9D89A7AF25:1`. */\n  readonly members: readonly string[];\n}\n\n/** Input of {@link Homematic.updateGroup}; at least one field is required. */\nexport interface HmGroupUpdate {\n  readonly name?: string;\n  /** The full new member list (not a delta). */\n  readonly members?: readonly string[];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAM,eAAe;;;ACoB5B,sBAAqC;;;ACd9B,IAAK,YAAL,kBAAKA,eAAL;AACL,EAAAA,WAAA,eAAY;AACZ,EAAAA,WAAA,aAAU;AACV,EAAAA,WAAA,kBAAe;AACf,EAAAA,WAAA,qBAAkB;AAJR,SAAAA;AAAA,GAAA;AAcL,IAAM,kBAA+D;AAAA,EAC1E,CAAC,2BAAmB,GAAG,EAAE,QAAQ,MAAM,KAAK,MAAM;AAAA,EAClD,CAAC,uBAAiB,GAAG,EAAE,QAAQ,MAAM,KAAK,MAAM;AAAA,EAChD,CAAC,iCAAsB,GAAG,EAAE,QAAQ,KAAM,KAAK,KAAM;AAAA,EACrD,CAAC,sCAAyB,GAAG,EAAE,QAAQ,MAAM,KAAK,MAAM;AAC1D;AASO,IAAM,wBAA4D;AAAA,EACvE,CAAC,sCAAyB,GAAG;AAC/B;AAOO,IAAM,gBAAgB;AAiBtB,IAAM,WAAW;AAAA;AAAA,EAEtB,KAAK;AAAA;AAAA,EAEL,MAAM;AAAA;AAAA,EAEN,SAAS;AACX;AAGO,SAAS,YAAY,aAAqB,OAA0B;AACzE,SAAO,GAAG,WAAW,IAAI,KAAK;AAChC;AAcO,SAAS,WAAW,IAAqB;AAC9C,UAAQ,KAAK,kBAAqB;AACpC;AAGO,SAAS,WAAW,IAAqB;AAC9C,UAAQ,KAAK,mBAAsB;AACrC;AAGO,SAAS,UAAU,IAAqB;AAC7C,UAAQ,KAAK,mBAAsB;AACrC;AAYO,SAAS,UAAU,OAAwB;AAChD,UAAQ,QAAQ,qBAAkB;AACpC;AAQO,IAAK,gBAAL,kBAAKC,mBAAL;AACL,EAAAA,eAAA,YAAS;AACT,EAA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AACA,aAAWA,SAAQ,SAAS,CAAC,GAAG;AAC9B,QAAI,CAAC,IAAI,SAASA,KAAI,EAAG,KAAI,KAAKA,KAAI;AAAA,EACxC;AACA,SAAO;AACT;;;ACtvCO,IAAM,kBAAkB;AAAA;AAAA,EAE7B,OAAO;AAAA;AAAA,EAEP,OAAO;AAAA;AAAA,EAEP,OAAO;AACT;","names":["Interface","ParameterType","interfaceId","channelAddress","delay","DEFAULTS","delay","name","name","record","channelAddress","name","import_undici","import_undici","undiciFetch","CONTROL_CHARS","name","channelAddress","name","CHANNEL_ADDRESS","CONTROL_CHARS","MAX_NAME","isRecord","name","validName","interfaceId","CHANNEL_ADDRESS","channelAddress","name","channel","isRecord","CHANNEL_ADDRESS","isRecord","name","channel","name","interfaceId","asStruct","errorMessage","channelAddress","channel","stableStringify","record","interfaceId","channelAddress","name","interfaceId","channelAddress","name","record","channel","HubValueType","isRecord","asString","asRecordArray","name","record","interfaceId","DEFAULTS","interfaceId","NOOP_LOGGER","name","deviceAddressOf","channelAddress","interfaceId","NOOP_LOGGER","interfaceId","channelAddress","name","channel","deviceAddressOf","socket","toBool","channelAddress","interfaceId","buildChannel","channel","buildDevice","isStruct","name","channel","interfaceId","isStruct","name","channel","toInterface","name","deviceAddressOf","channelAddress","interfaceId","channel","buildDevice","dp","program"]}