peat-btle 0.3.2

Bluetooth Low Energy mesh transport for Peat Protocol
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
// Copyright (c) 2025-2026 (r)evolve - Revolve Team LLC
// SPDX-License-Identifier: Apache-2.0
//
// 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.

//! BLE Scanner for discovering Peat nodes
//!
//! Provides filtering, deduplication, and tracking of discovered Peat beacons.

#[cfg(not(feature = "std"))]
use alloc::{string::String, vec::Vec};
#[cfg(feature = "std")]
use std::collections::HashMap;

#[cfg(feature = "std")]
use crate::config::DiscoveryConfig;
use crate::HierarchyLevel;
#[cfg(feature = "std")]
use crate::NodeId;

use super::beacon::{ParsedAdvertisement, PeatBeacon};
#[cfg(feature = "std")]
use super::encrypted_beacon::{BeaconKey, EncryptedBeacon};

/// Default timeout for considering a device "stale" (ms)
#[cfg(feature = "std")]
const DEFAULT_DEVICE_TIMEOUT_MS: u64 = 30_000;

/// Minimum interval between processing duplicate beacons from same node (ms)
#[cfg(feature = "std")]
const DEDUP_INTERVAL_MS: u64 = 500;

/// Tracked device state
#[derive(Debug, Clone)]
pub struct TrackedDevice {
    /// Last received beacon
    pub beacon: PeatBeacon,
    /// Device address
    pub address: String,
    /// Last RSSI reading
    pub rssi: i8,
    /// RSSI history for averaging (last N readings)
    pub rssi_history: Vec<i8>,
    /// When first discovered (monotonic ms timestamp)
    pub first_seen_ms: u64,
    /// When last beacon received (monotonic ms timestamp)
    pub last_seen_ms: u64,
    /// Estimated distance in meters
    pub estimated_distance: Option<f32>,
    /// Whether this device is currently connectable
    pub connectable: bool,
}

impl TrackedDevice {
    /// Create a new tracked device
    #[cfg(feature = "std")]
    fn new(
        beacon: PeatBeacon,
        address: String,
        rssi: i8,
        connectable: bool,
        current_time_ms: u64,
    ) -> Self {
        Self {
            beacon,
            address,
            rssi,
            rssi_history: vec![rssi],
            first_seen_ms: current_time_ms,
            last_seen_ms: current_time_ms,
            estimated_distance: None,
            connectable,
        }
    }

    /// Update with new beacon data
    #[cfg(feature = "std")]
    fn update(&mut self, beacon: PeatBeacon, rssi: i8, connectable: bool, current_time_ms: u64) {
        self.beacon = beacon;
        self.rssi = rssi;
        self.last_seen_ms = current_time_ms;
        self.connectable = connectable;

        // Keep last 10 RSSI readings for averaging
        self.rssi_history.push(rssi);
        if self.rssi_history.len() > 10 {
            self.rssi_history.remove(0);
        }
    }

    /// Get average RSSI
    pub fn average_rssi(&self) -> i8 {
        if self.rssi_history.is_empty() {
            return self.rssi;
        }
        let sum: i32 = self.rssi_history.iter().map(|&r| r as i32).sum();
        (sum / self.rssi_history.len() as i32) as i8
    }

    /// Check if this device is stale (not seen recently)
    pub fn is_stale(&self, timeout_ms: u64, current_time_ms: u64) -> bool {
        current_time_ms.saturating_sub(self.last_seen_ms) > timeout_ms
    }

    /// Get time since first discovery in milliseconds
    pub fn time_tracked_ms(&self, current_time_ms: u64) -> u64 {
        current_time_ms.saturating_sub(self.first_seen_ms)
    }
}

/// Filter criteria for scanning
#[derive(Debug, Clone, Default)]
pub struct ScanFilter {
    /// Only include Peat nodes
    pub peat_only: bool,
    /// Only include nodes at or above this hierarchy level
    pub min_hierarchy_level: Option<HierarchyLevel>,
    /// Only include nodes with these capabilities (bitmask)
    pub required_capabilities: Option<u16>,
    /// Exclude nodes with these capabilities
    pub excluded_capabilities: Option<u16>,
    /// Minimum RSSI threshold (exclude weaker signals)
    pub min_rssi: Option<i8>,
    /// Maximum estimated distance in meters
    pub max_distance: Option<f32>,
    /// Only include connectable devices
    pub connectable_only: bool,
}

impl ScanFilter {
    /// Create a filter for Peat nodes only
    pub fn peat_nodes() -> Self {
        Self {
            peat_only: true,
            ..Default::default()
        }
    }

    /// Create a filter for potential parents (nodes above our level)
    pub fn potential_parents(our_level: HierarchyLevel) -> Self {
        Self {
            peat_only: true,
            min_hierarchy_level: Some(our_level),
            connectable_only: true,
            ..Default::default()
        }
    }

    /// Check if a parsed advertisement passes this filter
    pub fn matches(&self, adv: &ParsedAdvertisement) -> bool {
        // Peat-only filter
        if self.peat_only && !adv.is_peat_device() {
            return false;
        }

        // RSSI filter
        if let Some(min_rssi) = self.min_rssi {
            if adv.rssi < min_rssi {
                return false;
            }
        }

        // Distance filter
        if let Some(max_distance) = self.max_distance {
            if let Some(distance) = adv.estimated_distance_meters() {
                if distance > max_distance {
                    return false;
                }
            }
        }

        // Connectable filter
        if self.connectable_only && !adv.connectable {
            return false;
        }

        // Beacon-specific filters
        if let Some(ref beacon) = adv.beacon {
            // Hierarchy level filter
            if let Some(min_level) = self.min_hierarchy_level {
                if beacon.hierarchy_level < min_level {
                    return false;
                }
            }

            // Required capabilities
            if let Some(required) = self.required_capabilities {
                if beacon.capabilities & required != required {
                    return false;
                }
            }

            // Excluded capabilities
            if let Some(excluded) = self.excluded_capabilities {
                if beacon.capabilities & excluded != 0 {
                    return false;
                }
            }
        }

        true
    }
}

/// Scanner state machine
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScannerState {
    /// Not scanning
    Idle,
    /// Actively scanning
    Scanning,
    /// Paused (e.g., during connection)
    Paused,
}

/// BLE Scanner for discovering Peat nodes
///
/// Handles beacon reception, filtering, deduplication, and device tracking.
///
/// Note: This type requires the `std` feature for full functionality.
#[cfg(feature = "std")]
pub struct Scanner {
    /// Scanner configuration (will be used for PHY/power management)
    #[allow(dead_code)]
    config: DiscoveryConfig,
    /// Current state
    state: ScannerState,
    /// Tracked devices by node ID
    devices: HashMap<NodeId, TrackedDevice>,
    /// Address to node ID mapping (for devices without parsed beacon)
    address_map: HashMap<String, NodeId>,
    /// Filter criteria
    filter: ScanFilter,
    /// Device timeout (ms)
    device_timeout_ms: u64,
    /// Last dedup timestamps per node (ms)
    last_processed: HashMap<NodeId, u64>,
    /// Current time (monotonic ms, set externally)
    current_time_ms: u64,
    /// Beacon key for decrypting encrypted beacons (optional)
    beacon_key: Option<BeaconKey>,
    /// Expected mesh ID bytes for filtering decrypted beacons
    mesh_id_bytes: Option<[u8; 4]>,
}

#[cfg(feature = "std")]
impl Scanner {
    /// Create a new scanner with default settings
    pub fn new(config: DiscoveryConfig) -> Self {
        Self {
            config,
            state: ScannerState::Idle,
            devices: HashMap::new(),
            address_map: HashMap::new(),
            filter: ScanFilter::default(),
            device_timeout_ms: DEFAULT_DEVICE_TIMEOUT_MS,
            last_processed: HashMap::new(),
            current_time_ms: 0,
            beacon_key: None,
            mesh_id_bytes: None,
        }
    }

    /// Set the current time (call periodically from platform)
    pub fn set_time_ms(&mut self, time_ms: u64) {
        self.current_time_ms = time_ms;
    }

    /// Set the scan filter
    pub fn set_filter(&mut self, filter: ScanFilter) {
        self.filter = filter;
    }

    /// Set device timeout in milliseconds
    pub fn set_device_timeout_ms(&mut self, timeout_ms: u64) {
        self.device_timeout_ms = timeout_ms;
    }

    /// Configure beacon key for decrypting encrypted advertisements
    ///
    /// # Arguments
    /// * `key` - Beacon encryption key from mesh genesis
    /// * `mesh_id_bytes` - Expected 4-byte mesh identifier for filtering
    ///
    /// When configured, the scanner will attempt to decrypt encrypted beacons
    /// and only accept those from the specified mesh.
    pub fn set_beacon_key(&mut self, key: BeaconKey, mesh_id_bytes: [u8; 4]) {
        self.beacon_key = Some(key);
        self.mesh_id_bytes = Some(mesh_id_bytes);
    }

    /// Clear beacon key (stop accepting encrypted beacons)
    pub fn clear_beacon_key(&mut self) {
        self.beacon_key = None;
        self.mesh_id_bytes = None;
    }

    /// Check if this scanner can decrypt encrypted beacons
    pub fn can_decrypt_beacons(&self) -> bool {
        self.beacon_key.is_some() && self.mesh_id_bytes.is_some()
    }

    /// Get current state
    pub fn state(&self) -> ScannerState {
        self.state
    }

    /// Start scanning
    pub fn start(&mut self) {
        self.state = ScannerState::Scanning;
    }

    /// Pause scanning
    pub fn pause(&mut self) {
        self.state = ScannerState::Paused;
    }

    /// Stop scanning
    pub fn stop(&mut self) {
        self.state = ScannerState::Idle;
    }

    /// Process a received advertisement
    ///
    /// Returns true if this is a new or updated device that passes the filter.
    ///
    /// Handles both plaintext and encrypted beacons:
    /// - Plaintext beacons are processed directly from `adv.beacon`
    /// - Encrypted beacons (in `adv.encrypted_service_data`) are decrypted if a
    ///   beacon key is configured
    pub fn process_advertisement(&mut self, adv: ParsedAdvertisement) -> bool {
        // Apply filter
        if !self.filter.matches(&adv) {
            return false;
        }

        // Extract beacon and node ID - try plaintext first, then encrypted
        let (beacon, node_id) = if let Some(ref b) = adv.beacon {
            // Plaintext beacon
            (b.clone(), b.node_id)
        } else if let Some(ref encrypted_data) = adv.encrypted_service_data {
            // Try to decrypt encrypted beacon
            match self.try_decrypt_beacon(encrypted_data) {
                Some((decrypted_beacon, _mesh_id)) => {
                    let node_id = decrypted_beacon.node_id;
                    (decrypted_beacon, node_id)
                }
                None => return false, // Decryption failed (wrong mesh or no key)
            }
        } else {
            return false; // No beacon = not a Peat device
        };

        // Check deduplication
        if let Some(&last) = self.last_processed.get(&node_id) {
            if self.current_time_ms.saturating_sub(last) < DEDUP_INTERVAL_MS {
                return false;
            }
        }
        self.last_processed.insert(node_id, self.current_time_ms);

        // Update or create tracked device
        let is_new = !self.devices.contains_key(&node_id);

        if let Some(device) = self.devices.get_mut(&node_id) {
            // Update existing device
            device.update(beacon, adv.rssi, adv.connectable, self.current_time_ms);
        } else {
            // New device
            let device = TrackedDevice::new(
                beacon,
                adv.address.clone(),
                adv.rssi,
                adv.connectable,
                self.current_time_ms,
            );
            self.devices.insert(node_id, device);
            self.address_map.insert(adv.address, node_id);
        }

        is_new
    }

    /// Attempt to decrypt an encrypted beacon
    ///
    /// Returns the decrypted beacon and mesh_id if successful.
    fn try_decrypt_beacon(&self, encrypted_data: &[u8]) -> Option<(PeatBeacon, [u8; 4])> {
        let key = self.beacon_key.as_ref()?;
        let expected_mesh_id = self.mesh_id_bytes?;

        // Try to decrypt
        let (encrypted_beacon, mesh_id) = EncryptedBeacon::decrypt(encrypted_data, key)?;

        // Check mesh ID matches (ensures this is from our mesh)
        if mesh_id != expected_mesh_id {
            return None;
        }

        // Convert EncryptedBeacon to a PeatBeacon
        let beacon = PeatBeacon {
            version: 1,
            capabilities: encrypted_beacon.capabilities,
            node_id: encrypted_beacon.node_id,
            hierarchy_level: HierarchyLevel::from(encrypted_beacon.hierarchy_level),
            geohash: 0, // Not included in encrypted beacon
            battery_percent: encrypted_beacon.battery_percent,
            seq_num: 0, // Not included in encrypted beacon
        };

        Some((beacon, mesh_id))
    }

    /// Get a tracked device by node ID
    pub fn get_device(&self, node_id: &NodeId) -> Option<&TrackedDevice> {
        self.devices.get(node_id)
    }

    /// Get node ID for an address
    pub fn get_node_id_for_address(&self, address: &str) -> Option<&NodeId> {
        self.address_map.get(address)
    }

    /// Get all tracked devices
    pub fn devices(&self) -> impl Iterator<Item = &TrackedDevice> {
        self.devices.values()
    }

    /// Get devices sorted by RSSI (strongest first)
    pub fn devices_by_rssi(&self) -> Vec<&TrackedDevice> {
        let mut devices: Vec<_> = self.devices.values().collect();
        devices.sort_by_key(|d| std::cmp::Reverse(d.rssi));
        devices
    }

    /// Get devices sorted by hierarchy level (highest first)
    pub fn devices_by_hierarchy(&self) -> Vec<&TrackedDevice> {
        let mut devices: Vec<_> = self.devices.values().collect();
        devices.sort_by_key(|d| std::cmp::Reverse(d.beacon.hierarchy_level));
        devices
    }

    /// Get count of tracked devices
    pub fn device_count(&self) -> usize {
        self.devices.len()
    }

    /// Remove stale devices
    ///
    /// Returns the number of devices removed.
    pub fn remove_stale(&mut self) -> usize {
        let timeout = self.device_timeout_ms;
        let current_time = self.current_time_ms;
        let stale: Vec<NodeId> = self
            .devices
            .iter()
            .filter(|(_, d)| d.is_stale(timeout, current_time))
            .map(|(id, _)| *id)
            .collect();

        let count = stale.len();
        for node_id in stale {
            if let Some(device) = self.devices.remove(&node_id) {
                self.address_map.remove(&device.address);
                self.last_processed.remove(&node_id);
            }
        }

        count
    }

    /// Clear all tracked devices
    pub fn clear(&mut self) {
        self.devices.clear();
        self.address_map.clear();
        self.last_processed.clear();
    }

    /// Find the best parent candidate
    ///
    /// Selects based on hierarchy level (prefer higher) and RSSI (prefer stronger).
    pub fn find_best_parent(&self, our_level: HierarchyLevel) -> Option<&TrackedDevice> {
        self.devices
            .values()
            .filter(|d| {
                d.beacon.hierarchy_level > our_level && d.connectable && !d.beacon.is_lite_node()
            })
            .max_by(|a, b| {
                // First compare hierarchy level
                match a.beacon.hierarchy_level.cmp(&b.beacon.hierarchy_level) {
                    core::cmp::Ordering::Equal => {
                        // Then compare RSSI
                        a.average_rssi().cmp(&b.average_rssi())
                    }
                    other => other,
                }
            })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_adv(node_id: u32, rssi: i8, level: HierarchyLevel) -> ParsedAdvertisement {
        let beacon = PeatBeacon::new(NodeId::new(node_id))
            .with_hierarchy_level(level)
            .with_battery(80);

        ParsedAdvertisement {
            address: format!("00:11:22:33:44:{:02X}", node_id as u8),
            rssi,
            beacon: Some(beacon),
            encrypted_service_data: None,
            local_name: Some(format!("PEAT-{:08X}", node_id)),
            tx_power: Some(0),
            connectable: true,
        }
    }

    #[test]
    fn test_scanner_process_advertisement() {
        let config = DiscoveryConfig::default();
        let mut scanner = Scanner::new(config);
        scanner.set_time_ms(1000);

        let adv = make_adv(0x12345678, -60, HierarchyLevel::Platform);
        assert!(scanner.process_advertisement(adv));
        assert_eq!(scanner.device_count(), 1);

        // Duplicate within dedup interval should be ignored
        scanner.set_time_ms(1100);
        let adv2 = make_adv(0x12345678, -65, HierarchyLevel::Platform);
        assert!(!scanner.process_advertisement(adv2));
        assert_eq!(scanner.device_count(), 1);
    }

    #[test]
    fn test_scan_filter_peat_only() {
        let filter = ScanFilter::peat_nodes();

        let peat_adv = make_adv(0x12345678, -60, HierarchyLevel::Platform);
        assert!(filter.matches(&peat_adv));

        let non_peat = ParsedAdvertisement {
            address: "AA:BB:CC:DD:EE:FF".to_string(),
            rssi: -50,
            beacon: None,
            encrypted_service_data: None,
            local_name: Some("Other Device".to_string()),
            tx_power: None,
            connectable: true,
        };
        assert!(!filter.matches(&non_peat));
    }

    #[test]
    fn test_scan_filter_rssi() {
        let filter = ScanFilter {
            peat_only: true,
            min_rssi: Some(-70),
            ..Default::default()
        };

        let strong = make_adv(0x11111111, -60, HierarchyLevel::Platform);
        assert!(filter.matches(&strong));

        let weak = make_adv(0x22222222, -80, HierarchyLevel::Platform);
        assert!(!filter.matches(&weak));
    }

    #[test]
    fn test_find_best_parent() {
        let config = DiscoveryConfig::default();
        let mut scanner = Scanner::new(config);
        scanner.set_time_ms(0);

        // Add a squad leader
        let squad = make_adv(0x11111111, -60, HierarchyLevel::Squad);
        scanner.process_advertisement(squad);

        // Add a platoon leader (higher hierarchy)
        scanner.set_time_ms(501); // Avoid dedup
        let platoon = make_adv(0x22222222, -70, HierarchyLevel::Platoon);
        scanner.process_advertisement(platoon);

        // Find parent for platform node
        let parent = scanner.find_best_parent(HierarchyLevel::Platform);
        assert!(parent.is_some());
        // Should prefer platoon (higher hierarchy) despite weaker signal
        assert_eq!(
            parent.unwrap().beacon.hierarchy_level,
            HierarchyLevel::Platoon
        );
    }

    #[test]
    fn test_devices_by_rssi() {
        let config = DiscoveryConfig::default();
        let mut scanner = Scanner::new(config);
        scanner.set_time_ms(0);

        scanner.process_advertisement(make_adv(0x11111111, -80, HierarchyLevel::Platform));
        scanner.set_time_ms(501);
        scanner.process_advertisement(make_adv(0x22222222, -50, HierarchyLevel::Platform));
        scanner.set_time_ms(1002);
        scanner.process_advertisement(make_adv(0x33333333, -70, HierarchyLevel::Platform));

        let sorted = scanner.devices_by_rssi();
        assert_eq!(sorted.len(), 3);
        assert_eq!(sorted[0].rssi, -50); // Strongest first
        assert_eq!(sorted[1].rssi, -70);
        assert_eq!(sorted[2].rssi, -80);
    }

    #[test]
    fn test_remove_stale() {
        let config = DiscoveryConfig::default();
        let mut scanner = Scanner::new(config);
        scanner.set_time_ms(0);

        scanner.process_advertisement(make_adv(0x11111111, -60, HierarchyLevel::Platform));
        assert_eq!(scanner.device_count(), 1);

        // Fast forward past timeout
        scanner.set_time_ms(35_000);
        let removed = scanner.remove_stale();
        assert_eq!(removed, 1);
        assert_eq!(scanner.device_count(), 0);
    }

    #[test]
    fn test_encrypted_beacon_scanning() {
        use crate::discovery::{mesh_id_to_bytes, EncryptedBeacon as EB};

        let config = DiscoveryConfig::default();
        let mut scanner = Scanner::new(config);
        scanner.set_time_ms(0);

        let beacon_key = BeaconKey::from_base(&[0x42; 32]);
        let mesh_id_bytes = mesh_id_to_bytes("TEST-MESH");
        let node_id = NodeId::new(0x12345678);

        // Configure scanner for encrypted beacons
        scanner.set_beacon_key(beacon_key.clone(), mesh_id_bytes);
        assert!(scanner.can_decrypt_beacons());

        // Create an encrypted beacon
        let encrypted_beacon = EB::new(node_id, 0x0F00, u8::from(HierarchyLevel::Squad), 85);
        let encrypted_data = encrypted_beacon.encrypt(&beacon_key, &mesh_id_bytes);

        // Create advertisement with encrypted data
        let adv = ParsedAdvertisement {
            address: "00:11:22:33:44:55".to_string(),
            rssi: -60,
            beacon: None,
            encrypted_service_data: Some(encrypted_data),
            local_name: Some("PEAT".to_string()),
            tx_power: None,
            connectable: true,
        };

        // Process advertisement
        assert!(scanner.process_advertisement(adv));
        assert_eq!(scanner.device_count(), 1);

        // Verify decrypted device
        let device = scanner.get_device(&node_id).unwrap();
        assert_eq!(device.beacon.node_id, node_id);
        assert_eq!(device.beacon.capabilities, 0x0F00);
        assert_eq!(device.beacon.hierarchy_level, HierarchyLevel::Squad);
        assert_eq!(device.beacon.battery_percent, 85);
    }

    #[test]
    fn test_encrypted_beacon_wrong_mesh_rejected() {
        use crate::discovery::{mesh_id_to_bytes, EncryptedBeacon as EB};

        let config = DiscoveryConfig::default();
        let mut scanner = Scanner::new(config);
        scanner.set_time_ms(0);

        let beacon_key = BeaconKey::from_base(&[0x42; 32]);
        let our_mesh_id = mesh_id_to_bytes("OUR-MESH");
        let other_mesh_id = mesh_id_to_bytes("OTHER-MESH");
        let node_id = NodeId::new(0x12345678);

        // Configure scanner for our mesh
        scanner.set_beacon_key(beacon_key.clone(), our_mesh_id);

        // Create encrypted beacon for a different mesh
        let encrypted_beacon = EB::new(node_id, 0x0F00, u8::from(HierarchyLevel::Squad), 85);
        let encrypted_data = encrypted_beacon.encrypt(&beacon_key, &other_mesh_id);

        let adv = ParsedAdvertisement {
            address: "00:11:22:33:44:55".to_string(),
            rssi: -60,
            beacon: None,
            encrypted_service_data: Some(encrypted_data),
            local_name: Some("PEAT".to_string()),
            tx_power: None,
            connectable: true,
        };

        // Should be rejected - wrong mesh
        assert!(!scanner.process_advertisement(adv));
        assert_eq!(scanner.device_count(), 0);
    }
}