/** * @license * Copyright 2022-2026 Matter.js Authors * SPDX-License-Identifier: Apache-2.0 */ import { asError, Bytes, DataReader, Diagnostic, Endian, ImplementationError, Logger, MatterError, Observable, Time, } from "@matter/general"; import { BtpCodec } from "../codec/BtpCodec.js"; import { BleDisconnectedError } from "./Ble.js"; import { MatterBle } from "./BleConsts.js"; export class BtpMatterError extends MatterError {} export class BtpProtocolError extends BtpMatterError {} export class BtpFlowError extends BtpMatterError {} const MAXIMUM_SEQUENCE_NUMBER = 255; const logger = Logger.get("BtpSessionHandler"); export class BtpSessionHandler { private currentIncomingSegmentedMsgLength: number | undefined; private currentIncomingSegmentedPayload: Bytes | undefined; private prevIncomingSequenceNumber = 255; // Incoming Sequence Number received. Set to 255 to start at 0 private prevIncomingAckNumber = -1; // Previous ackNumber received private readonly ackReceiveTimer = Time.getTimer("BTP ack timeout", MatterBle.BTP_ACK_TIMEOUT, () => this.btpAckTimeoutTriggered(), ); private sequenceNumber = 0; // Sequence number is set to 0 already for the handshake, next sequence number is 1 private prevAckedSequenceNumber = -1; // Previous (outgoing) Acked Sequence Number private readonly queuedOutgoingMatterMessages = new Array>(); private sendInProgress = false; private readonly sendAckTimer = Time.getTimer("BTP send timeout", MatterBle.BTP_SEND_ACK_TIMEOUT, () => this.btpSendAckTimeoutTriggered(), ); private isActive = true; private idleTimeout = Time.getTimer("Central Device Idle Timer", MatterBle.BTP_CONN_IDLE_TIMEOUT, async () => { logger.info("Central Device Connection Idle Timer expired, closing BTP session"); await this.close(); }); readonly #closed = Observable<[]>(); readonly #stalledAfterHandshake = Observable<[messagesToReplay: readonly Bytes[]]>(); /** * Matter messages handed to {@link sendMatterMessage} while the peer has not acknowledged anything yet. Dropped as * soon as any BTP packet arrives, because from then on {@link stalledAfterHandshake} can no longer fire, and the * ack timeout bounds how much can accumulate. */ #messagesPendingFirstAck: Bytes[] | undefined = new Array(); /** Emitted exactly once when the session transitions to closed. */ get closed() { return this.#closed; } /** * Emitted instead of {@link closed} when the peer completed the handshake and then sent no BTP packet at all before * the acknowledgement timeout, although we sent it at least one Matter message. Carries the Matter messages the peer * never acknowledged in submission order. Only a central session above the minimum segment size reports this, as the * remedy is a smaller segment size. * * Some peripherals were observed to behave this way with large segments on Bluetooth 4.1 adapters and to work with * the minimum segment size; the cause is not established. Recovering is an interop workaround with no basis in the * specification: the transport may establish a fresh session with a smaller segment size and resend the messages, * which the specification neither describes nor forbids. * * The session is suspended when this fires: it no longer touches the transport, and the transport owns what happens * next. A session nobody observes closes on the acknowledgement timeout, so a transport that cannot renegotiate * need not observe this. */ get stalledAfterHandshake() { return this.#stalledAfterHandshake; } /** Factory method to create a new BTPSessionHandler from a received handshake request */ static async createFromHandshakeRequest( maxDataSize: number | undefined, handshakeRequestPayload: Bytes, writeBleCallback: (data: Bytes) => Promise, disconnectBleCallback: () => Promise, handleMatterMessagePayload: (data: Bytes) => Promise, ): Promise { // Decode handshake request const handshakeRequest = BtpCodec.decodeBtpHandshakeRequest(handshakeRequestPayload); const { versions, attMtu: handshakeMtu, // Number excluding 3 header bytes clientWindowSize, } = handshakeRequest; logger.debug(`Received BTP handshake request:`, Diagnostic.dict({ maxDataSize, ...handshakeRequest })); // Verify handshake request and choose the highest supported version for both parties const version = MatterBle.BTP_SUPPORTED_VERSIONS.find(version => versions.includes(version)); if (version === undefined) { await disconnectBleCallback(); throw new BtpProtocolError(`No supported BTP version found in ${versions}`); } let attMtu = MatterBle.MINIMUM_ATT_MTU; if (maxDataSize !== undefined) { if (maxDataSize > MatterBle.MINIMUM_ATT_MTU) { if (handshakeMtu <= MatterBle.MINIMUM_ATT_MTU) { attMtu = Math.min(maxDataSize, MatterBle.MAXIMUM_BTP_MTU); } else { attMtu = Math.min(handshakeMtu, maxDataSize, MatterBle.MAXIMUM_BTP_MTU); } } } const fragmentSize = attMtu; // The attMtu is the maximum size of a single ATT packet, so use as fragmentSize const windowSize = Math.min(MatterBle.BTP_MAXIMUM_WINDOW_SIZE, clientWindowSize); // Generate and send out handshake response const handshakeResponse = BtpCodec.encodeBtpHandshakeResponse({ version, attMtu, windowSize, }); logger.debug( `Sending BTP handshake response:`, Diagnostic.dict({ version, attMtu, windowSize, }), ); const btpSession = new BtpSessionHandler( "peripheral", version, fragmentSize, windowSize, writeBleCallback, disconnectBleCallback, handleMatterMessagePayload, ); await writeBleCallback(handshakeResponse); // Start awaiting the ack for the just-sent handshake response only now that it is on the wire. btpSession.ackReceiveTimer.start(); return btpSession; } /** * @param requestedSegmentSize The segment size offered in our handshake request. A peripheral must not select more * than we offered, so it also bounds the session; without it a peripheral that echoes an oversized value would * defeat a deliberate reduction of the segment size. */ static async createAsCentral( handshakeResponsePayload: Bytes, writeBleCallback: (data: Bytes) => Promise, disconnectBleCallback: () => Promise, handleMatterMessagePayload: (data: Bytes) => Promise, requestedSegmentSize: number, ) { if (!Number.isInteger(requestedSegmentSize) || requestedSegmentSize < MatterBle.MINIMUM_ATT_MTU) { throw new ImplementationError( `Requested BTP segment size must be an integer of at least ${MatterBle.MINIMUM_ATT_MTU}, got ${requestedSegmentSize}`, ); } const handshakeResponse = BtpCodec.decodeBtpHandshakeResponsePayload(handshakeResponsePayload); logger.debug("Handshake response", Diagnostic.dict(handshakeResponse)); const { version, attMtu: handshakeMtu, windowSize } = handshakeResponse; const fragmentSize = Math.min(handshakeMtu, requestedSegmentSize, MatterBle.MAXIMUM_BTP_MTU); return new BtpSessionHandler( "central", version, fragmentSize, windowSize, writeBleCallback, disconnectBleCallback, handleMatterMessagePayload, ); } /** * Creates a new BTP session handler * * @param role The role of the BTP session handler * @param btpVersion The BTP protocol version to use * @param fragmentSize The fragment size to use for the messages * @param clientWindowSize The client window size to use * @param writeBleCallback Callback to write data to the BLE transport * @param disconnectBleCallback Callback to disconnect the BLE transport * @param handleMatterMessagePayload Callback to handle a Matter message payload */ constructor( private readonly role: "central" | "peripheral", btpVersion: number, private readonly fragmentSize: number, private readonly clientWindowSize: number, private readonly writeBleCallback: (data: Bytes) => Promise, private readonly disconnectBleCallback: () => Promise, private readonly handleMatterMessagePayload: (data: Bytes) => Promise, ) { if (btpVersion !== 4) { throw new BtpProtocolError(`Unsupported BTP version ${btpVersion}`); } if (role === "peripheral") { // The handshake request is unsequenced, so nothing is pending to acknowledge yet. this.prevAckedSequenceNumber = this.prevIncomingSequenceNumber; // ackReceiveTimer is started once the handshake response has actually been written (see factory). } else { this.sendAckTimer.start(); this.prevIncomingSequenceNumber = 0; this.prevIncomingAckNumber = -1; this.sequenceNumber = -1; // First sequence number needs to be 0 } } /** * Handle incoming data from the transport layer and hand over completely received matter messages to the * ExchangeManager layer * * @param data ByteArray containing the data */ public async handleIncomingBleData(data: Bytes) { if (!this.isActive) { logger.debug(`BTP session is not active, ignoring incoming BLE data`); return; } try { if (data.byteLength > this.fragmentSize) { // Apple seems to interpret the ATT_MTU as the maximum size of a single ATT packet if (data.byteLength > this.fragmentSize + 3) { throw new BtpProtocolError( `Received data ${data.byteLength} bytes exceeds fragment size of ${this.fragmentSize} bytes`, ); } else { logger.warn( `Received data ${data.byteLength} bytes exceeds fragment size of ${this.fragmentSize} bytes, still accepting`, ); } } const btpPacket = BtpCodec.decodeBtpPacket(data); logger.debug(`Received BTP packet: ${Diagnostic.json(btpPacket)}`); const { header: { hasAckNumber, isHandshakeRequest, hasManagementOpcode, isEndingSegment, isBeginningSegment, isContinuingSegment, }, payload: { ackNumber, sequenceNumber, messageLength, segmentPayload }, } = btpPacket; if (isHandshakeRequest || hasManagementOpcode) { throw new BtpProtocolError("BTP packet must not be a handshake request or have a management opcode."); } if (segmentPayload.byteLength === 0 && !hasAckNumber) { throw new BtpProtocolError("BTP packet must have a segment payload or an ack number."); } if (sequenceNumber !== (this.prevIncomingSequenceNumber + 1) % 256) { logger.debug( `sequenceNumber : ${sequenceNumber}, prevClientSequenceNumber : ${this.prevIncomingSequenceNumber}`, ); throw new BtpProtocolError("Expected and actual BTP packets sequence number does not match"); } this.prevIncomingSequenceNumber = sequenceNumber; this.#messagesPendingFirstAck = undefined; if (!this.sendAckTimer.isRunning) { this.sendAckTimer.start(); } if (hasAckNumber && ackNumber !== undefined) { // A valid ack falls within the outstanding (sent-but-unacknowledged) interval // (prevIncomingAckNumber, sequenceNumber], compared as a wrap-safe modular distance. const outstanding = this.modularDistance(this.prevIncomingAckNumber, this.sequenceNumber); if (this.modularDistance(this.prevIncomingAckNumber, ackNumber) > outstanding) { throw new BtpProtocolError( `Invalid Ack Number, Ack Number: ${ackNumber}, Sequence Number: ${this.sequenceNumber}, Previous AckNumber: ${this.prevIncomingAckNumber}`, ); } // for valid ack, stop timer and update prevIncomingAckNumber this.ackReceiveTimer.stop(); this.prevIncomingAckNumber = ackNumber; // if still waiting for ack for sequence number restart timer if (ackNumber !== this.sequenceNumber) { this.ackReceiveTimer.start(); } } // Set or add the payload to the current incoming segmented payload if (isBeginningSegment) { if (this.currentIncomingSegmentedPayload !== undefined) { throw new BtpProtocolError( `BTP message flow error! New beginning packet was received without previous message being completed.`, ); } this.currentIncomingSegmentedMsgLength = messageLength; this.currentIncomingSegmentedPayload = segmentPayload; } else if (isContinuingSegment || isEndingSegment) { if (this.currentIncomingSegmentedPayload === undefined) { throw new BtpProtocolError(`BTP Continuing or ending packet received without beginning packet.`); } if (segmentPayload.byteLength === 0) { throw new BtpProtocolError(`BTP Continuing or ending packet received without payload.`); } const reassembledLength = this.currentIncomingSegmentedPayload.byteLength + segmentPayload.byteLength; if ( this.currentIncomingSegmentedMsgLength !== undefined && reassembledLength > this.currentIncomingSegmentedMsgLength ) { throw new BtpProtocolError( `BTP reassembled length ${reassembledLength} exceeds declared message length ${this.currentIncomingSegmentedMsgLength}`, ); } this.currentIncomingSegmentedPayload = Bytes.concat( this.currentIncomingSegmentedPayload, segmentPayload, ); } if (isEndingSegment) { if ( this.currentIncomingSegmentedMsgLength === undefined || this.currentIncomingSegmentedPayload === undefined ) { throw new BtpProtocolError("BTP beginning packet missing but ending packet received."); } if (this.currentIncomingSegmentedPayload.byteLength !== this.currentIncomingSegmentedMsgLength) { throw new BtpProtocolError( `BTP packet payload length does not match message length: ${this.currentIncomingSegmentedPayload.byteLength} !== ${this.currentIncomingSegmentedMsgLength}`, ); } const payloadToProcess = this.currentIncomingSegmentedPayload; this.currentIncomingSegmentedMsgLength = undefined; this.currentIncomingSegmentedPayload = undefined; // resetting current segment Payload to empty byte array // Hand over the resulting Matter message to ExchangeManager via the callback await this.handleMatterMessagePayload(payloadToProcess); } // A received ack may have reopened the remote window; flush held-back fragments (they piggyback the ack). await this.processSendQueue(); // If nothing was queued to piggyback on, ack proactively when our receive window is low. await this.sendImmediateAckIfWindowLow(); } catch (error) { logger.warn(`Error while handling incoming BTP data:`, error); await this.close(); // If no BTP protocol error, rethrow BtpProtocolError.accept(error); } } /** * Send a Matter message to the transport layer, but before that encode it into a BTP packet and potentially split * it into multiple segments. This Method is indirectly called by the ExchangeManager layer when a Matter message * should be sent. * * @param data ByteArray containing the Matter message */ public async sendMatterMessage(data: Bytes) { if (!this.isActive) { throw new BtpFlowError("BTP session is not active"); } logger.debug(`Got Matter message to send via BLE transport: ${Bytes.toHex(data)}`); if (data.byteLength === 0) { throw new BtpFlowError("BTP packet must not be empty"); } const dataReader = new DataReader(data, Endian.Little); this.#messagesPendingFirstAck?.push(data); this.queuedOutgoingMatterMessages.push(dataReader); await this.processSendQueue(); } private async processSendQueue() { if (this.sendInProgress || !this.isActive) return; if (this.queuedOutgoingMatterMessages.length === 0) return; this.sendInProgress = true; while (this.queuedOutgoingMatterMessages.length > 0) { //checks if last ack number sent < ack number to be sent const hasAckNumber = this.prevIncomingSequenceNumber !== this.prevAckedSequenceNumber; // §4.19.4.7: stop if the remote receive window is full, or if only the reserved last slot is free // and this data fragment would not carry an acknowledgement to fill it. if (!this.canSend(hasAckNumber)) { break; } if (hasAckNumber) { this.sendAckTimer.stop(); } const currentProcessedMessage = this.queuedOutgoingMatterMessages[0]; const remainingMessageLength = currentProcessedMessage.remainingBytesCount; logger.debug( "Sending BTP fragment: ", Diagnostic.dict({ fullMessageLength: currentProcessedMessage.length, remainingLengthInBytes: remainingMessageLength, }), ); const isBeginningSegment = remainingMessageLength === currentProcessedMessage.length; // Calculate Header Size - faster than encoding and checking length const btpHeaderLength = 2 + (isBeginningSegment ? 2 : 0) + (hasAckNumber ? 1 : 0); // 2(flags, sequenceNumber) + 2(beginning) + 1(ackNumber) const isEndingSegment = remainingMessageLength <= this.fragmentSize - btpHeaderLength; const packetHeader = { isHandshakeRequest: false, hasManagementOpcode: false, hasAckNumber, isBeginningSegment, isContinuingSegment: !isBeginningSegment, isEndingSegment, }; logger.debug( `Take up to ${ this.fragmentSize - btpHeaderLength } bytes from Rest of message: ${remainingMessageLength}`, ); const segmentPayload = currentProcessedMessage.readByteArray( Math.min(this.fragmentSize - btpHeaderLength, remainingMessageLength), ); const ackNumberToSend = hasAckNumber ? this.prevIncomingSequenceNumber : undefined; const btpPacket = { header: packetHeader, payload: { ackNumber: ackNumberToSend, sequenceNumber: this.getNextSequenceNumber(), messageLength: packetHeader.isBeginningSegment ? remainingMessageLength : undefined, // remainingMessageLength if the fill length on beginning packet segmentPayload, }, }; logger.debug(`Sending BTP packet: ${Diagnostic.json(btpPacket)}`); const packet = BtpCodec.encodeBtpPacket(btpPacket); logger.debug(`Sending BTP packet raw: ${Bytes.toHex(packet)}`); // Commit the ack before the await so a concurrent send can't observe the stale value and ack the same // sequence twice (spec-compliant peers reject a duplicate ack). if (ackNumberToSend !== undefined) { this.prevAckedSequenceNumber = ackNumberToSend; } try { await this.writeBleCallback(packet); } catch (error) { // Whether the packet reached the peer is unknown, and its sequence number is spent either way, so the // session cannot continue without the peer seeing a gap or a partial message this.queuedOutgoingMatterMessages.length = 0; this.sendInProgress = false; await this.#handleFailedWrite(error, `BTP packet (seq ${btpPacket.payload.sequenceNumber})`); return; } if (!this.isActive) { // A suspend during the write hands the transport to someone else; further segments of this session // would reach a peer that has already renegotiated this.queuedOutgoingMatterMessages.length = 0; this.sendInProgress = false; return; } if (!this.ackReceiveTimer.isRunning) { this.ackReceiveTimer.start(); // starts the timer } if (this.role === "central") { // Restart idle timer when sending unique data if (this.idleTimeout.isRunning) { this.idleTimeout.stop(); } this.idleTimeout.start(); } // Remove the message from the queue if it is the last segment if (isEndingSegment) { this.queuedOutgoingMatterMessages.shift(); } } this.sendInProgress = false; // A pending ack that could not be piggybacked (e.g. an incoming packet arrived mid-send) would otherwise // be stranded until the send-ack timer, since the timer is one-shot and may have already fired while a // send held the lock; flush it now that the send completed. await this.sendStandaloneAck(); } /** * Close the BTP session. This method is called when the BLE transport is disconnected and so the BTP session gets closed. */ public async close() { this.#stopTimers(); if (this.isActive) { logger.debug(`Closing BTP session`); this.isActive = false; try { await this.disconnectBleCallback(); } finally { // Session is logically closed regardless of transport-level cleanup failure. // Downstream consumers (e.g. PASE force-close on BLE loss) must observe this. this.#closed.emit(); } } } /** * Ends the session after a failed write and re-raises the error unless it is a disconnect. A write that fails after * the session already ended is only logged: that end was reported through {@link closed} or * {@link stalledAfterHandshake}, and after a stall the message belongs to the replay. */ async #handleFailedWrite(error: unknown, packetDescription: string) { if (!this.isActive) { logger.debug( `${packetDescription} failed after the BTP session ended`, Diagnostic.errorMessage(asError(error)), ); return; } try { await this.close(); } catch (closeError) { logger.debug(`Error closing the BTP session after a failed write`, closeError); } BleDisconnectedError.accept(error); logger.debug(`${packetDescription} send failed because BLE is disconnected`, Diagnostic.errorMessage(error)); } /** * End the session without touching the transport, so the same BLE connection can carry a renegotiated session. * Unlike {@link close} this emits neither {@link closed} nor a disconnect. */ suspend() { this.#stopTimers(); this.isActive = false; } #stopTimers() { this.sendAckTimer.stop(); this.ackReceiveTimer.stop(); this.idleTimeout.stop(); } /** * If this timer expires and the peer has a pending acknowledgement, the peer SHALL immediately send that * acknowledgement */ private async btpSendAckTimeoutTriggered() { if (!this.isActive) return; await this.sendStandaloneAck(); } /** §4.19.4.8: ack proactively once our receive window runs low; skipped if queued data will piggyback it. */ private async sendImmediateAckIfWindowLow() { if (this.queuedOutgoingMatterMessages.length > 0 || this.sendInProgress) return; if (this.localWindowFreeSlots() > MatterBle.BTP_IMMEDIATE_ACK_WINDOW_THRESHOLD) return; await this.sendStandaloneAck(); } /** Send a stand-alone acknowledgement packet if one is pending. */ private async sendStandaloneAck() { // Mutually exclusive with processSendQueue (both directions): if a send is in progress it will piggyback // the pending ack, and two concurrent writes could otherwise reach the wire out of order. if (this.sendInProgress || !this.isActive) return; const ackNumberToSend = this.prevIncomingSequenceNumber; if (ackNumberToSend === this.prevAckedSequenceNumber) return; // §4.19.4.7: an ack still consumes a remote-window slot, so never send into a full window. if (!this.canSend(true)) return; this.sendInProgress = true; try { logger.debug(`Sending BTP ACK for sequence number ${ackNumberToSend}`); const btpPacket = { header: { isHandshakeRequest: false, hasManagementOpcode: false, hasAckNumber: true, isBeginningSegment: false, isContinuingSegment: false, isEndingSegment: false, }, payload: { ackNumber: ackNumberToSend, sequenceNumber: this.getNextSequenceNumber(), }, }; const packet = BtpCodec.encodeBtpPacket(btpPacket); // Commit the ack before the await so an interleaved send can't re-ack the same sequence // (spec-compliant peers reject a duplicate ack). this.prevAckedSequenceNumber = ackNumberToSend; try { await this.writeBleCallback(packet); } catch (error) { await this.#handleFailedWrite( error, `BTP ACK (seq ${btpPacket.payload.sequenceNumber}, ack ${ackNumberToSend})`, ); return; } this.sendAckTimer.stop(); if (this.isActive && !this.ackReceiveTimer.isRunning) { this.ackReceiveTimer.start(); // starts the timer } } finally { this.sendInProgress = false; } // Flush any Matter message that was queued while the ack held the send lock. await this.processSendQueue(); } /** * If a peer’s acknowledgement-received timer expires, or if a peer receives an invalid acknowledgement, * the peer SHALL close the BTP session and report an error to the application. * * A stall reported through {@link stalledAfterHandshake} suspends the session instead, leaving the transport to * its observer. */ private async btpAckTimeoutTriggered() { if (!this.isActive || this.prevIncomingAckNumber === this.sequenceNumber) { return; } const messagesToReplay = this.#messagesToReplayOnStall(); if (messagesToReplay !== undefined) { logger.debug( `No BTP packet received since the handshake with a segment size of ${this.fragmentSize} bytes, reporting a stall`, ); this.#messagesPendingFirstAck = undefined; this.suspend(); this.#stalledAfterHandshake.emit(messagesToReplay); return; } logger.warn("Acknowledgement for the sent sequence number was not received ... disconnect"); await this.close(); } /** * The messages to replay if we sent Matter data and the peer has since sent nothing at all, someone observes * {@link stalledAfterHandshake}, and a smaller segment size is still possible; undefined otherwise. */ #messagesToReplayOnStall() { const pending = this.#messagesPendingFirstAck; if (pending === undefined || pending.length === 0 || !this.#stalledAfterHandshake.isObserved) { return; } if (this.role !== "central" || this.fragmentSize <= MatterBle.MINIMUM_ATT_MTU) { return; } return pending; } /** * Increments sequence number for the packets and round it off to 0 when it reaches the maximum limit. */ getNextSequenceNumber() { this.sequenceNumber++; if (this.sequenceNumber > MAXIMUM_SEQUENCE_NUMBER) { this.sequenceNumber = 0; } return this.sequenceNumber; } /** Wrap-safe forward distance between two sequence numbers (modulo 256); the -1 sentinels read as 255. */ private modularDistance(from: number, to: number): number { return (((to - from) % 256) + 256) % 256; } /** Free slots in the remote peer's receive window; gates our sending (§4.19.4.7). */ private remoteWindowFreeSlots(): number { return this.clientWindowSize - this.modularDistance(this.prevIncomingAckNumber, this.sequenceNumber); } /** Free slots in our own receive window; drives proactive acknowledgement (§4.19.4.8). */ private localWindowFreeSlots(): number { return ( this.clientWindowSize - this.modularDistance(this.prevAckedSequenceNumber, this.prevIncomingSequenceNumber) ); } /** §4.19.4.7: a data-only packet must leave the last window slot free; an ack-bearing packet may use it. */ private canSend(carriesAck: boolean): boolean { const free = this.remoteWindowFreeSlots(); if (free <= 0) return false; if (free <= MatterBle.BTP_WINDOW_NO_ACK_SEND_THRESHOLD && !carriesAck) return false; return true; } }