/** * @license * Copyright 2022-2026 Matter.js Authors * SPDX-License-Identifier: Apache-2.0 */ import { Message } from "#codec/MessageCodec.js"; import { NetworkProfile } from "#peer/NetworkProfile.js"; import { Session } from "#session/Session.js"; import { SessionParameters } from "#session/SessionParameters.js"; import { AsyncObservableValue, Bytes, Duration, Lifetime, ServerAddressUdp, Timestamp } from "@matter/general"; import { NodeId } from "@matter/types"; import { MessageChannel } from "./MessageChannel.js"; export type ExchangeLogContext = Record; export interface ExchangeSendOptions { /** * The response to this send should be an ack only and no StatusResponse or such. If a StatusResponse is returned * then this is handled as error. */ expectAckOnly?: boolean; /** * If the message is part of a multiple message interaction, this flag indicates that it is not allowed * to establish a new exchange */ multipleMessageInteraction?: boolean; /** * Defined an expected processing time by the responder for the message. This is used to calculate the final * timeout for responses together with the normal retransmission logic when MRP is used. */ expectedProcessingTime?: Duration; /** * Sends the message without requesting acknowledgement, for a message whose delivery we deliberately do not * track — a Busy or CloseSession status report, or an ICD check-in on a session we are about to drop. * * MRP requests an ack for every message on an MRP session, so there is nothing to opt into: only suppression is * expressible. */ suppressAck?: true; /** * Disables the MRP logic which means that no retransmissions are done and receiving an ack is not awaited. */ disableMrpLogic?: boolean; /** Additional context information for logging to be included at the beginning of the Message log. */ logContext?: ExchangeLogContext; /** * Aborts sending. Before or during the first transmission the send rejects with {@link AbortedError} (cause: the * reason). While waiting for the ack it resolves if the reason is an {@link AbortedError}, otherwise it rejects with * the reason. */ abort?: AbortSignal; /** * Ends only the waits for the ack and for retransmissions; the message is still transmitted once, even when this * fired before. The send then resolves. Either this or {@link abort} ends the waits; only {@link abort} stops the * transmission. */ ackWaitAbort?: AbortSignal; /** Number of MRP transmissions, the first one included (default: MRP.MAX_TRANSMISSIONS) */ maxRetransmissions?: number; /** Maximum MRP retransmission time (default: unlimited) */ maxRetransmissionTime?: Duration; /** Initial MRP retransmission time (default: calculated as by Matter specification) */ initialRetransmissionTime?: Duration; /** * Time after the first transmission from which no further retransmission is sent (default: unlimited). It applies * only once {@link MRP.MAX_TRANSMISSIONS} transmissions went out, so the peer always gets the standard MRP budget. * Reaching it ends the send the same way as reaching {@link maxRetransmissions}, including the final wait for a * response that may still be on its way. */ retransmissionTimeLimit?: Duration; /** * Transmission number at which the MRP backoff schedule of this send starts (default: 0). Lets a new exchange * continue the schedule of one it replaces instead of falling back to the base interval. Does not count against * {@link maxRetransmissions}. */ backoffOffset?: number; /** Suppress peer-loss reporting for this send. OR'd with {@link MessageExchange.Options.suppressPeerLoss}. */ suppressPeerLoss?: boolean; } export interface ExchangeReceiveOptions { /** Aborts receiving; rejects with {@link AbortedError} (cause: the reason) unless a message is already queued. */ abort?: AbortSignal; timeout?: Duration; /** * Defined an expected processing time by the responder for the message. This is used to calculate the final * timeout for responses together with the normal retransmission logic when MRP is used. */ expectedProcessingTime?: Duration; /** Suppress peer-loss reporting for this receive. OR'd with {@link MessageExchange.Options.suppressPeerLoss}. */ suppressPeerLoss?: boolean; } /** * Message size overhead of a Matter message: * 26 (Matter Message Header) + 12 (Matter Payload Header) taken from https://github.com/project-chip/connectedhomeip/blob/2d97cda23024e72f36216900ca667bf1a0d9499f/src/system/SystemConfig.h#L327 * 16 byte MIC is then also needed to be excluded from the max payload size * Secure Extensions and Message Extensions need to be handled by exchange additionally! */ export declare const MATTER_MESSAGE_OVERHEAD: number; /** * Interfaces {@link MessageExchange} with other components. */ export interface MessageExchangeContext { session: Session; localSessionParameters: SessionParameters; /** Additive MRP retransmission margin for our own (sender-side) network. */ localAdditionalMrpDelay: Duration; /** Fixed sender-side MRP backoff pad (e.g. an ICD's fast-polling interval), not amplified by backoff. */ localFixedMrpBackoff: Duration; peerLost(exchange: MessageExchange, cause: Error): Promise; /** @deprecated */ retry(number: number): void; } /** * A Matter "message exchange" is a sequence of messages associated with a single interaction. * * TODO - rewrite main send retransmission loop using sleeps instead of timers * TODO - track dangling promises (annotated with TODO) * TODO - replace throws with logging for some errors triggered by peer */ export declare class MessageExchange { #private; static fromInitialMessage(context: MessageExchangeContext, initialMessage: Message, options?: MessageExchange.Options): MessageExchange; static initiate(context: MessageExchangeContext, exchangeId: number, protocolId: number, options?: MessageExchange.Options): MessageExchange; constructor(config: MessageExchange.Config); get context(): MessageExchangeContext; get isInitiator(): boolean; /** * Overrides the medium-derived MRP retransmission margin for this exchange. * * An exchange the peer initiated has no construction options to carry {@link MessageExchange.Options * .peerAdditionalMrpDelay}, so a protocol that knows better than the peer's medium — BDX with a per-transfer * margin, say — applies it here once it has adopted the exchange. */ set peerAdditionalMrpDelay(margin: Duration); /** * Sets the receive-notifier when none was provided at construction time. This allows code that obtains an exchange * after its creation (e.g. via protocol handler dispatch) to hook into message receipt. */ set onReceive(fn: MessageExchange.ReceiveNotifier); /** * Sets the send-notifier when none was provided at construction time. Mirrors {@link onReceive} for code that * obtains an exchange after its creation and needs to observe transmissions. */ set onSend(fn: MessageExchange.SendNotifier); /** Emits when the exchange is actually closed. This happens after all Retries and Communication are done. */ get closed(): AsyncObservableValue<[any, ...any[]]>; get considerClosed(): any; /** Timestamp of the last send or receive on this exchange, used to evict the least-recently-active exchange. */ get lastActive(): Timestamp; /** * Emit when the exchange is closing, but not yet closed. We only wait for acks and retries to happen, but the * actual interaction logic is already done. */ get closing(): AsyncObservableValue<[any, ...any[]]>; get id(): number; get idStr(): string; get session(): Session; /** Number of retransmissions of the current outstanding message (resets on ack or new send). */ get retransmissionCount(): number; /** * True while a message we sent still awaits peer acknowledgement. The exchange cannot send a new message in this * state, so best-effort status reports (e.g. PASE/CASE InvalidParam on failure) must be skipped: the peer never * acked our prior message, so the send would only fail with a flow error. */ get hasUnackedMessage(): boolean; get channel(): MessageChannel; /** * Max Payload size of the exchange which bases on the maximum payload size of the channel reduced by Matter * protocol overhead. */ get maxPayloadSize(): number; join(...name: unknown[]): Lifetime; onMessageReceived(message: Message, duplicate?: boolean): Promise; send(messageType: number, payload: Bytes, options?: ExchangeSendOptions): Promise; nextMessage(options?: ExchangeReceiveOptions): Promise; sendStandaloneAckForMessage(message: Message): Promise; [Symbol.asyncDispose](): Promise; destroy(): Promise; startTimedInteraction(timeout: Duration): void; clearTimedInteraction(): void; hasTimedInteraction(): boolean; hasActiveTimedInteraction(): boolean; hasExpiredTimedInteraction(): boolean; /** * Closes the exchange. * * If cause is defined, the exchange is closed immediately, even if there are still messages to send. Further * attempts at communicating via the exchange will throw this error. * * If cause is undefined, the exchange is closed only after all messages have been sent. */ close(cause?: Error): Promise; get via(): string; /** * Expose some diagnostics for logging. * For simply one message exchanges without retransmissions nothing will be exposed */ get diagnostics(): string; /** * How much restarting on a new exchange with the base MRP schedule would shorten the wait until the next * (re)transmission. The base schedule has no {@link ExchangeSendOptions.backoffOffset} and no * {@link ExchangeSendOptions.initialRetransmissionTime}. Roughly zero near the base interval — e.g. an idle * peer, whose fresh interval is just as slow. */ get retransmissionRestartSaving(): Duration; } export declare namespace MessageExchange { interface Options { /** * Invoked when a message transmits */ onSend?: SendNotifier; /** * Invoked upon message receipt. */ onReceive?: ReceiveNotifier; /** * Network profile governing exchange throttling. Retained for diagnostics; MRP backoff derives from * {@link peerAdditionalMrpDelay} instead, so an explicit throttle override (e.g. "unlimited") does not * affect retransmission timing. */ network?: NetworkProfile; /** * Additive MRP retransmission margin for the peer's network medium. Sourced independently of * {@link network} so concurrency overrides cannot strip the medium-correct margin (e.g. thread's). * * Overrides {@link Session.peerMrpMargins}, which supplies the margin for exchanges created without this * option (notably peer-initiated ones). */ peerAdditionalMrpDelay?: Duration; /** * Optional address override for this exchange. When set, messages are sent to this address * instead of the session's default peer address. */ addressOverride?: ServerAddressUdp; /** Waive peer-loss inference here. Required for exchanges to a peer that drives its own recovery. */ suppressPeerLoss?: boolean; } interface Config extends Options { context: MessageExchangeContext; isInitiator: boolean; peerSessionId: number; nodeId?: NodeId; peerNodeId?: NodeId; exchangeId: number; protocolId: number; } /** * Callback invoked by exchange before message transmission. */ type SendNotifier = (message: Message, retransmission: number) => void; /** * Callback invoked by exchange after message receipt. */ type ReceiveNotifier = (message: Message, duplicate: boolean) => void; } //# sourceMappingURL=MessageExchange.d.ts.map