matter_kit/transport/ble.rs
1//! What a BLE stack needs to carry Matter: the GATT service, and the advertisement a
2//! commissioner scans for (Core §4.19.4.2, §5.4.2.5).
3//!
4//! [`btp`](super::btp) is the protocol; this is its surface against the radio. Everything
5//! here is data — identifiers and payload formats — because the API that drives a BLE
6//! controller is where every platform differs, and a trait covering `nrf-softdevice`,
7//! `esp32-nimble`, BlueZ and CoreBluetooth alike would fit none of them well.
8//!
9//! # The commissioner has to find the device without asking
10//!
11//! §5.4.2.5.6 explains why everything is in the advertisement rather than the scan response:
12//!
13//! > In order to reduce 2.4 GHz spectrum congestion due to active BLE scanning, and to extend
14//! > battery life in battery-powered devices, all critical data used for device discovery is
15//! > contained in the Advertising Data rather than the Scan Response Data.
16//!
17//! So a commissioner scanning passively already has the discriminator it needs to match a
18//! device against a Setup Code, and never transmits at all.
19
20use crate::bytes::Cursor;
21use crate::commissioning::OnboardingPayload;
22use crate::error::{ErrorCode, Result, bail};
23use crate::msg::VendorId;
24
25/// `0xFFF6` — `MATTER_BLE_SERVICE_UUID`, the 16-bit UUID the Bluetooth SIG assigned to Matter
26/// (Core Table 36).
27pub const SERVICE_UUID: u16 = 0xFFF6;
28
29/// C1, the Client TX Buffer: `18EE2EF5-263D-4559-959F-4F9C429F9D11`, write-only.
30///
31/// "The client SHALL exclusively use C1 to initiate BTP sessions by sending BTP handshake
32/// requests and send data to the server via GATT ATT_WRITE_REQ PDUs" (§4.19.4.2).
33///
34/// Written most-significant octet first, the order a UUID is printed in. A BLE stack that
35/// wants the little-endian wire order reverses it.
36pub const C1_UUID: [u8; 16] = [
37 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, 0x9D, 0x11,
38];
39
40/// C2, the Client RX Buffer: `18EE2EF5-263D-4559-959F-4F9C429F9D12`, indications only.
41///
42/// "While a client is subscribed to allow indications over C2, the server SHALL exclusively
43/// use C2 to respond to BTP handshake requests and send data to the client via GATT
44/// ATT_HANDLE_VALUE_IND PDUs" (§4.19.4.2). Unsubscribing from it is also how a client closes
45/// a BTP session (§4.19.4.10).
46pub const C2_UUID: [u8; 16] = [
47 0x18, 0xEE, 0x2E, 0xF5, 0x26, 0x3D, 0x45, 0x59, 0x95, 0x9F, 0x4F, 0x9C, 0x42, 0x9F, 0x9D, 0x12,
48];
49
50/// C3, the optional additional commissioning data: `64630238-8772-45F2-B87D-748A83218F04`,
51/// read-only, up to 512 octets (§4.19.4.2, §5.4.2.5.7).
52pub const C3_UUID: [u8; 16] = [
53 0x64, 0x63, 0x02, 0x38, 0x87, 0x72, 0x45, 0xF2, 0xB8, 0x7D, 0x74, 0x8A, 0x83, 0x21, 0x8F, 0x04,
54];
55
56/// The maximum length of C1 and C2, "imposed to align with maximum PDU size when LE Data
57/// Packet Length Extensions (DPLE) is enabled on Bluetooth 4.2 hardware" (§4.19.4.2).
58pub const CHARACTERISTIC_MAX: usize = 244;
59
60/// `AD Type` 0x01 — Flags.
61pub const AD_TYPE_FLAGS: u8 = 0x01;
62/// `AD Type` 0x16 — Service Data, 16-bit UUID (Bluetooth CSS 12 §1.11).
63pub const AD_TYPE_SERVICE_DATA: u8 = 0x16;
64
65/// The GAP flags a commissionable device advertises: General Discoverable, BR/EDR not
66/// supported (§5.4.2.5.4 — "Commissionable devices SHALL use the GAP General Discoverable
67/// mode, sending connectable undirected advertising events").
68pub const FLAGS_COMMISSIONABLE: u8 = 0x06;
69
70/// The GAP flags a device in Network Recovery advertises: Limited Discoverable, BR/EDR not
71/// supported (Core Table 75).
72pub const FLAGS_RECOVERY: u8 = 0x05;
73
74/// §5.4.2.5.6's Matter BLE Device OpCodes (Core Table 71).
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
76#[repr(u8)]
77pub enum OpCode {
78 /// The device is advertising to be commissioned.
79 Commissionable = 0x00,
80 /// The device has lost its operational network and is advertising for recovery
81 /// (§11.10.6.11's `RecoveryIdentifier`).
82 NetworkRecovery = 0x01,
83}
84
85/// What a Matter BLE advertisement says (§5.4.2.5.6).
86///
87/// All multi-byte values are little-endian "within the service data payload", which is the
88/// opposite of the UUID order two octets earlier in the same advertisement.
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub enum Advertisement {
91 /// Core Table 72 — a device waiting to be commissioned.
92 Commissionable {
93 /// §5.4.2.4.1's 12-bit discriminator, the value a Setup Code selects a device by.
94 discriminator: u16,
95 /// The Vendor ID, or [`VendorId`]`(0)` when elided.
96 vendor_id: VendorId,
97 /// The Product ID, or 0 when elided.
98 product_id: u16,
99 /// Whether C3 carries §5.4.2.5.7's GATT-based Additional Data.
100 additional_data: bool,
101 /// Whether the device is in its §5.4.2.3.3 Extended Announcement period. "SHALL NOT
102 /// be set during the initial Announcement Duration."
103 extended_announcement: bool,
104 },
105 /// Core Table 74 — a device that has lost its network.
106 NetworkRecovery {
107 /// §11.10.6.11's 64-bit `RecoveryIdentifier`.
108 recovery_id: u64,
109 /// Whether C3 carries additional data.
110 additional_data: bool,
111 },
112}
113
114impl Advertisement {
115 /// The longest service data payload either form produces.
116 pub const SERVICE_DATA_MAX: usize = 11;
117
118 /// The longest complete advertising payload [`Advertisement::encode`] produces: the Flags
119 /// structure, the Service Data header, and the payload.
120 pub const MAX: usize = 3 + 4 + Self::SERVICE_DATA_MAX;
121
122 /// The advertisement for a device whose label carries `payload`.
123 ///
124 /// The QR code and the BLE advertisement have to agree: a commissioner scans for the
125 /// discriminator it read off the label, and a device advertising a different one is
126 /// simply never found. Deriving one from the other is how they stay in step.
127 #[must_use]
128 pub const fn for_onboarding(payload: &OnboardingPayload) -> Self {
129 Self::Commissionable {
130 discriminator: payload.discriminator,
131 vendor_id: payload.vendor_id,
132 product_id: payload.product_id,
133 additional_data: false,
134 extended_announcement: false,
135 }
136 }
137
138 /// Drops the vendor and product from a commissionable advertisement.
139 ///
140 /// §5.4.2.5.6: "Devices MAY choose not to advertise either the VID and PID … due to
141 /// privacy or other considerations." Both go or neither does — a product without a
142 /// vendor is forbidden, and [`Advertisement::encode`] refuses it.
143 #[must_use]
144 pub const fn elide_identity(self) -> Self {
145 match self {
146 Self::Commissionable {
147 discriminator,
148 additional_data,
149 extended_announcement,
150 ..
151 } => Self::Commissionable {
152 discriminator,
153 vendor_id: VendorId(0),
154 product_id: 0,
155 additional_data,
156 extended_announcement,
157 },
158 other => other,
159 }
160 }
161
162 /// Marks C3 as carrying §5.4.2.5.7's GATT-based Additional Data.
163 #[must_use]
164 pub const fn with_additional_data(self, present: bool) -> Self {
165 match self {
166 Self::Commissionable {
167 discriminator,
168 vendor_id,
169 product_id,
170 extended_announcement,
171 ..
172 } => Self::Commissionable {
173 discriminator,
174 vendor_id,
175 product_id,
176 additional_data: present,
177 extended_announcement,
178 },
179 Self::NetworkRecovery { recovery_id, .. } => Self::NetworkRecovery {
180 recovery_id,
181 additional_data: present,
182 },
183 }
184 }
185
186 /// Marks the device as being in its §5.4.2.3.3 Extended Announcement period.
187 ///
188 /// "SHALL be set while the device is in the Extended Announcement period and SHALL NOT be
189 /// set during the initial Announcement Duration" — a commissioner reads it as "this
190 /// device has been waiting a while", and a device that leaves it set from boot says
191 /// something untrue about itself.
192 #[must_use]
193 pub const fn with_extended_announcement(self, extended: bool) -> Self {
194 match self {
195 Self::Commissionable {
196 discriminator,
197 vendor_id,
198 product_id,
199 additional_data,
200 ..
201 } => Self::Commissionable {
202 discriminator,
203 vendor_id,
204 product_id,
205 additional_data,
206 extended_announcement: extended,
207 },
208 other => other,
209 }
210 }
211
212 /// The OpCode this form carries.
213 #[must_use]
214 pub const fn opcode(&self) -> OpCode {
215 match self {
216 Self::Commissionable { .. } => OpCode::Commissionable,
217 Self::NetworkRecovery { .. } => OpCode::NetworkRecovery,
218 }
219 }
220
221 /// Writes just the service data payload — the part after the `0xFFF6` UUID.
222 ///
223 /// Useful where the BLE stack assembles the AD structures itself, which most of them do.
224 pub fn encode_service_data(&self, out: &mut [u8]) -> Result<usize> {
225 match *self {
226 Self::Commissionable {
227 discriminator,
228 vendor_id,
229 product_id,
230 additional_data,
231 extended_announcement,
232 } => {
233 if discriminator > 0x0FFF {
234 // "Bits[15:12] == 0x0 (Advertisement version)" leaves twelve for the
235 // discriminator, and a wider value would silently become a version.
236 bail!(InvalidArgument)
237 }
238 if vendor_id.0 == 0 && product_id != 0 {
239 // "A device SHALL NOT set the VID to 0 when providing a non-zero PID."
240 bail!(InvalidArgument)
241 }
242 let mut w = Cursor::writer(out);
243 w.u8(OpCode::Commissionable as u8)?;
244 // The advertisement version occupies bits[15:12] and is zero, so the
245 // discriminator goes out as-is.
246 w.u16(discriminator)?;
247 w.u16(vendor_id.0)?;
248 w.u16(product_id)?;
249 w.u8(u8::from(additional_data) | (u8::from(extended_announcement) << 1))?;
250 Ok(w.position())
251 }
252 Self::NetworkRecovery {
253 recovery_id,
254 additional_data,
255 } => {
256 let mut w = Cursor::writer(out);
257 w.u8(OpCode::NetworkRecovery as u8)?;
258 w.u8(0)?; // Advertisement version and reserved, both zero.
259 w.u64(recovery_id)?;
260 w.u8(u8::from(additional_data))?;
261 Ok(w.position())
262 }
263 }
264 }
265
266 /// Writes the complete advertising payload: the Flags AD structure followed by the
267 /// Service Data one, as Core Tables 73 and 75 lay them out.
268 ///
269 /// A conformant advertisement may order its AD structures differently — "there are no
270 /// ordering constraints for advertisement fields in the Length-Type-Value format used in
271 /// BLE advertisements" — but this order is the one the specification's own examples use.
272 pub fn encode(&self, out: &mut [u8]) -> Result<usize> {
273 let flags = match self {
274 Self::Commissionable { .. } => FLAGS_COMMISSIONABLE,
275 Self::NetworkRecovery { .. } => FLAGS_RECOVERY,
276 };
277 // The service data goes into a scratch buffer first, because AD[1]'s length octet
278 // comes before the payload it measures.
279 let mut payload = [0u8; Self::SERVICE_DATA_MAX];
280 let n = self.encode_service_data(&mut payload)?;
281 let (Some(body), Ok(length)) = (payload.get(..n), u8::try_from(n.saturating_add(3))) else {
282 // The type octet, the two UUID octets, and the payload.
283 bail!(BufferTooSmall)
284 };
285
286 let mut w = Cursor::writer(out);
287 w.u8(2)?; // AD[0] length: the type octet plus the flags octet.
288 w.u8(AD_TYPE_FLAGS)?;
289 w.u8(flags)?;
290 w.u8(length)?;
291 w.u8(AD_TYPE_SERVICE_DATA)?;
292 w.u16(SERVICE_UUID)?;
293 w.put(body)?;
294 Ok(w.position())
295 }
296
297 /// Reads a service data payload — the octets a scanner finds under UUID `0xFFF6`.
298 ///
299 /// This is a commissioner's half of the protocol: it turns a passive scan result into
300 /// something that can be matched against a Setup Code's discriminator.
301 pub fn decode_service_data(buf: &[u8]) -> Result<Self> {
302 let mut r = Cursor::reader(buf, ErrorCode::BtpMalformed);
303 match r.read_u8()? {
304 0x00 => {
305 let versioned = r.read_u16()?;
306 if versioned >> 12 != 0 {
307 // An advertisement version this crate does not know: its remaining fields
308 // may mean something else entirely.
309 bail!(UnsupportedVersion)
310 }
311 let vendor_id = VendorId(r.read_u16()?);
312 let product_id = r.read_u16()?;
313 let flags = r.read_u8()?;
314 Ok(Self::Commissionable {
315 discriminator: versioned & 0x0FFF,
316 vendor_id,
317 product_id,
318 additional_data: flags & 0x01 != 0,
319 extended_announcement: flags & 0x02 != 0,
320 })
321 }
322 0x01 => {
323 if r.read_u8()? >> 4 != 0 {
324 bail!(UnsupportedVersion)
325 }
326 let recovery_id = r.read_u64()?;
327 Ok(Self::NetworkRecovery {
328 recovery_id,
329 additional_data: r.read_u8()? & 0x01 != 0,
330 })
331 }
332 // "0x02 - 0xFF Reserved".
333 _ => bail!(UnsupportedVersion),
334 }
335 }
336
337 /// Finds and reads the Matter service data inside a complete advertising payload.
338 ///
339 /// Walks the length-type-value structures looking for Service Data under
340 /// [`SERVICE_UUID`], because a real advertisement carries other structures too and puts
341 /// them in whatever order it likes.
342 pub fn decode(advertisement: &[u8]) -> Result<Self> {
343 let mut r = Cursor::reader(advertisement, ErrorCode::BtpMalformed);
344 // Running out of structures is "no Matter device here"; a structure whose declared
345 // length runs off the end is a malformed advertisement.
346 while let Ok(length) = r.read_u8() {
347 if length == 0 {
348 // A zero length terminates the advertising data early (Bluetooth Core Spec
349 // Vol 3 Part C §11), and the rest is padding.
350 break;
351 }
352 let mut structure =
353 Cursor::reader(r.take(usize::from(length))?, ErrorCode::BtpMalformed);
354 if structure.read_u8() == Ok(AD_TYPE_SERVICE_DATA)
355 && structure.read_u16() == Ok(SERVICE_UUID)
356 {
357 return Self::decode_service_data(structure.rest());
358 }
359 }
360 bail!(TlvNotFound)
361 }
362}
363
364#[cfg(test)]
365mod tests {
366 use super::*;
367
368 #[test]
369 fn a_commissionable_advertisement_matches_table_73() {
370 // The specification's own worked example: VID 0xFFF1, PID 0x8000, discriminator 0x3AB,
371 // additional data present. Byte-for-byte, because a commissioner matches on these.
372 let advert = Advertisement::Commissionable {
373 discriminator: 0x3AB,
374 vendor_id: VendorId(0xFFF1),
375 product_id: 0x8000,
376 additional_data: true,
377 extended_announcement: false,
378 };
379 let mut buf = [0u8; Advertisement::MAX];
380 let n = advert.encode(&mut buf).expect("encode");
381 assert_eq!(
382 &buf[..n],
383 &[
384 0x02, 0x01, 0x06, // Flags: General Discoverable, BR/EDR not supported
385 0x0B, 0x16, 0xF6, 0xFF, // Service Data, 16-bit UUID 0xFFF6
386 0x00, // Commissionable
387 0xAB, 0x03, // version 0, discriminator 0x3AB
388 0xF1, 0xFF, // Vendor ID
389 0x00, 0x80, // Product ID
390 0x01, // additional data present
391 ]
392 );
393 assert_eq!(Advertisement::decode(&buf[..n]).expect("decode"), advert);
394 }
395
396 #[test]
397 fn a_network_recovery_advertisement_matches_table_75() {
398 let advert = Advertisement::NetworkRecovery {
399 // "the octet string 0x11 0x22 … 0x88", little-endian in the payload.
400 recovery_id: u64::from_le_bytes([0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88]),
401 additional_data: false,
402 };
403 let mut buf = [0u8; Advertisement::MAX];
404 let n = advert.encode(&mut buf).expect("encode");
405 assert_eq!(
406 &buf[..n],
407 &[
408 0x02, 0x01, 0x05, // Flags: Limited Discoverable, BR/EDR not supported
409 0x0E, 0x16, 0xF6, 0xFF, 0x01, // Network Recovery
410 0x00, // version and reserved
411 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x00,
412 ]
413 );
414 assert_eq!(Advertisement::decode(&buf[..n]).expect("decode"), advert);
415 }
416
417 #[test]
418 fn the_service_data_is_found_wherever_it_sits() {
419 // "the position of the fields within the Advertising PDU … MAY differ from the
420 // example above, since there are no ordering constraints" — so a scanner that assumed
421 // a fixed offset would miss conformant devices.
422 let advert = Advertisement::Commissionable {
423 discriminator: 0xFFF,
424 vendor_id: VendorId(0xFFF1),
425 product_id: 0x8001,
426 additional_data: false,
427 extended_announcement: true,
428 };
429 let mut service_data = [0u8; 16];
430 let n = advert
431 .encode_service_data(&mut service_data)
432 .expect("encode");
433
434 let mut payload = heapless::Vec::<u8, 64>::new();
435 // A Complete Local Name first, then some other Service Data, then Matter's.
436 payload
437 .extend_from_slice(&[0x05, 0x09, b'l', b'a', b'm', b'p'])
438 .expect("name");
439 payload
440 .extend_from_slice(&[0x04, 0x16, 0x0F, 0x18, 0x64])
441 .expect("battery");
442 payload
443 .extend_from_slice(&[u8::try_from(n + 3).expect("fits"), 0x16, 0xF6, 0xFF])
444 .expect("header");
445 payload
446 .extend_from_slice(&service_data[..n])
447 .expect("service data");
448
449 assert_eq!(Advertisement::decode(&payload).expect("decode"), advert);
450 }
451
452 #[test]
453 fn an_advertisement_with_no_matter_service_data_is_not_a_matter_device() {
454 let other = [0x05u8, 0x09, b'l', b'a', b'm', b'p'];
455 assert_eq!(
456 Advertisement::decode(&other).map_err(|e| e.code()),
457 Err(crate::ErrorCode::TlvNotFound)
458 );
459 }
460
461 #[test]
462 fn a_truncated_ad_structure_is_refused() {
463 // A scanner takes these from the air; a length field longer than the buffer is the
464 // first thing a malformed or clipped advertisement gets wrong.
465 let clipped = [0x0Bu8, 0x16, 0xF6, 0xFF, 0x00];
466 assert_eq!(
467 Advertisement::decode(&clipped).map_err(|e| e.code()),
468 Err(crate::ErrorCode::BtpMalformed)
469 );
470 }
471
472 #[test]
473 fn a_discriminator_wider_than_twelve_bits_is_refused() {
474 // Bits[15:12] are the advertisement version. A 13-bit discriminator would advertise
475 // version 1 and be discarded by every commissioner.
476 let bad = Advertisement::Commissionable {
477 discriminator: 0x1000,
478 vendor_id: VendorId(0xFFF1),
479 product_id: 0x8000,
480 additional_data: false,
481 extended_announcement: false,
482 };
483 let mut buf = [0u8; Advertisement::MAX];
484 assert_eq!(
485 bad.encode(&mut buf).map_err(|e| e.code()),
486 Err(crate::ErrorCode::InvalidArgument)
487 );
488 }
489
490 #[test]
491 fn a_product_id_without_a_vendor_id_is_refused() {
492 // "A device SHALL NOT set the VID to 0 when providing a non-zero PID." Eliding both is
493 // allowed; eliding only the vendor is not.
494 let bad = Advertisement::Commissionable {
495 discriminator: 0x3AB,
496 vendor_id: VendorId(0),
497 product_id: 0x8000,
498 additional_data: false,
499 extended_announcement: false,
500 };
501 let mut buf = [0u8; Advertisement::MAX];
502 assert_eq!(
503 bad.encode(&mut buf).map_err(|e| e.code()),
504 Err(crate::ErrorCode::InvalidArgument)
505 );
506
507 let elided = Advertisement::Commissionable {
508 discriminator: 0x3AB,
509 vendor_id: VendorId(0),
510 product_id: 0,
511 additional_data: false,
512 extended_announcement: false,
513 };
514 elided.encode(&mut buf).expect("eliding both is allowed");
515 }
516
517 #[test]
518 fn a_reserved_opcode_is_not_guessed_at() {
519 // "0x02 - 0xFF Reserved". A future opcode's fields mean something this crate does not
520 // know, so reading them as a discriminator would hand the commissioner a wrong device.
521 assert_eq!(
522 Advertisement::decode_service_data(&[0x02, 0, 0, 0, 0, 0, 0, 0]).map_err(|e| e.code()),
523 Err(crate::ErrorCode::UnsupportedVersion)
524 );
525 }
526
527 #[test]
528 fn the_advertisement_and_the_qr_code_agree_on_the_discriminator() {
529 // A device that advertises a different discriminator from the one on its label is
530 // never found, and the failure looks like a radio problem rather than a wrong number.
531 use crate::commissioning::{CustomFlow, DiscoveryCapabilities, Passcode};
532
533 let payload = OnboardingPayload::new(
534 VendorId(0xFFF1),
535 0x8000,
536 0x3AB,
537 Passcode::new(20_202_021).expect("passcode"),
538 DiscoveryCapabilities::BLE,
539 CustomFlow::Standard,
540 )
541 .expect("payload");
542
543 let advert = Advertisement::for_onboarding(&payload);
544 let mut buf = [0u8; Advertisement::MAX];
545 let n = advert.encode(&mut buf).expect("encode");
546 let Advertisement::Commissionable {
547 discriminator,
548 vendor_id,
549 product_id,
550 ..
551 } = Advertisement::decode(&buf[..n]).expect("decode")
552 else {
553 panic!("a commissionable advertisement")
554 };
555 assert_eq!(discriminator, payload.discriminator);
556 assert_eq!(vendor_id, payload.vendor_id);
557 assert_eq!(product_id, payload.product_id);
558
559 // Eliding takes both halves of the identity, never one.
560 let private = advert.elide_identity().with_extended_announcement(true);
561 let n = private.encode(&mut buf).expect("encode");
562 assert_eq!(Advertisement::decode(&buf[..n]).expect("decode"), private);
563 let Advertisement::Commissionable {
564 discriminator,
565 vendor_id,
566 product_id,
567 extended_announcement,
568 ..
569 } = private
570 else {
571 panic!("still commissionable")
572 };
573 assert_eq!(discriminator, 0x3AB, "the discriminator is what finds it");
574 assert_eq!((vendor_id, product_id), (VendorId(0), 0));
575 assert!(extended_announcement);
576 }
577
578 #[test]
579 fn the_characteristic_uuids_are_the_ones_in_table_34() {
580 // Printed order, most-significant octet first. A stack wanting little-endian reverses.
581 assert_eq!(&C1_UUID[12..], &[0x42, 0x9F, 0x9D, 0x11]);
582 assert_eq!(&C2_UUID[12..], &[0x42, 0x9F, 0x9D, 0x12]);
583 assert_eq!(
584 C1_UUID[..12],
585 C2_UUID[..12],
586 "C1 and C2 differ in one nibble"
587 );
588 assert_eq!(C3_UUID[0], 0x64);
589 }
590}