rs-matter 0.3.0

Native Rust implementation of the Matter (Smart-Home) ecosystem
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
/*
 *
 *    Copyright (c) 2024-2026 Project CHIP Authors
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

use core::iter::{empty, once};

use crate::dm::clusters::basic_info::BasicInfoConfig;
use crate::transport::network::mdns::CommissionableFilter;

use super::{GATT_HEADER_SIZE, MAX_BTP_SEGMENT_SIZE};

/// The AD structure type for "Service Data - 16-bit UUID" (AD2), as per the BLE Core spec.
const AD_TYPE_SERVICE_DATA_UUID16: u8 = 0x16;
/// The length, in bytes, of the Matter commissionable service-data payload
/// (the bytes _following_ the 2-byte service UUID16 in the AD2 record), as per
/// the Matter Core spec, section "5.4.2.5.6. Advertising Data".
const MATTER_SERVICE_DATA_PAYLOAD_LEN: usize = 8;
/// The Matter BLE advertisement OpCode designating a commissionable device.
const MATTER_ADV_OPCODE_COMMISSIONABLE: u8 = 0x00;
/// The Matter BLE advertisement OpCode designating a node in Network Recovery mode.
const MATTER_ADV_OPCODE_NETWORK_RECOVERY: u8 = 0x01;
/// The length, in bytes, of the Matter Network-Recovery service-data payload
/// (the bytes _following_ the 2-byte service UUID16 in the AD2 record), as per
/// the Matter Core spec.
const MATTER_RECOVERY_SERVICE_DATA_PAYLOAD_LEN: usize = 11;
/// The length, in bytes, of the Recovery ID carried in a Network-Recovery
/// advertisement / stored as `GeneralCommissioning::RecoveryIdentifier`.
pub const RECOVERY_ID_LEN: usize = 8;

#[cfg(all(feature = "os", feature = "bluer", target_os = "linux"))]
pub mod bluer;
// BlueZ is Linux-only (it uses the Linux Bluetooth stack and Linux-specific
// socket flags such as `SOCK_CLOEXEC`).
#[cfg(all(feature = "zbus", target_os = "linux"))]
pub mod bluez;

// The 16-bit, registered Matter Service UUID, as per the Matter Core spec.
pub const MATTER_BLE_SERVICE_UUID16: u16 = 0xFFF6;
// A 128-bit expanded representation of the Matter Service UUID.
pub const MATTER_BLE_SERVICE_UUID: u128 = 0x0000FFF600001000800000805F9B34FB;

/// `C1` characteristic UUID, as per the Matter Core spec.
pub const C1_CHARACTERISTIC_UUID: u128 = 0x18EE2EF5263D4559959F4F9C429F9D11;
/// `C2` characteristic UUID, as per the Matter Core spec.
pub const C2_CHARACTERISTIC_UUID: u128 = 0x18EE2EF5263D4559959F4F9C429F9D12;
/// `C3` characteristic UUID, as per the Matter Core spec.
pub const C3_CHARACTERISTIC_UUID: u128 = 0x64630238877245F2B87D748A83218F04;

/// The maximum length of packet data written to the `C1` characteristic, as per the Matter Core spec, and as advertised in the GATT service.
pub const C1_MAX_LEN: usize = MAX_BTP_SEGMENT_SIZE + GATT_HEADER_SIZE;
/// The maximum length of packet data indicated via the `C2` characteristic, as per the Matter Core spec, and as advertised in the GATT service.
pub const C2_MAX_LEN: usize = MAX_BTP_SEGMENT_SIZE + GATT_HEADER_SIZE;
/// The maximum length of data read from the `C3` characteristic, as per the Matter Core spec, and as advertised in the GATT service.
pub const C3_MAX_LEN: usize = 512;

/// Encapsulates the advertising data for the Matter BTP protocol.
///
/// This type is used in two directions:
/// - By an Accessory (GATT Peripheral) to **serialize** the advertising data it
///   broadcasts while commissionable (see [`AdvData::iter`] and friends).
/// - By a Commissioner (GATT Central) to **parse** a scanned advertisement and
///   decide whether it designates the commissionable device it is looking for
///   (see [`AdvData::parse_adv`] / [`AdvData::parse_service_data`] and
///   [`AdvData::matches`]) - the BLE-side analogue of resolving a commissionable
///   node from an mDNS TXT record.
///
/// See section "5.4.2.5.6. Advertising Data" in the Core Matter spec
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct AdvData {
    vid: u16,
    pid: u16,
    discriminator: u16,
    /// Whether the device signals that it carries additional (BLE) advertising
    /// data (bit 0 of the last byte of the Matter service-data payload).
    ///
    /// Always `false` for advertisements produced by this stack; decoded from
    /// the wire when parsing a peer's advertisement.
    additional_data: bool,
}

impl AdvData {
    /// Create a new instance by using the provided `BasicInfoConfig` and `CommissioningData`.
    pub const fn new(dev_det: &BasicInfoConfig, discriminator: u16) -> Self {
        Self {
            vid: dev_det.vid,
            pid: dev_det.pid,
            discriminator,
            additional_data: false,
        }
    }

    /// The Vendor ID carried by this advertising data.
    pub const fn vid(&self) -> u16 {
        self.vid
    }

    /// The Product ID carried by this advertising data.
    pub const fn pid(&self) -> u16 {
        self.pid
    }

    /// The 12-bit discriminator carried by this advertising data.
    pub const fn discriminator(&self) -> u16 {
        self.discriminator
    }

    /// Whether the advertised device signals that it carries additional (BLE)
    /// advertising data. See the field of the same name; commissioners do not
    /// usually need to inspect this.
    pub const fn additional_data(&self) -> bool {
        self.additional_data
    }

    /// Return an iterator over the binary representation of the advertising data.
    ///
    /// As per the Matter Core spec, the advertising data consists of
    /// an AD1 record which is of Flags type, and an AD2 record, which is of type UUID16+Service Data
    pub fn iter(&self) -> impl Iterator<Item = u8> + '_ {
        self.flags_iter().chain(self.service_iter())
    }

    /// Return an iterator over the binary representation of the AD1 advertising data (Flags).
    /// Useful with GATT stacks that require the advertising data to be reported as separate AD records
    pub fn flags_iter(&self) -> impl Iterator<Item = u8> + '_ {
        empty()
            .chain(once(self.flags_payload_iter().count() as u8 + 1)) // 1-byte type
            .chain(once(self.flags_adv_type()))
            .chain(self.flags_payload_iter())
    }

    /// The AD1 advertising data type (Flags).
    pub const fn flags_adv_type(&self) -> u8 {
        0x01
    }

    /// Return an iterator over the binary representation of the AD1 advertising data _payload_.
    /// Useful with GATT stacks that require the advertising data to be reported as separate AD records
    pub fn flags_payload_iter(&self) -> impl Iterator<Item = u8> + '_ {
        once(0x06)
    }

    /// Return an iterator over the binary representation of the AD2 advertising data (UUID16+Service Data).
    pub fn service_iter(&self) -> impl Iterator<Item = u8> + '_ {
        empty()
            .chain(once(self.service_payload_iter().count() as u8 + 3)) // + 1-byte type and 2-bytes Matter UUID16 Service
            .chain(once(self.service_adv_type()))
            .chain(MATTER_BLE_SERVICE_UUID16.to_le_bytes())
            .chain(self.service_payload_iter())
    }

    /// The AD2 advertising data type (UUID16+Service Data).
    pub const fn service_adv_type(&self) -> u8 {
        0x16
    }

    /// Return an iterator over the binary representation of the AD2 advertising data _payload_.
    /// Useful with GATT stacks that require the advertising data to be reported as separate AD records
    pub fn service_payload_iter(&self) -> impl Iterator<Item = u8> + '_ {
        [
            0, // Always 0 = "Commissionable"
            self.discriminator.to_le_bytes()[0],
            self.discriminator.to_le_bytes()[1],
            self.vid.to_le_bytes()[0],
            self.vid.to_le_bytes()[1],
            self.pid.to_le_bytes()[0],
            self.pid.to_le_bytes()[1],
            self.additional_data as u8, // Additional-data flag (bit 0)
        ]
        .into_iter()
    }

    /// Parse the advertising data out of a full, raw BLE advertising-data blob
    /// (a sequence of `length`-prefixed AD structures, i.e. `[len, type, ..len-1 bytes..]*`).
    ///
    /// This walks the AD structures, looks for the "Service Data - 16-bit UUID"
    /// (`0x16`) structure whose UUID is the Matter service UUID (`0xFFF6`), and
    /// decodes its payload.
    ///
    /// Returns `None` if the blob contains no (valid) Matter commissionable
    /// service-data structure. Use this when the OS/GATT stack hands you the raw
    /// advertising bytes; if it instead de-multiplexes service data by UUID for
    /// you (as BlueZ and `bluer` do), use [`AdvData::parse_service_data`] with
    /// the `0xFFF6` service-data value directly.
    pub fn parse_adv(adv: &[u8]) -> Option<Self> {
        matter_service_data(adv).and_then(Self::parse_service_data)
    }

    /// Parse the advertising data out of the Matter service-data payload - i.e.
    /// the bytes of the `0xFFF6` "Service Data - 16-bit UUID" advertising
    /// structure that _follow_ the 2-byte service UUID.
    ///
    /// This is the layout produced by [`AdvData::service_payload_iter`] and is
    /// what most OS GATT stacks (BlueZ, `bluer`) hand back when they expose
    /// advertised service data as a `UUID -> bytes` map.
    ///
    /// Returns `None` if the payload is not a valid, commissionable Matter
    /// service-data payload.
    pub fn parse_service_data(payload: &[u8]) -> Option<Self> {
        // As per spec the payload is exactly 8 bytes. Be lenient and accept a
        // longer payload (future extensions), but never a shorter one.
        if payload.len() < MATTER_SERVICE_DATA_PAYLOAD_LEN {
            return None;
        }

        // Byte 0 is the Matter BLE OpCode; only "Commissionable" (0) is a
        // commissionable device.
        if payload[0] != MATTER_ADV_OPCODE_COMMISSIONABLE {
            return None;
        }

        // Bytes 1..=2 are a 16-bit LE field whose low 12 bits are the
        // discriminator and whose high 4 bits are the advertising version
        // (currently 0). Mask off the version so we get the plain discriminator.
        let discriminator = u16::from_le_bytes([payload[1], payload[2]]) & 0x0FFF;
        let vid = u16::from_le_bytes([payload[3], payload[4]]);
        let pid = u16::from_le_bytes([payload[5], payload[6]]);
        let additional_data = payload[7] & 0x01 != 0;

        Some(Self {
            vid,
            pid,
            discriminator,
            additional_data,
        })
    }

    /// Whether this advertised commissionable device matches **all** of the
    /// non-`None` fields of the provided [`CommissionableFilter`] (AND
    /// semantics); an empty filter matches every commissionable device.
    ///
    /// This mirrors [`CommissionableFilter::matches`] (the mDNS TXT-record path)
    /// over the subset of fields a BLE advertisement carries:
    /// - `discriminator` (full 12-bit) and `short_discriminator` (upper 4 bits)
    ///   are matched against the advertised discriminator;
    /// - `vendor_id` / `product_id` are matched against the advertised VID / PID.
    ///
    /// A BLE advertisement does not carry a device type, and being advertised at
    /// all already implies commissioning mode, so a filter that constrains
    /// `device_type` never matches a BLE advertisement, and
    /// `commissioning_mode_only` is always satisfied.
    pub fn matches(&self, filter: &CommissionableFilter) -> bool {
        if let Some(want) = filter.discriminator {
            if self.discriminator != want {
                return false;
            }
        }

        if let Some(want) = filter.short_discriminator {
            // Short discriminator is the upper 4 bits of the 12-bit discriminator.
            if (self.discriminator >> 8) as u8 != want {
                return false;
            }
        }

        if let Some(want) = filter.vendor_id {
            if self.vid != want {
                return false;
            }
        }

        if let Some(want) = filter.product_id {
            if self.pid != want {
                return false;
            }
        }

        // A BLE advertisement carries no device type; a filter that requires one
        // cannot be satisfied by BLE discovery.
        if filter.device_type.is_some() {
            return false;
        }

        // `commissioning_mode_only` is implicit: a commissionable advertisement
        // (OpCode 0) is, by definition, in commissioning mode.

        true
    }
}

/// Advertising data for a node in Matter Network Recovery mode (BLE Device
/// OpCode `0x01`), per the Matter 1.6 Core spec.
///
/// The Recovery ID is the 8-byte `GeneralCommissioning::RecoveryIdentifier`
/// attribute value; it lets an Administrator identify the node without learning
/// its Node ID. Unlike the commissionable advertisement, a Network Recovery
/// advertisement carries no VID / PID / discriminator.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct RecoveryAdvData {
    /// The 8-byte Recovery ID (`GeneralCommissioning::RecoveryIdentifier`).
    recovery_id: [u8; RECOVERY_ID_LEN],
    /// Whether the device signals that it carries additional (BLE) advertising
    /// data (bit 0 of the last byte of the service-data payload).
    ///
    /// Always `false` for advertisements produced by this stack; decoded from
    /// the wire when parsing a peer's advertisement.
    additional_data: bool,
}

impl RecoveryAdvData {
    /// Create a new instance carrying the given 8-byte Recovery ID.
    ///
    /// The bytes are the `GeneralCommissioning::RecoveryIdentifier` attribute
    /// value, copied verbatim onto the wire (Matter 1.6 Core spec, Table 75).
    pub const fn new(recovery_id: [u8; RECOVERY_ID_LEN]) -> Self {
        Self {
            recovery_id,
            additional_data: false,
        }
    }

    /// The 8-byte Recovery ID carried by this advertising data.
    pub const fn recovery_id(&self) -> [u8; RECOVERY_ID_LEN] {
        self.recovery_id
    }

    /// Whether the advertised device signals that it carries additional (BLE)
    /// advertising data. See the field of the same name.
    pub const fn additional_data(&self) -> bool {
        self.additional_data
    }

    /// Return an iterator over the binary representation of the advertising data
    /// (the AD1 Flags record followed by the AD2 UUID16+Service Data record).
    pub fn iter(&self) -> impl Iterator<Item = u8> + '_ {
        self.flags_iter().chain(self.service_iter())
    }

    /// Return an iterator over the binary representation of the AD1 advertising
    /// data (Flags). Useful with GATT stacks that require the advertising data
    /// to be reported as separate AD records.
    pub fn flags_iter(&self) -> impl Iterator<Item = u8> + '_ {
        empty()
            .chain(once(self.flags_payload_iter().count() as u8 + 1)) // 1-byte type
            .chain(once(self.flags_adv_type()))
            .chain(self.flags_payload_iter())
    }

    /// The AD1 advertising data type (Flags).
    pub const fn flags_adv_type(&self) -> u8 {
        0x01
    }

    /// Return an iterator over the binary representation of the AD1 advertising
    /// data _payload_.
    ///
    /// Per the Matter 1.6 Core spec (Table 75) a Recovery Node advertises
    /// `0x05`: LE Limited Discoverable Mode (bit 0) set, LE General Discoverable
    /// Mode (bit 1) clear, BR/EDR Not Supported (bit 2) set. (A commissionable
    /// device instead advertises `0x06` - General, not Limited.)
    pub fn flags_payload_iter(&self) -> impl Iterator<Item = u8> + '_ {
        once(0x05)
    }

    /// Return an iterator over the binary representation of the AD2 advertising
    /// data (UUID16+Service Data).
    pub fn service_iter(&self) -> impl Iterator<Item = u8> + '_ {
        empty()
            .chain(once(self.service_payload_iter().count() as u8 + 3)) // + 1-byte type and 2-bytes Matter UUID16 Service
            .chain(once(self.service_adv_type()))
            .chain(MATTER_BLE_SERVICE_UUID16.to_le_bytes())
            .chain(self.service_payload_iter())
    }

    /// The AD2 advertising data type (UUID16+Service Data).
    pub const fn service_adv_type(&self) -> u8 {
        0x16
    }

    /// Return an iterator over the binary representation of the AD2 advertising
    /// data _payload_ (the Matter Network-Recovery service-data payload).
    pub fn service_payload_iter(&self) -> impl Iterator<Item = u8> + '_ {
        empty()
            .chain(once(MATTER_ADV_OPCODE_NETWORK_RECOVERY))
            .chain(once(0x00)) // Bits[7:4] advertisement version == 0, Bits[3:0] reserved == 0
            .chain(self.recovery_id) // Recovery ID, copied verbatim
            .chain(once(self.additional_data as u8)) // Additional-data flag (bit 0)
    }

    /// Parse a Network-Recovery advertisement out of a full, raw BLE
    /// advertising-data blob (a sequence of `length`-prefixed AD structures).
    ///
    /// Walks the AD structures, finds the Matter service-data structure
    /// (`0xFFF6`) and decodes it as a Network-Recovery payload. Returns `None`
    /// if the blob carries no (valid) Matter Network-Recovery service data.
    ///
    /// Use this when the OS/GATT stack hands you the raw advertising bytes; if
    /// it instead de-multiplexes service data by UUID, use
    /// [`RecoveryAdvData::parse_service_data`] with the `0xFFF6` value directly.
    pub fn parse_adv(adv: &[u8]) -> Option<Self> {
        matter_service_data(adv).and_then(Self::parse_service_data)
    }

    /// Parse a Network-Recovery advertisement out of the Matter service-data
    /// payload - i.e. the bytes of the `0xFFF6` service-data structure that
    /// _follow_ the 2-byte service UUID.
    ///
    /// This is the layout produced by [`RecoveryAdvData::service_payload_iter`].
    /// Returns `None` if the payload is not a valid Matter Network-Recovery
    /// service-data payload (e.g. it is a commissionable payload instead).
    pub fn parse_service_data(payload: &[u8]) -> Option<Self> {
        // As per spec the payload is exactly 11 bytes. Be lenient and accept a
        // longer payload (future extensions), but never a shorter one.
        if payload.len() < MATTER_RECOVERY_SERVICE_DATA_PAYLOAD_LEN {
            return None;
        }

        // Byte 0 is the Matter BLE OpCode; only "Network Recovery" (1) applies.
        if payload[0] != MATTER_ADV_OPCODE_NETWORK_RECOVERY {
            return None;
        }

        // Byte 1 high nibble is the advertisement version (currently 0); the low
        // nibble is reserved. We do not reject a non-zero version so that a
        // future minor revision keeps parsing, mirroring the commissionable path
        // which tolerates the version bits.

        // Bytes 2..=9 are the Recovery ID, copied verbatim. The slice is
        // exactly `RECOVERY_ID_LEN` long (guaranteed by the length check above),
        // so the `try_into` never fails.
        let recovery_id: [u8; RECOVERY_ID_LEN] =
            payload[2..2 + RECOVERY_ID_LEN].try_into().unwrap();
        let additional_data = payload[2 + RECOVERY_ID_LEN] & 0x01 != 0;

        Some(Self {
            recovery_id,
            additional_data,
        })
    }

    /// Whether this advertised Recovery Node carries the given Recovery ID.
    ///
    /// This is the Network-Recovery analogue of [`AdvData::matches`]: an
    /// Administrator that retrieved the `RecoveryIdentifier` before the node
    /// lost connectivity uses it to pick out that specific node among any
    /// Recovery Nodes it scans.
    pub fn matches(&self, recovery_id: &[u8; RECOVERY_ID_LEN]) -> bool {
        self.recovery_id == *recovery_id
    }
}

/// Walk the AD structures of a raw BLE advertising-data blob and return the
/// Matter service-data payload - the bytes of the `0xFFF6` "Service Data -
/// 16-bit UUID" structure that _follow_ the 2-byte service UUID - or `None` if
/// there is no such structure.
///
/// Shared by [`AdvData::parse_adv`] and [`RecoveryAdvData::parse_adv`], which
/// differ only in how they interpret the returned payload (by its OpCode byte).
fn matter_service_data(adv: &[u8]) -> Option<&[u8]> {
    for (ad_type, ad_payload) in AdStructures::new(adv) {
        if ad_type != AD_TYPE_SERVICE_DATA_UUID16 {
            continue;
        }

        // The service-data payload starts with the 2-byte (LE) UUID16. A
        // structure too short to hold one is malformed - skip it and keep
        // looking, rather than giving up on the whole advertisement: the Matter
        // record may well be further along.
        let Some((uuid16, service_data)) = ad_payload.split_first_chunk::<2>() else {
            continue;
        };

        if u16::from_le_bytes(*uuid16) == MATTER_BLE_SERVICE_UUID16 {
            return Some(service_data);
        }
    }

    None
}

/// An iterator over the individual AD structures of a raw BLE advertising-data
/// blob, yielding `(ad_type, ad_payload)` for each well-formed
/// `[length, type, ..payload..]` structure and stopping at the first malformed
/// or zero-length structure (as per the BLE Core spec, a zero-length structure
/// marks the end of significant data).
struct AdStructures<'a> {
    rem: &'a [u8],
}

impl<'a> AdStructures<'a> {
    const fn new(adv: &'a [u8]) -> Self {
        Self { rem: adv }
    }
}

impl<'a> Iterator for AdStructures<'a> {
    type Item = (u8, &'a [u8]);

    fn next(&mut self) -> Option<Self::Item> {
        let (&len, rest) = self.rem.split_first()?;

        // A zero-length structure marks the end of significant data.
        let len = len as usize;
        if len == 0 || len > rest.len() {
            self.rem = &[];
            return None;
        }

        let (structure, rest) = rest.split_at(len);
        self.rem = rest;

        // `len` counts the type byte plus the payload, so `structure` is
        // non-empty here.
        let (&ad_type, payload) = structure.split_first()?;

        Some((ad_type, payload))
    }
}

#[cfg(test)]
mod test {
    use crate::transport::network::mdns::CommissionableFilter;

    use super::{AdvData, RecoveryAdvData};

    /// A sample `AdvData` with a 12-bit discriminator that exercises the
    /// version-nibble masking on parse.
    fn sample() -> AdvData {
        AdvData {
            vid: 0xFFF1,
            pid: 0x8000,
            discriminator: 0xF00,
            additional_data: false,
        }
    }

    /// The parsed form of [`sample`], via the service-data payload round-trip.
    fn sample_parsed() -> AdvData {
        let payload: heapless::Vec<u8, 16> = sample().service_payload_iter().collect();
        AdvData::parse_service_data(&payload).unwrap()
    }

    #[test]
    fn parse_service_data_round_trips_adv_data() {
        let adv = sample();
        let parsed = sample_parsed();

        assert_eq!(parsed, adv);
        assert_eq!(parsed.discriminator(), adv.discriminator());
        assert_eq!(parsed.vid(), adv.vid());
        assert_eq!(parsed.pid(), adv.pid());
        assert!(!parsed.additional_data());
    }

    #[test]
    fn parse_service_data_round_trips_additional_data_flag() {
        let adv = AdvData {
            additional_data: true,
            ..sample()
        };
        let payload: heapless::Vec<u8, 16> = adv.service_payload_iter().collect();
        let parsed = AdvData::parse_service_data(&payload).unwrap();

        assert!(parsed.additional_data());
        assert_eq!(parsed, adv);
    }

    #[test]
    fn parse_full_adv_round_trips_adv_data() {
        let adv = sample();

        // The full AD blob is the AD1 (Flags) record chained with the AD2
        // (UUID16 + Service Data) record.
        let blob: heapless::Vec<u8, 32> = adv.iter().collect();

        let parsed = AdvData::parse_adv(&blob).unwrap();

        assert_eq!(parsed, adv);
    }

    #[test]
    fn parse_adv_ignores_unrelated_records() {
        // A blob with a Flags record, an unrelated 16-bit service-data record,
        // and finally the Matter one - the parser must skip to the Matter one.
        let adv = sample();

        let mut blob: heapless::Vec<u8, 64> = heapless::Vec::new();
        // Flags
        blob.extend([0x02, 0x01, 0x06]);
        // Unrelated Service Data - UUID16 (0x1234), 3 payload bytes
        blob.extend([0x06, 0x16, 0x34, 0x12, 0xAA, 0xBB, 0xCC]);
        // The Matter one
        blob.extend(adv.service_iter());

        let parsed = AdvData::parse_adv(&blob).unwrap();
        assert_eq!(parsed.discriminator(), adv.discriminator());
    }

    #[test]
    fn parse_adv_skips_a_malformed_service_data_record() {
        // A service-data record too short to even hold its UUID16, *before* the
        // Matter one. It must be skipped rather than abandoning the whole scan.
        let adv = sample();

        let mut blob: heapless::Vec<u8, 64> = heapless::Vec::new();
        // Service Data - UUID16 with a 1-byte payload: not even a full UUID.
        blob.extend([0x02, 0x16, 0x34]);
        // The Matter one.
        blob.extend(adv.service_iter());

        let parsed = unwrap!(AdvData::parse_adv(&blob), "Failed to parse");
        assert_eq!(parsed.discriminator(), adv.discriminator());
    }

    #[test]
    fn parse_service_data_rejects_non_commissionable_opcode() {
        let mut payload: heapless::Vec<u8, 16> = sample().service_payload_iter().collect();
        payload[0] = 0x01; // Not "Commissionable"

        assert!(AdvData::parse_service_data(&payload).is_none());
    }

    #[test]
    fn parse_service_data_rejects_short_payload() {
        assert!(AdvData::parse_service_data(&[0, 1, 2, 3]).is_none());
    }

    #[test]
    fn parse_adv_returns_none_without_matter_service_data() {
        // Just a Flags record - no Matter service data.
        assert!(AdvData::parse_adv(&[0x02, 0x01, 0x06]).is_none());
    }

    #[test]
    fn parse_adv_tolerates_truncated_trailing_record() {
        let adv = sample();
        let mut blob: heapless::Vec<u8, 64> = adv.iter().collect();
        // Append a malformed record claiming more bytes than are present.
        blob.extend([0x05, 0x16, 0x00]);

        // The Matter record precedes the malformed one, so it's still found.
        assert!(AdvData::parse_adv(&blob).is_some());
    }

    // ---- Network Recovery advertisement (BLE Device OpCode 0x01) -----------

    /// The exemplary Recovery ID from Matter 1.6 Core spec Table 75.
    const SPEC_RECOVERY_ID: [u8; 8] = [0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88];

    /// The full advertising PDU payload from Matter 1.6 Core spec Table 75
    /// ("Advertising PDU payload when CHIP BLE OpCode indicates Node is in
    /// Network Recovery mode"), for `SPEC_RECOVERY_ID` with the additional-data
    /// flag clear.
    const SPEC_RECOVERY_ADV: [u8; 18] = [
        0x02, 0x01, 0x05, // AD1: Flags (Limited Discoverable + BR/EDR not supported)
        0x0E, 0x16, 0xF6, 0xFF, // AD2: len 14, Service Data - UUID16 == 0xFFF6
        0x01, // OpCode == Network Recovery
        0x00, // advertisement version 0 / reserved
        0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, // Recovery ID
        0x00, // additional-data flag clear
    ];

    #[test]
    fn recovery_serialize_matches_spec_example() {
        let adv = RecoveryAdvData::new(SPEC_RECOVERY_ID);
        let blob: heapless::Vec<u8, 32> = adv.iter().collect();

        assert_eq!(&blob[..], &SPEC_RECOVERY_ADV[..]);
    }

    #[test]
    fn recovery_parse_service_data_round_trips() {
        let adv = RecoveryAdvData::new(SPEC_RECOVERY_ID);
        let payload: heapless::Vec<u8, 16> = adv.service_payload_iter().collect();

        let parsed = RecoveryAdvData::parse_service_data(&payload).unwrap();

        assert_eq!(parsed, adv);
        assert_eq!(parsed.recovery_id(), SPEC_RECOVERY_ID);
        assert!(!parsed.additional_data());
    }

    #[test]
    fn recovery_parse_full_spec_adv() {
        let parsed = RecoveryAdvData::parse_adv(&SPEC_RECOVERY_ADV).unwrap();

        assert_eq!(parsed.recovery_id(), SPEC_RECOVERY_ID);
        assert!(!parsed.additional_data());
    }

    #[test]
    fn recovery_additional_data_flag_round_trips() {
        let adv = RecoveryAdvData {
            additional_data: true,
            ..RecoveryAdvData::new(SPEC_RECOVERY_ID)
        };
        let payload: heapless::Vec<u8, 16> = adv.service_payload_iter().collect();

        let parsed = RecoveryAdvData::parse_service_data(&payload).unwrap();

        assert!(parsed.additional_data());
        assert_eq!(parsed, adv);
    }

    #[test]
    fn recovery_matches_only_its_own_id() {
        let adv = RecoveryAdvData::new(SPEC_RECOVERY_ID);

        assert!(adv.matches(&SPEC_RECOVERY_ID));

        let mut other = SPEC_RECOVERY_ID;
        other[0] ^= 0xFF;
        assert!(!adv.matches(&other));
    }

    #[test]
    fn recovery_parse_rejects_short_payload() {
        // 10 bytes: one short of the 11-byte minimum.
        assert!(RecoveryAdvData::parse_service_data(&[1, 0, 1, 2, 3, 4, 5, 6, 7, 8]).is_none());
    }

    #[test]
    fn recovery_and_commissionable_payloads_are_disjoint() {
        // A commissionable payload (OpCode 0) is not a Recovery advertisement...
        let comm: heapless::Vec<u8, 16> = sample().service_payload_iter().collect();
        assert!(RecoveryAdvData::parse_service_data(&comm).is_none());

        // ...and a Recovery payload (OpCode 1) is not a commissionable one.
        let recovery: heapless::Vec<u8, 16> = RecoveryAdvData::new(SPEC_RECOVERY_ID)
            .service_payload_iter()
            .collect();
        assert!(AdvData::parse_service_data(&recovery).is_none());
    }

    #[test]
    fn recovery_parse_adv_returns_none_without_matter_service_data() {
        // Just a Flags record - no Matter service data.
        assert!(RecoveryAdvData::parse_adv(&[0x02, 0x01, 0x05]).is_none());
    }

    #[test]
    fn matches_filter_by_full_and_short_discriminator() {
        let parsed = sample_parsed();

        // Exact discriminator 0xF00
        let mut filter = CommissionableFilter {
            discriminator: Some(0xF00),
            ..Default::default()
        };
        assert!(parsed.matches(&filter));

        filter.discriminator = Some(0xF01);
        assert!(!parsed.matches(&filter));

        // Short discriminator = upper 4 bits of 0xF00 = 0xF
        let filter = CommissionableFilter {
            short_discriminator: Some(0xF),
            ..Default::default()
        };
        assert!(parsed.matches(&filter));

        let filter = CommissionableFilter {
            short_discriminator: Some(0x0),
            ..Default::default()
        };
        assert!(!parsed.matches(&filter));
    }

    #[test]
    fn matches_filter_by_vid_pid() {
        let parsed = sample_parsed();

        let filter = CommissionableFilter {
            vendor_id: Some(0xFFF1),
            product_id: Some(0x8000),
            ..Default::default()
        };
        assert!(parsed.matches(&filter));

        let filter = CommissionableFilter {
            vendor_id: Some(0x1234),
            ..Default::default()
        };
        assert!(!parsed.matches(&filter));
    }

    #[test]
    fn empty_filter_matches_any_commissionable_adv() {
        assert!(sample_parsed().matches(&CommissionableFilter::default()));
    }

    #[test]
    fn device_type_filter_never_matches_ble() {
        let filter = CommissionableFilter {
            device_type: Some(0x0100),
            ..Default::default()
        };
        assert!(!sample_parsed().matches(&filter));
    }
}