Documentation
¶
Overview ¶
Package ble is the commissioner's seam to Bluetooth LE (ADR 0024, decision 2): the interfaces a platform BLE stack implements (Central, Connection), the scanner that turns Matter advertisements into commissionable devices (Scanner) and the commissioning channel that runs PASE over a BTP session to one peripheral (Dial, Channel). It carries no dependency and opens no radio: the BlueZ implementation is the separate module github.com/SukramJ/go-fabric/ble/bluez (ADR 0024, decision 3), an in-memory one is in ble/bletest.
A port of matter.js at 0ceb202d: the scanner of packages/protocol/src/common/BleScanner.ts (records, deduplication by service data, aging, discoveries by identifier) over the advertisement codec of packages/protocol/src/codec/BtpCodec.ts, and the central's channel of packages/nodejs-ble/src/NobleBleChannel.ts (the BTP handshake over C1 and C2, the session's writes on C1, C2 data into the session, the disconnect by unsubscribing C2). The channel's renegotiation at the minimum segment size after a stall follows NobleBleChannel.ts at 862ad75f (BD-Matter-BTP-RenegotiationAfterStall).
A BTP session is reliable, so the channel's exchange manager runs no MRP (exchange.Config.Reliable; matter.js Ble.ts:38, Session.ts:355-356).
Index ¶
- Constants
- Variables
- func Transport(s *Scanner) discovery.Transport
- type Central
- type Channel
- func (c *Channel) Close() error
- func (c *Channel) Closed() <-chan struct{}
- func (c *Channel) ClosedCause() error
- func (c *Channel) Conn() *btp.Conn
- func (c *Channel) Exchanges() *exchange.Manager
- func (c *Channel) PeerAddress() *net.UDPAddr
- func (c *Channel) Peripheral() Peripheral
- func (c *Channel) PeripheralAddress() string
- func (c *Channel) Send(_ *net.UDPAddr, payload []byte) error
- type CommissionedIdentity
- type Connection
- type Device
- type DialOptions
- type ListeningClock
- type ListeningMeter
- type MTUExchange
- type Peripheral
- type Reachability
- type Scanner
- func (s *Scanner) Cancel(id discovery.Identifier)
- func (s *Scanner) Close(ctx context.Context) error
- func (s *Scanner) Device(address string) (Device, error)
- func (s *Scanner) Discovered(id discovery.Identifier) []Device
- func (s *Scanner) Find(ctx context.Context, id discovery.Identifier, timeout time.Duration, ...) ([]Device, error)
- func (s *Scanner) FindContinuously(ctx context.Context, id discovery.Identifier, callback func(Device), ...) ([]Device, error)
- func (s *Scanner) ForgetCommissioned(peripheralAddresses []string, identity *CommissionedIdentity)
- type ScannerOptions
Constants ¶
const ( // StaleEntryAge is the silence after which a record is dropped once // its service data arrives from another address, and after which it // is no candidate when the client reports listening time. StaleEntryAge = 60 * time.Second // RecordMaxAge is the age after which a record is forgotten // (§5.4.2.3: the longest a device announces at the rapid interval). RecordMaxAge = 15 * time.Minute // DefaultDiscoveryTimeout is [Scanner.Find]'s timeout when none is given. DefaultDiscoveryTimeout = 10 * time.Second // ScanTransitionTimeout is how long a client's StartScanning or // StopScanning may take before it counts as failed with // [ErrScanTransitionTimeout]: a radio that powers off may never settle // the call. Mirrors matter.js // packages/protocol/src/common/BleScanner.ts:110-114 // (SCAN_TRANSITION_TIMEOUT). ScanTransitionTimeout = 10 * time.Second )
Timing of the scanner. Mirrors matter.js packages/protocol/src/common/BleScanner.ts:92-115 (STALE_ENTRY_AGE, RECORD_MAX_AGE) and the default discovery timeout of findCommissionableDevices (:543-546) at db021da0.
const ATTMTUSettleTimeout = 2 * time.Second
ATTMTUSettleTimeout is how long Dial waits for a pending ATT_MTU exchange before it sizes the BTP segment without it — matter.js ATT_MTU_SETTLE_TIMEOUT (packages/nodejs-ble/src/NobleBleChannel.ts:40-41 at b25ed960).
const DisconnectTimeout = 5 * time.Second
DisconnectTimeout bounds each C2 unsubscribe: a GATT stack can leave the operation pending when the peripheral vanished without a disconnect event — matter.js BLE_DISCONNECT_TIMEOUT (packages/nodejs-ble/src/NobleBleChannel.ts:38 at db021da0) and its unsubscribeC2 (:573-588), which runs the unsubscribe under it (:579).
Variables ¶
var ErrChannelClosed = fmt.Errorf("ble: commissioning channel closed: %w", btp.ErrDisconnected)
ErrChannelClosed is the cause a PASE session over a lost channel is closed with — matter.js BleChannelClosedError (packages/protocol/src/ble/Ble.ts:17-22). It wraps btp.ErrDisconnected, so the commissioning flow reads it as a channel drop. Channel.Send returns it for a message the channel can no longer carry.
var ErrHandshakeTimeout = errors.New("ble: BTP handshake response not received")
ErrHandshakeTimeout is a peripheral that sent no BTP handshake response within btp.ConnRspTimeout — matter.js's BleError("Handshake Response not received", packages/nodejs-ble/src/NobleBleChannel.ts:643-652).
var ErrNoDevice = errors.New("ble: no device")
ErrNoDevice is Scanner.Device without a usable record — matter.js's BleError of getDiscoveredDevice (common/BleScanner.ts:145-154).
var ErrScanTransitionTimeout = errors.New("ble: scan transition timed out")
ErrScanTransitionTimeout is a client's scan start or stop that did not settle within ScanTransitionTimeout — matter.js's PromiseTimeoutError of withTimeout (common/BleScanner.ts:186-188, :662).
Functions ¶
func Transport ¶
Transport is the scanner s as a discovery transport — matter.js's BleScanner in the node's ScannerSet (its ChannelType.BLE, packages/protocol/src/common/BleScanner.ts at 862ad75f). Each device it reports is Device.Commissionable: its InstanceID is the peripheral's address, which Scanner.Device looks the peripheral up by.
Types ¶
type Central ¶
type Central interface {
// SetDiscoveryCallback installs the receiver of every advertisement
// of the Matter service: the peripheral and the service data of the
// Matter service UUID (btp.ServiceUUID).
SetDiscoveryCallback(func(p Peripheral, serviceData []byte))
// StartScanning starts the scan. It is asked again while a scan runs,
// so a radio that stopped on its own resumes (common/BleScanner.ts:186-189).
StartScanning(ctx context.Context) error
// StopScanning stops the scan.
StopScanning(ctx context.Context) error
// Connect opens a GATT connection to the peripheral and resolves the
// Matter service's C1, C2 and C3 characteristics.
Connect(ctx context.Context, p Peripheral) (Connection, error)
}
Central is what a platform BLE stack offers the commissioner: the scan of Matter advertisements — matter.js BleScannerClient (common/BleScanner.ts:41-64) — and the GATT connection to one peripheral. Implementations: the BlueZ module (phase 13) and ble/bletest.
type Channel ¶
type Channel struct {
// contains filtered or unexported fields
}
Channel is a BTP session to one peripheral as a commissioning channel: the exchange manager whose one carrier is the session, reliable, so no MRP runs — matter.js NobleBleChannel (packages/nodejs-ble/src/NobleBleChannel.ts:670-1022 at b25ed960) under the ExchangeManager it feeds. It satisfies commissioner.Channel.
The session behind the channel is replaceable: a peripheral that completes the handshake and then answers no BTP packet before the acknowledgement timeout is given a fresh session at the minimum segment size, once, with the unacknowledged messages replayed — matter.js's renegotiation (NobleBleChannel.ts:864-918 at b25ed960), an interop workaround its session documents as having no basis in the specification (packages/protocol/src/ble/BtpSessionHandler.ts:67-84 at b25ed960). Every Channel.Send waits for a renegotiation in flight; a renegotiation that fails closes the channel. See BD-Matter-BTP-RenegotiationAfterStall.
func Dial ¶
func Dial(ctx context.Context, central Central, p Peripheral, opts DialOptions) (*Channel, error)
Dial opens the commissioning channel to p — matter.js NobleBleChannel.create (NobleBleChannel.ts:671-715) and performBtpHandshake (:593-668): the GATT connection, the segment size from the ATT_MTU (a pending exchange awaited for ATTMTUSettleTimeout when the connection reports one, the minimum while it stays unknown), the handshake request (versions, segment size, the maximum window) written on C1, C2 subscribed, the handshake response awaited for btp.ConnRspTimeout, then the central's BTP session on C1 and C2. A lost GATT connection closes the session and the channel.
func (*Channel) Close ¶
Close closes the exchange manager and the BTP session, which unsubscribes C2 and disconnects — matter.js close (NobleBleChannel.ts:1004-1021 at b25ed960). A renegotiation in flight is abandoned, its parked sends released, the C2 handler detached so data that still arrives is dropped (:1010 #detachDataHandler), and the connection a suspended session no longer owns is dropped here.
func (*Channel) Closed ¶
func (c *Channel) Closed() <-chan struct{}
Closed is closed when the channel is gone.
func (*Channel) ClosedCause ¶
ClosedCause is the error a session over the lost channel ends with.
func (*Channel) Conn ¶
Conn is the current BTP session as a transport.Conn; a renegotiation replaces it, so send through Channel.Send, which waits for one.
func (*Channel) PeerAddress ¶
PeerAddress is the address the manager names the peripheral by.
func (*Channel) Peripheral ¶
func (c *Channel) Peripheral() Peripheral
Peripheral is the peripheral the channel runs to.
func (*Channel) PeripheralAddress ¶ added in v0.13.0
PeripheralAddress is the peripheral's address — the BLE address the commissioner hands the scanners once the device is commissioned (commissioner.CommissionedScanner).
func (*Channel) Send ¶
Send is the exchange manager's carrier: one Matter message on the BTP session; dst is the channel's own address. It waits for a renegotiation in flight — the replay goes first — as matter.js's send awaits it before it takes the session: "A renegotiation replaces the session, so sending into the outgoing one would be rejected as inactive" (NobleBleChannel.ts:944-953 at b25ed960). It returns ErrChannelClosed when the channel is lost meanwhile, the error matter.js's test asserts for a send parked on a failed renegotiation: "BtpFlowError from the suspended session would not read as channel loss downstream" (packages/nodejs-ble/test/NobleBleChannelTest.ts:772 at b25ed960).
type CommissionedIdentity ¶ added in v0.7.3
type CommissionedIdentity = discovery.CommissionedIdentity
CommissionedIdentity identifies a commissioned device independently of the transport that discovered it: discovery.CommissionedIdentity, the commissioner's (commissioner.CommissionedScanner).
type Connection ¶
type Connection interface {
// ATTMTU is the negotiated ATT_MTU; 0 when still unknown, which
// selects the minimum BTP segment size (NobleBleChannel.ts:679-681).
ATTMTU() int
// WriteC1 writes C1 (a write with response). A write that fails
// because the peripheral is gone returns an error wrapping
// btp.ErrDisconnected (NobleBleChannel.ts:770-781). It must not
// deliver C2 data on the calling goroutine.
WriteC1(ctx context.Context, data []byte) error
// SubscribeC2 subscribes to C2's indications; on receives each one,
// in order, on a goroutine of the implementation's.
SubscribeC2(ctx context.Context, on func(data []byte)) error
// UnsubscribeC2 ends the subscription, which is how a GATT client
// closes a BTP session (§4.19.4.10, NobleBleChannel.ts:571-574).
UnsubscribeC2(ctx context.Context) error
// ReadC3 reads the additional commissioning data; an error when the
// peripheral has none.
ReadC3(ctx context.Context) ([]byte, error)
// Disconnect drops the GATT connection.
Disconnect() error
// Disconnected is closed when the connection is gone, from either side.
Disconnected() <-chan struct{}
}
Connection is a GATT connection to one peripheral's Matter service.
type Device ¶
type Device struct {
// Peripheral is the advertising peripheral; its address is the
// device identifier.
Peripheral Peripheral
// Discriminator is the 16-bit discriminator field, unmasked as
// matter.js reads it (D).
Discriminator uint16
// VendorID and ProductID are the advertisement's (VP), 0 in an
// extended announcement.
VendorID, ProductID uint16
// HasAdditionalAdvertisementData is the flag of C3 data.
HasAdditionalAdvertisementData bool
}
Device is a commissionable device a BLE advertisement describes — matter.js CommissionableDeviceData with its DiscoveredBleDevice (common/BleScanner.ts:66-75, built at :388-399).
func (Device) Commissionable ¶
Commissionable is the device as discovery describes one: the peripheral's address as instance id, D, VP, CM 1 (:391-397).
func (Device) ShortDiscriminator ¶
ShortDiscriminator is the discriminator's upper four bits (SD, :394).
type DialOptions ¶
type DialOptions struct {
// Clock paces the BTP timers, the handshake timeout and the channel's
// exchanges.
Clock exchange.Clock
// Logger receives the channel's diagnostics.
Logger *slog.Logger
// LocalParameters are our session parameters in PASE.
LocalParameters *sessionparams.Parameters
}
DialOptions configure Dial; the zero value is the system clock, no log, the default session parameters and the segment size the ATT_MTU gives.
type ListeningClock ¶
type ListeningClock interface {
// ListeningTime is the total time listened so far.
ListeningTime() time.Duration
}
ListeningClock is a Central that reports how long it listened: its radio scanned and it reported every advertisement it received (common/BleScanner.ts:54-63). A record states that its device went silent only when its age is measured in this time.
type ListeningMeter ¶ added in v0.7.3
type ListeningMeter struct {
// contains filtered or unexported fields
}
ListeningMeter accumulates the time a Central's radio scanned, which the central reports as ListeningClock.ListeningTime — matter.js BleListeningClock (packages/protocol/src/common/BleListeningClock.ts:9-37). A central calls Start when its radio reports that it scans and Stop when the radio stopped or can no longer scan. It is safe for concurrent use; the zero value is not usable, use NewListeningMeter.
func NewListeningMeter ¶ added in v0.7.3
func NewListeningMeter(clk exchange.Clock) *ListeningMeter
NewListeningMeter returns a meter on clk; nil is the system clock.
func (*ListeningMeter) Start ¶ added in v0.7.3
func (m *ListeningMeter) Start()
Start records that the radio scans; a repeated Start while it scans keeps the first start (BleListeningClock.ts:16-19).
func (*ListeningMeter) Stop ¶ added in v0.7.3
func (m *ListeningMeter) Stop()
Stop records that the radio stopped scanning; a Stop without a running scan changes nothing (BleListeningClock.ts:21-28).
func (*ListeningMeter) Total ¶ added in v0.7.3
func (m *ListeningMeter) Total() time.Duration
Total is the scan time so far, a scan still running included (BleListeningClock.ts:30-36).
type MTUExchange ¶
type MTUExchange interface {
ATTMTUExchanged() <-chan struct{}
}
MTUExchange is a Connection whose platform reports the ATT_MTU exchange after the connection opens — noble leaves the MTU unknown until its "mtu" event (matter.js NobleBleChannel.ts:520-526 at b25ed960). ATTMTUExchanged is closed once the exchange landed and Connection.ATTMTU reports it; Dial waits for it up to ATTMTUSettleTimeout instead of sizing the BTP segment at the minimum. A Connection without it that reports 0 gets the minimum at once.
type Peripheral ¶
type Peripheral struct {
// Address is the platform's address of the peripheral (a MAC address
// under BlueZ).
Address string
}
Peripheral is a BLE peripheral as the platform names it — matter.js BlePeripheral (packages/protocol/src/common/BleScanner.ts:37-39).
type Reachability ¶
Reachability is a Central that can lose access to a peripheral it reported, such as one routing through proxies (common/BleScanner.ts:46-52). A Central without it keeps every discovered peripheral available.
type Scanner ¶
type Scanner struct {
// contains filtered or unexported fields
}
Scanner finds commissionable devices by their BLE advertisements — matter.js BleScanner (packages/protocol/src/common/BleScanner.ts:124-674) at b25ed960. One radio serves every discovery: the scan starts with the first and stops with the last. It is safe for concurrent use.
func NewScanner ¶
func NewScanner(client Central, opts ScannerOptions) *Scanner
NewScanner returns a scanner over client and installs its discovery callback.
func (*Scanner) Cancel ¶
func (s *Scanner) Cancel(id discovery.Identifier)
Cancel ends every discovery waiting for the identifier (cancelCommissionableDeviceDiscovery, :374-382).
func (*Scanner) Close ¶
Close stops the scan and ends every discovery (close, :654-673): the stop queues behind a transition still running and fails with ErrScanTransitionTimeout when it does not settle in time.
func (*Scanner) Device ¶
Device is the stored record of a peripheral — getDiscoveredDevice (common/BleScanner.ts:145-154): an error when there is none or the client cannot reach the peripheral now.
func (*Scanner) Discovered ¶
func (s *Scanner) Discovered(id discovery.Identifier) []Device
Discovered is getDiscoveredCommissionableDevices (:652-654): the stored devices the identifier selects, newest first.
func (*Scanner) Find ¶
func (s *Scanner) Find(ctx context.Context, id discovery.Identifier, timeout time.Duration, ignoreExisting bool) ([]Device, error)
Find is findCommissionableDevices (:543-575): the stored devices the identifier selects, else a scan until the first advertisement that selects one or timeout (0 is DefaultDiscoveryTimeout). ignoreExisting forgets the matching records first, for a fresh result. An identifier BLE cannot select by returns none.
func (*Scanner) FindContinuously ¶
func (s *Scanner) FindContinuously(ctx context.Context, id discovery.Identifier, callback func(Device), timeout time.Duration) ([]Device, error)
FindContinuously is findCommissionableDevicesContinuously (:576-644): callback receives every device the identifier selects, once per peripheral (address) for the discovery — as matter.js, which reports each deviceIdentifier once (:617-621), the address (:392) — until timeout (0: none), ctx ends, Scanner.Cancel or Scanner.Close; it returns the devices then stored. The peripherals already reported are bounded as the records are: past [maxScannerRecords] of them, those whose record the scanner forgot are dropped, and such a peripheral advertising again is reported again — also when it advertised again before the drop: the record's epoch tells it from the one reported (review II, R2-P6-bound-2029).
func (*Scanner) ForgetCommissioned ¶ added in v0.7.3
func (s *Scanner) ForgetCommissioned(peripheralAddresses []string, identity *CommissionedIdentity)
ForgetCommissioned forgets the records of a device that was commissioned: its advertisement described a commissioning window that is now closed. peripheralAddresses are the BLE addresses it was reached at (a device commissioned over another transport has none); with an identity, every record of its discriminator and vendor (and product, when the identity names one) is forgotten too. A device that advertises again is discovered again. Mirrors matter.js packages/protocol/src/common/BleScanner.ts:298-320 (forgetCommissionedDevice) and :116-122 (matchesVendorProduct).
Directories
¶
| Path | Synopsis |
|---|---|
|
Package bletest is an in-memory BLE stack for tests: a Central that implements ble.Central and the [Peripheral]s it reaches, each a GATT server of the Matter service whose BTP side is a transport/btp peripheral session.
|
Package bletest is an in-memory BLE stack for tests: a Central that implements ble.Central and the [Peripheral]s it reaches, each a GATT server of the Matter service whose BTP side is a transport/btp peripheral session. |