/** * @license * Copyright 2025-2026 Open Home Foundation * SPDX-License-Identifier: Apache-2.0 */ import type { WebRtcCallbackData } from "@matter-server/ws-client"; import { AsyncObservable, ClientNode, Duration, FabricId, FabricIndex, NodeId, Observable, NodeConnectionState } from "@matter/main"; import { OperationalCredentials } from "@matter/main/clusters"; import { WebRtcTransportProvider } from "@matter/main/clusters/web-rtc-transport-provider"; import { AttestationFinding, Invoke, Specifier } from "@matter/main/protocol"; import { EndpointNumber } from "@matter/main/types"; import { WebRtcTransportRequestorServer } from "@matter/node/behaviors/web-rtc-transport-requestor"; import type { SessionEstablishingCommandName, SignallingCommandName } from "../camera/webRtcProviderArguments.js"; import { AttributeResponseStatus, AttributesData, CommissioningRequest, CommissioningResponse, DiscoveryRequest, DiscoveryResponse, InteractionReadRequest, InteractionReport, InteractionSubscribeRequest, InteractionSubscription, InteractionSubscriptionListener, InvokeRequest, MatterNodeData, OpenCommissioningWindowRequest, OpenCommissioningWindowResponse, WriteAttributeRequest, WriteAtomicAttributeRequest, BatchedInvokeRequest, BatchedInvokeResult } from "../types/CommandHandler.js"; import { AccessControlEntry, AttributeWriteResult, BindingTarget, IcdStateData, MatterSoftwareVersion, NodePingResult, ServerError } from "../types/WebSocketMessageTypes.js"; import type { ControllerResources } from "./ControllerNode.js"; import { AttributeChange, EventChange } from "./PeerChangeBus.js"; /** The controller's own camera endpoint, which receives the WebRTC callbacks a peer sends back. */ export declare const CameraControllerEndpoint: import("@matter/main").MutableEndpoint.With, import("@matter/main").SupportedBehaviors.With<{ readonly webRtcTransportRequestor: typeof WebRtcTransportRequestorServer; }, readonly [typeof WebRtcTransportRequestorServer]>, {}>; export type CameraControllerEndpoint = typeof CameraControllerEndpoint; /** * Discovered peers, one entry per device, ordered by the advertisement each was last seen in. * * A device re-advertising within the discovery window is emitted again for the same node, so the raw * result counts one device many times, and the last entry is whichever device happened to be found first. */ export declare function uniqueByLastAdvertisement(discovered: readonly T[]): T[]; export interface ControllerCommandHandlerOptions { bleEnabled: boolean; bleProxyEnabled: boolean; otaEnabled: boolean; /** Defaults to false. */ timeSyncEnabled?: boolean; /** Defaults to false. */ threadDiagnosticsEnabled?: boolean; /** Interval between custom cluster polling cycles. Defaults to, and is floored at, 60 seconds. */ customClusterPollInterval?: Duration; /** * Do not subscribe to peers on our own, neither after commissioning nor when the server starts, unless switched on * per peer. Defaults to false. */ disableAutoSubscription?: boolean; /** Accept the attestation findings that test-net DCL tolerates, see {@link attestationRefusalOf}. Defaults to false. */ testNetDclEnabled?: boolean; } /** * Whether `finding` is an error-level finding that commissioning accepts with test-net DCL enabled: a test * certificate, or a Certification Declaration that cannot be checked against the BasicInformation VendorID or * ProductID because the device did not report it. * * @see Matter Core specification § 6.2.3.1 "Attestation Information Validation" */ export declare function isTestNetAcceptedError({ level, type, message }: AttestationFinding): boolean; /** * Why device attestation refuses a device, as the text the client is shown, or `undefined` when no finding * stops it. When enabling test-net DCL would accept the device, the text says so; otherwise every refusing finding is * named with its check. */ export declare function attestationRefusalOf(findings: AttestationFinding[], testNetDclEnabled: boolean): string | undefined; /** The result of {@link ourFabricEntriesOf}. */ export type OurFabricEntries = { kind: "ours"; value: unknown; } | { kind: "foreign" | "unchecked"; fabricIndex: number; }; /** * Prepares the value of a fabric-scoped list for a write of the WebSocket API, which writes only entries of our * fabric. The device stores every written entry under the writer's fabric, so an entry naming another fabric cannot * mean what the client intended. * * | FabricIndex of an entry | Result | * | --------------------------------------------------- | ------------------------------------------ | * | absent, `FabricIndex.OMIT_FABRIC` or ours | kept | * | `NO_FABRIC` (0) or `null`, the CHIP client defaults | replaced by `FabricIndex.OMIT_FABRIC` | * | another, with {@link fabricIndexOnPeer} known | `foreign`, the write is refused | * | another, with {@link fabricIndexOnPeer} unknown | `unchecked`, the write is refused | * * Pass `undefined` as {@link fabricIndexOnPeer} for a group write, whose members may know us by different indexes. * * @see Matter Core specification § 7.13.6 "FabricIndex Field" */ export declare function ourFabricEntriesOf(value: unknown, fabricIndexOnPeer: FabricIndex | undefined): OurFabricEntries; /** * The `NodeCommissionFailed` error for a failed commissioning, with a `reason` a client can act on. With * `attestationRejected` the reason is `attestation-rejected`, whatever error the aborted commissioning raised. */ export declare function commissionFailureOf(error: unknown, attestationRejected: boolean): ServerError; export declare class ControllerCommandHandler { #private; events: { started: AsyncObservable; /** A removed attribute is reported with an `undefined` value. */ attributeChanged: Observable<[nodeId: NodeId, data: AttributeChange], void>; eventChanged: Observable<[nodeId: NodeId, data: EventChange], void>; nodeAdded: Observable<[nodeId: NodeId], void>; nodeStateChanged: Observable<[nodeId: NodeId, state: NodeConnectionState], void>; /** Emitted when node availability changes (for sending node_updated events) */ nodeAvailabilityChanged: Observable<[nodeId: NodeId, available: boolean], void>; nodeStructureChanged: Observable<[nodeId: NodeId], void>; nodeDecommissioned: Observable<[nodeId: NodeId], void>; nodeEndpointAdded: Observable<[nodeId: NodeId, endpointId: EndpointNumber], void>; nodeEndpointRemoved: Observable<[nodeId: NodeId, endpointId: EndpointNumber], void>; webRtcCallback: Observable<[WebRtcCallbackData], void>; /** @see WebRtcProviderSessionWatchIo.reported */ webRtcProviderSessionsReported: Observable<[nodeId: NodeId, endpointId: EndpointNumber, present: ReadonlySet, restarted: boolean], void>; }; constructor(controller: ControllerResources, options: ControllerCommandHandlerOptions); /** Format a NodeId as a PeerAddress string for logging. */ formatNode(nodeId: NodeId): string; get started(): boolean; get bleEnabled(): boolean; get bleProxyEnabled(): boolean; get autoSubscriptionDisabled(): boolean; start(): Promise; /** * `fields` must already be in matter.js's convention (see `toProviderCommandFields`); any * `originatingEndpointId` in it is overwritten. */ invokeWebRtcProviderCommand(args: { nodeId: NodeId; endpointId: EndpointNumber; commandName: SessionEstablishingCommandName; fields: Record; /** @see WebRtcProviderSessionArgs.sessionEstablishing */ sessionEstablishing?: (webRtcSessionId: number) => void; }): Promise; /** * The session id is not checked against local records: they cover only this run, and the camera * answers for ids it does not hold. */ invokeWebRtcSignallingCommand(args: { nodeId: NodeId; endpointId: EndpointNumber; commandName: SignallingCommandName; fields: Record; }): Promise; /** This server's node id on the fabric: the `PeerNodeID` a camera stores for its sessions (§11.4.5.5). */ get localNodeId(): NodeId; /** @throws ServerError if node not found */ getNode(nodeId: NodeId): ClientNode; invokeCommand(node: ClientNode, request: Invoke.ConcreteCommandRequest, options?: Omit): Promise; /** @see WebRtcProviderSessions.removeTracked */ removeTrackedWebRtcSession(webRtcSessionId: number, nodeId: NodeId, endpointId: EndpointNumber): Promise; /** @see WebRtcProviderSessions.abandon */ abandonWebRtcSession(webRtcSessionId: number, nodeId: NodeId, endpointId: EndpointNumber): Promise; /** Release everything this handler owns. The controller node belongs to its creator and stays open. */ close(): Promise; /** * Initialize the controller and register all commissioned nodes, which populates their attribute * caches. Connecting the peers is the controller node's own job. * * Guarded by #connected so it runs exactly once, even if called multiple times * (e.g. when WebServer.start() registers handlers for multiple listen addresses). */ initializeNodes(): Promise; getNodeIds(): NodeId[]; hasNode(nodeId: NodeId): boolean; /** * Whether a node id is already reserved on the fabric, either by a commissioned peer or the commissioner itself. * Authoritative against matter.js rather than the locally tracked node set, which can drift from the fabric. */ isNodeIdInUse(nodeId: NodeId): boolean; /** * Alias for decommissionNode to match NodeCommandHandler interface. */ removeNode(nodeId: NodeId): Promise; interviewNode(nodeId: NodeId): Promise; /** * Await the node's attribute cache being populated so a direct read returns a complete snapshot * rather than the empty-then-node_updated sequence the lazy fallback in getNodeDetails produces. * A rebuild that is already running is awaited too, so a read after a structure change serves the * new structure instead of the one the node reported before it. */ ensureNodePopulated(nodeId: NodeId): Promise; /** * Get full node details in WebSocket API format. * @param nodeId The node ID * @param lastInterviewDate Optional last interview date (tracked externally) */ getNodeDetails(nodeId: NodeId, lastInterviewDate?: Date): MatterNodeData; /** * Read multiple attributes from a node by path strings. * Supports wildcards in paths. Batches up to 9 paths per read call. */ handleReadAttributes(nodeId: NodeId, attributePaths: string[], fabricFiltered?: boolean): Promise; /** * Read with full control over the Matter request. Unlike {@link handleReadAttributes} the paths go out as one * request, and only the data version filters the caller gives are sent. * @throws {ServerError} with code InvalidArguments, before anything is sent, for a malformed path or invalid id, a * request without paths, an `eventMin` or data version out of range, or `eventMin` without event paths and data * version filters without attribute paths. */ read(request: InteractionReadRequest): Promise; /** * Open a subscription of the caller's own. Only available with auto subscription disabled, and only for a node * whose auto subscription was not enabled with {@link setAutoSubscription}. Reports reach * {@link InteractionSubscriptionListener.report} except the priming report, which the result carries. matter.js ends * the subscription when the node is removed or the controller goes offline. * @throws {ServerError} with code InvalidArguments, before anything is sent, for the arguments {@link read} refuses * and for intervals outside 0 to 65535 seconds or a `maxInterval` below `minInterval`. */ subscribe(request: InteractionSubscribeRequest, listener: InteractionSubscriptionListener): Promise; /** * Set the fabric label. matter.js requires a non-empty label of at most 32 UTF-8 bytes; callers pass the result of * `normalizeFabricLabel` from `ConfigStorage`. * * Resolves once the controller holds the label. The connected nodes are told in the background, see * {@link #pushFabricLabel}. `pushed` resolves when that push has finished, was stopped by a newer label or by * {@link close}. It never rejects. * * A label the controller already holds tells no node and `pushed` resolves at once, even while an earlier push * of that label still runs. Clients such as Home Assistant send their label on every connect. */ setFabricLabel(label: string): Promise<{ pushed: Promise; }>; /** Current fabric label as known to matter.js. */ getFabricLabel(): string | undefined; /** * A concrete, untimed write goes through the node's state, which also updates the node data at once. A wildcard * endpoint or a timed write is sent as a plain Write; the node data then changes only with the next report. * * While a {@link handleWriteAtomicAttribute} on the cluster is open, a write to an attribute with the Atomic quality * is not sent and answers BUSY: the device would take it into that atomic write (Matter spec §7.15.3). A wildcard * endpoint then answers BUSY for every endpoint with the cluster. */ handleWriteAttribute(data: WriteAttributeRequest): Promise; /** * Writes one attribute with the Atomic quality inside one atomic write (Matter spec §7.15.1): BeginWrite, the * Write, then CommitWrite. The device applies the value only if the commit succeeds. The Write carries the * cluster's data version the client read, when it gave one, so the device refuses it with DATA_VERSION_MISMATCH * when the cluster changed since that read (§8.7.3.2), and the server rolls back. With `ignoreDataVersionMismatch` * the server instead sends the Write again without the data version, inside the same atomic write. A timed write * with a data version, by a stated timeout or because the attribute requires one, is refused with InvalidArguments * before anything is sent. The answer is the first status that is not Success: from the BeginWrite, from the * Write, or from the CommitWrite. * * A failed Write is followed by a RollbackWrite, and so is an error the Write throws. A CommitWrite is never rolled * back: answered with a failure, the device already discarded the pending write (§7.15.6.4.2); unanswered, the * commit may have landed, and a RollbackWrite could then discard an atomic write another client opened meanwhile. A * BeginWrite the device refused is not rolled back either: it opened no atomic write, and a write state that caused * the refusal is not ours to discard. * * A RollbackWrite that fails, other than with INVALID_IN_STATE (no atomic write open), may leave the atomic write * open on the device until its timeout. So may a BeginWrite or a CommitWrite whose answer is lost; an error that * shows the BeginWrite was never sent (the peer unreachable, an ICD asleep) does not count. That BeginWrite is not * rolled back: if the device refused it because another client of this server holds an atomic write, the rollback * would discard that client's write, since both count as the same writer. In both cases the cluster's lock is kept for the * timeout: the one the BeginWrite answered, or the requested one when no answer came. * * The CommitWrite and the RollbackWrite name the attribute ids the BeginWrite answered (§7.15.6.4.1). The device * knows all clients of this server as one writer (the Atomic Writer ID is the controller's node id, §7.15.2), so a * client that holds its own atomic write through `device_command` makes this write fail with INVALID_IN_STATE. * For the same reason the server keeps its own atomic writes apart: while one is open on the cluster, another one * and every {@link handleWriteAttribute} to an attribute of the cluster with the Atomic quality answer BUSY without * being sent. * * The Write does not go through the node's state, so the pending value never reaches the node data; the committed * value arrives with the next report. */ handleWriteAtomicAttribute(data: WriteAtomicAttributeRequest): Promise; /** Resolves once the packet is sent: no node answers. Each node's group table decides which endpoints act. */ handleGroupWriteAttribute(data: Omit): Promise; /** * Resolves once the packet is sent: no node answers, so there are no timeouts, and timed commands * cannot be groupcast. Duplicates are not coalesced: with no answer to share, the second would not be sent. */ handleGroupInvoke(data: Omit): Promise; /** * Sends all commands in one InvokeRequest, never split and never combined with other invokes, so a device sees * exactly the batch the client asked for. */ handleBatchedInvoke(data: BatchedInvokeRequest): Promise; handleInvoke(data: InvokeRequest): Promise; commissionNode(data: CommissioningRequest): Promise; getCommissionerNodeId(): NodeId; getCommissionerFabricData(): Promise<{ fabricId: FabricId; compressedFabricId: bigint; fabricIndex: number; }>; /** Discover commissionable devices */ handleDiscovery({ findBy }: DiscoveryRequest): Promise; getNodeIpAddresses(nodeId: NodeId, preferCache?: boolean): Promise; /** * Ping a node on all its known IP addresses. * @param nodeId The node ID to ping * @param attempts Number of ping attempts per IP (default: 1) * @returns A record of IP addresses to ping success status */ pingNode(nodeId: NodeId, attempts?: number): Promise; decommissionNode(nodeId: NodeId): Promise; openCommissioningWindow(data: OpenCommissioningWindowRequest): Promise; getFabrics(nodeId: NodeId): Promise<{ fabricId: any; vendorId: any; fabricIndex: any; label: any; }[]>; removeFabric(nodeId: NodeId, fabricIndex: FabricIndex): Promise; /** * Register this controller as an ICD Check-In client on the peer. * @throws {ServerError} with code IcdMultiAdmin if the peer has other-vendor administrators and * `options.allowMultiAdmin` is not set. */ registerIcd(nodeId: NodeId, options: { allowMultiAdmin?: boolean; ignoredVendors?: number[]; }): Promise; /** * Drop this controller's ICD Check-In registration. * `force` skips the peer round-trip (for an unreachable peer) and only clears local state. */ unregisterIcd(nodeId: NodeId, force: boolean): Promise; /** * Drop the local ICD registration and reconnect; a LIT peer re-registers automatically once subscribed. * With auto subscription disabled, and not enabled for the node, only the local registration is dropped. The last * {@link setAutoSubscription} call for the node decides the final setting, also one made while this runs. */ resyncIcd(nodeId: NodeId): Promise; /** * Switch the server's own subscription to one node on or off. Only available with auto subscription disabled, and * not kept across a restart. Enabling resolves once the subscription is active and ends the node's client * subscriptions, because the server's subscription does not keep other subscriptions. It fails when matter.js finds * the device unreachable while waiting, after {@link DEFAULT_CASE_CONNECTION_TIMEOUT}, or when the node is removed, * switched off with this method or the handler closes. Except when switched off, the setting stays enabled and * matter.js keeps trying. */ setAutoSubscription(nodeId: NodeId, enabled: boolean): Promise; getIcdState(nodeId: NodeId): Promise; /** * Set Access Control List entries on a node. * Writes to the ACL attribute on the AccessControl cluster (endpoint 0). */ setAclEntry(nodeId: NodeId, entries: AccessControlEntry[]): Promise; /** * Set bindings on a specific endpoint of a node. * Writes to the Binding attribute on the Binding cluster. */ setNodeBinding(nodeId: NodeId, endpointId: EndpointNumber, bindings: BindingTarget[]): Promise; /** * Check if a software update is available for a node. * First checks the cached updates from OTA events, then queries the DCL if not found. */ checkNodeUpdate(nodeId: NodeId): Promise; /** * Trigger a software update for a node. * @param nodeId The node to update * @param softwareVersion The target software version to update to */ updateNode(nodeId: NodeId, softwareVersion: number): Promise; /** * Drop cached update info for a vendor/product, so a newly stored image is seen by the next * `check_node_update` instead of the answer cached before it existed. */ invalidateAvailableUpdates(vendorId: number, productId: number): void; } //# sourceMappingURL=ControllerCommandHandler.d.ts.map