aranet-core 0.2.0

Core BLE library for Aranet environmental sensors
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
//! Device discovery and scanning.
//!
//! This module provides functionality to scan for Aranet devices
//! using Bluetooth Low Energy.

use std::time::Duration;

use btleplug::api::{Central, Manager as _, Peripheral as _, ScanFilter};
use btleplug::platform::{Adapter, Manager, Peripheral, PeripheralId};
use tokio::sync::RwLock;
use tokio::time::sleep;
use tracing::{debug, info, warn};

/// Cached BLE manager — avoids creating a new D-Bus connection on every call.
///
/// Using `RwLock<Option<Manager>>` instead of `OnceCell` so the manager can
/// be re-created if the underlying D-Bus connection dies (e.g., dbus-daemon
/// restart, adapter reset).
static MANAGER: RwLock<Option<Manager>> = RwLock::const_new(None);

/// Get or create the shared BLE manager.
async fn shared_manager() -> Result<Manager> {
    // Fast path: read lock to return existing manager.
    {
        let guard = MANAGER.read().await;
        if let Some(m) = guard.as_ref() {
            return Ok(m.clone());
        }
    }
    // Slow path: create a new manager under write lock.
    let mut guard = MANAGER.write().await;
    // Double-check after acquiring write lock.
    if let Some(m) = guard.as_ref() {
        return Ok(m.clone());
    }
    let m = Manager::new().await?;
    *guard = Some(m.clone());
    Ok(m)
}

/// Reset the cached manager, forcing the next call to create a fresh one.
///
/// Call this when the D-Bus connection appears to be dead (e.g., adapter
/// enumeration fails with a connection error).
async fn reset_manager() {
    let mut guard = MANAGER.write().await;
    if guard.take().is_some() {
        warn!("BLE manager reset — next operation will create a new D-Bus connection");
    }
}

use crate::error::{Error, Result};
use crate::util::{create_identifier, format_peripheral_id};
use crate::uuid::{MANUFACTURER_ID, SAF_TEHNIKA_SERVICE_NEW, SAF_TEHNIKA_SERVICE_OLD};
use aranet_types::DeviceType;

/// Progress update for device finding operations.
#[derive(Debug, Clone)]
pub enum FindProgress {
    /// Found device in cache, no scan needed.
    CacheHit,
    /// Starting scan attempt.
    ScanAttempt {
        /// Current attempt number (1-based).
        attempt: u32,
        /// Total number of attempts.
        total: u32,
        /// Duration of this scan attempt.
        duration_secs: u64,
    },
    /// Device found on specific attempt.
    Found { attempt: u32 },
    /// Attempt failed, will retry.
    RetryNeeded { attempt: u32 },
}

/// Callback type for progress updates during device finding.
pub type ProgressCallback = Box<dyn Fn(FindProgress) + Send + Sync>;

/// Information about a discovered Aranet device.
#[derive(Debug, Clone)]
pub struct DiscoveredDevice {
    /// The device name (e.g., "Aranet4 12345").
    pub name: Option<String>,
    /// The peripheral ID for connecting.
    pub id: PeripheralId,
    /// The BLE address as a string (may be zeros on macOS, use `id` instead).
    pub address: String,
    /// A connection identifier (peripheral ID on macOS, address on other platforms).
    pub identifier: String,
    /// RSSI signal strength.
    pub rssi: Option<i16>,
    /// Device type if detected from advertisement.
    pub device_type: Option<DeviceType>,
    /// Whether the device is connectable.
    pub is_aranet: bool,
    /// Raw manufacturer data from advertisement (if available).
    pub manufacturer_data: Option<Vec<u8>>,
}

/// Options for scanning.
#[derive(Debug, Clone)]
pub struct ScanOptions {
    /// How long to scan for devices.
    pub duration: Duration,
    /// Only return devices that appear to be Aranet devices.
    pub filter_aranet_only: bool,
    /// Use targeted BLE scan filter for Aranet service UUIDs.
    /// This reduces noise from non-Aranet devices but may not work on all platforms.
    pub use_service_filter: bool,
}

impl Default for ScanOptions {
    fn default() -> Self {
        Self {
            duration: Duration::from_secs(5),
            filter_aranet_only: true,
            // Default to false for maximum compatibility - service filtering
            // may not work on all platforms/adapters
            use_service_filter: false,
        }
    }
}

impl ScanOptions {
    /// Create new scan options with defaults.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the scan duration.
    pub fn duration(mut self, duration: Duration) -> Self {
        self.duration = duration;
        self
    }

    /// Set scan duration in seconds.
    pub fn duration_secs(mut self, secs: u64) -> Self {
        self.duration = Duration::from_secs(secs);
        self
    }

    /// Set whether to filter for Aranet devices only.
    pub fn filter_aranet_only(mut self, filter: bool) -> Self {
        self.filter_aranet_only = filter;
        self
    }

    /// Scan for all BLE devices, not just Aranet.
    pub fn all_devices(self) -> Self {
        self.filter_aranet_only(false)
    }

    /// Enable or disable BLE service UUID filtering.
    ///
    /// When enabled, the BLE scan will filter for Aranet service UUIDs at the
    /// adapter level, reducing noise from non-Aranet devices. This may not
    /// work on all platforms or with all BLE adapters.
    ///
    /// Default: `false` (for maximum compatibility)
    pub fn use_service_filter(mut self, enable: bool) -> Self {
        self.use_service_filter = enable;
        self
    }

    /// Create optimized scan options for finding Aranet devices quickly.
    ///
    /// Uses service UUID filtering if available and a shorter scan duration.
    pub fn optimized() -> Self {
        Self {
            duration: Duration::from_secs(3),
            filter_aranet_only: true,
            use_service_filter: true,
        }
    }
}

/// Get the first available Bluetooth adapter.
pub async fn get_adapter() -> Result<Adapter> {
    use crate::error::DeviceNotFoundReason;

    // On Linux, register a BlueZ agent to handle authentication during service
    // discovery. Without this, BlueZ hangs when it encounters characteristics
    // that require authentication (e.g., Battery Level on Aranet devices).
    #[cfg(target_os = "linux")]
    crate::bluez_agent::ensure_agent();

    let manager = shared_manager().await?;
    let adapters = match manager.adapters().await {
        Ok(a) => a,
        Err(e) => {
            // The D-Bus connection may have died — reset the cached manager
            // so the next call creates a fresh connection.
            reset_manager().await;
            return Err(e.into());
        }
    };

    adapters
        .into_iter()
        .next()
        .ok_or(Error::DeviceNotFound(DeviceNotFoundReason::NoAdapter))
}

/// Scan for Aranet devices in range.
///
/// Returns a list of discovered devices, or an error if the scan failed.
/// An empty list indicates no devices were found (not an error).
///
/// # Errors
///
/// Returns an error if:
/// - No Bluetooth adapter is available
/// - Bluetooth is not enabled
/// - The scan could not be started or stopped
pub async fn scan_for_devices() -> Result<Vec<DiscoveredDevice>> {
    scan_with_options(ScanOptions::default()).await
}

/// Scan for devices with custom options.
pub async fn scan_with_options(options: ScanOptions) -> Result<Vec<DiscoveredDevice>> {
    let adapter = get_adapter().await?;
    scan_with_adapter(&adapter, options).await
}

/// Scan for devices with retry logic for flaky Bluetooth environments.
///
/// This function will retry the scan up to `max_retries` times if:
/// - The scan fails due to a Bluetooth error
/// - No devices are found (when `retry_on_empty` is true)
///
/// A delay is applied between retries, starting at 500ms and doubling each attempt.
///
/// # Arguments
///
/// * `options` - Scan options
/// * `max_retries` - Maximum number of retry attempts
/// * `retry_on_empty` - Whether to retry if no devices are found
///
/// # Example
///
/// ```ignore
/// use aranet_core::scan::{ScanOptions, scan_with_retry};
///
/// // Retry up to 3 times, including when no devices found
/// let devices = scan_with_retry(ScanOptions::default(), 3, true).await?;
/// ```
pub async fn scan_with_retry(
    options: ScanOptions,
    max_retries: u32,
    retry_on_empty: bool,
) -> Result<Vec<DiscoveredDevice>> {
    let mut attempt = 0;
    let mut delay = Duration::from_millis(500);

    loop {
        match scan_with_options(options.clone()).await {
            Ok(devices) if devices.is_empty() && retry_on_empty && attempt < max_retries => {
                attempt += 1;
                warn!(
                    "No devices found, retrying ({}/{})...",
                    attempt, max_retries
                );
                sleep(delay).await;
                delay = delay.saturating_mul(2).min(Duration::from_secs(5));
            }
            Ok(devices) => return Ok(devices),
            Err(e) if attempt < max_retries => {
                attempt += 1;
                warn!(
                    "Scan failed ({}), retrying ({}/{})...",
                    e, attempt, max_retries
                );
                sleep(delay).await;
                delay = delay.saturating_mul(2).min(Duration::from_secs(5));
            }
            Err(e) => return Err(e),
        }
    }
}

/// Scan for devices using a specific adapter.
pub async fn scan_with_adapter(
    adapter: &Adapter,
    options: ScanOptions,
) -> Result<Vec<DiscoveredDevice>> {
    info!(
        "Starting BLE scan for {} seconds (service_filter={})...",
        options.duration.as_secs(),
        options.use_service_filter
    );

    // Create scan filter - optionally filter for Aranet service UUIDs
    let scan_filter = if options.use_service_filter {
        ScanFilter {
            services: vec![SAF_TEHNIKA_SERVICE_NEW, SAF_TEHNIKA_SERVICE_OLD],
        }
    } else {
        ScanFilter::default()
    };

    // Start scanning
    adapter.start_scan(scan_filter).await?;

    // Wait for the scan duration
    sleep(options.duration).await;

    // Stop scanning
    adapter.stop_scan().await?;

    // Get discovered peripherals
    let peripherals = adapter.peripherals().await?;
    let mut discovered = Vec::new();

    for peripheral in peripherals {
        match process_peripheral(&peripheral, options.filter_aranet_only).await {
            Ok(Some(device)) => {
                info!("Found Aranet device: {:?}", device.name);
                discovered.push(device);
            }
            Ok(None) => {
                // Not an Aranet device or filtered out
            }
            Err(e) => {
                debug!("Error processing peripheral: {}", e);
            }
        }
    }

    info!("Scan complete. Found {} device(s)", discovered.len());
    Ok(discovered)
}

/// Process a peripheral and determine if it's an Aranet device.
async fn process_peripheral(
    peripheral: &Peripheral,
    filter_aranet_only: bool,
) -> Result<Option<DiscoveredDevice>> {
    let properties = peripheral.properties().await?;
    let properties = match properties {
        Some(p) => p,
        None => return Ok(None),
    };

    let id = peripheral.id();
    let address = properties.address.to_string();
    let name = properties.local_name.clone();
    let rssi = properties.rssi;

    // Check if this is an Aranet device
    let is_aranet = is_aranet_device(&properties);

    if filter_aranet_only && !is_aranet {
        return Ok(None);
    }

    // Try to determine device type from name
    let device_type = name.as_ref().and_then(|n| DeviceType::from_name(n));

    // Get manufacturer data if available
    let manufacturer_data = properties.manufacturer_data.get(&MANUFACTURER_ID).cloned();

    // Create identifier: use peripheral ID string on macOS (where address is 00:00:00:00:00:00)
    // On other platforms, use the address
    let identifier = create_identifier(&address, &id);

    Ok(Some(DiscoveredDevice {
        name,
        id,
        address,
        identifier,
        rssi,
        device_type,
        is_aranet,
        manufacturer_data,
    }))
}

/// Check if a peripheral is an Aranet device based on its properties.
fn is_aranet_device(properties: &btleplug::api::PeripheralProperties) -> bool {
    // Check manufacturer data for Aranet manufacturer ID
    if properties.manufacturer_data.contains_key(&MANUFACTURER_ID) {
        return true;
    }

    // Check service UUIDs for Aranet services
    for service_uuid in properties.service_data.keys() {
        if *service_uuid == SAF_TEHNIKA_SERVICE_NEW || *service_uuid == SAF_TEHNIKA_SERVICE_OLD {
            return true;
        }
    }

    // Check advertised services
    for service_uuid in &properties.services {
        if *service_uuid == SAF_TEHNIKA_SERVICE_NEW || *service_uuid == SAF_TEHNIKA_SERVICE_OLD {
            return true;
        }
    }

    // Check device name for Aranet
    if let Some(name) = &properties.local_name {
        let name_lower = name.to_lowercase();
        if name_lower.contains("aranet") {
            return true;
        }
    }

    false
}

/// Find a specific device by name or address.
pub async fn find_device(identifier: &str) -> Result<(Adapter, Peripheral)> {
    find_device_with_options(identifier, ScanOptions::default()).await
}

/// Find a specific device by name or address with custom options.
///
/// This function uses a retry strategy to improve reliability:
/// 1. First checks if the device is already known (cached from previous scans)
/// 2. Performs up to 3 scan attempts with increasing durations
///
/// This helps with BLE reliability issues where devices may not appear
/// on every scan due to advertisement timing.
pub async fn find_device_with_options(
    identifier: &str,
    options: ScanOptions,
) -> Result<(Adapter, Peripheral)> {
    find_device_with_progress(identifier, options, None).await
}

/// Find a specific device using a pre-existing adapter.
///
/// This avoids creating a new btleplug `Manager` (and D-Bus connection) on
/// every call.  The caller is responsible for keeping the `Adapter` alive.
pub async fn find_device_with_adapter(
    adapter: &Adapter,
    identifier: &str,
    options: ScanOptions,
) -> Result<Peripheral> {
    find_device_with_adapter_progress(adapter, identifier, options, None).await
}

/// Find a specific device using a pre-existing adapter, with progress callback.
pub async fn find_device_with_adapter_progress(
    adapter: &Adapter,
    identifier: &str,
    options: ScanOptions,
    progress: Option<ProgressCallback>,
) -> Result<Peripheral> {
    let identifier_lower = identifier.to_lowercase();

    info!("Looking for device: {}", identifier);

    if let Some(peripheral) = find_peripheral_by_identifier(adapter, &identifier_lower).await? {
        info!("Found device in cache (no scan needed)");
        if let Some(ref cb) = progress {
            cb(FindProgress::CacheHit);
        }
        return Ok(peripheral);
    }

    let max_attempts: u32 = 3;
    let base_duration = options.duration.as_millis() as u64 / 2;
    let base_duration = Duration::from_millis(base_duration.max(2000));

    for attempt in 1..=max_attempts {
        let scan_duration = base_duration * attempt;
        let duration_secs = scan_duration.as_secs();

        info!(
            "Scan attempt {}/{} ({}s)...",
            attempt, max_attempts, duration_secs
        );

        if let Some(ref cb) = progress {
            cb(FindProgress::ScanAttempt {
                attempt,
                total: max_attempts,
                duration_secs,
            });
        }

        adapter.start_scan(ScanFilter::default()).await?;
        sleep(scan_duration).await;
        adapter.stop_scan().await?;

        if let Some(peripheral) = find_peripheral_by_identifier(adapter, &identifier_lower).await? {
            info!("Found device on attempt {}", attempt);
            if let Some(ref cb) = progress {
                cb(FindProgress::Found { attempt });
            }
            return Ok(peripheral);
        }

        if attempt < max_attempts {
            warn!("Device not found, retrying...");
            if let Some(ref cb) = progress {
                cb(FindProgress::RetryNeeded { attempt });
            }
        }
    }

    warn!(
        "Device not found after {} attempts: {}",
        max_attempts, identifier
    );
    Err(Error::device_not_found(identifier))
}

/// Find a specific device with progress callback for UI feedback.
///
/// The progress callback is called with updates about the search progress,
/// including cache hits, scan attempts, and retry information.
pub async fn find_device_with_progress(
    identifier: &str,
    options: ScanOptions,
    progress: Option<ProgressCallback>,
) -> Result<(Adapter, Peripheral)> {
    let adapter = get_adapter().await?;
    let peripheral =
        find_device_with_adapter_progress(&adapter, identifier, options, progress).await?;
    Ok((adapter, peripheral))
}

/// Search through known peripherals to find one matching the identifier.
async fn find_peripheral_by_identifier(
    adapter: &Adapter,
    identifier_lower: &str,
) -> Result<Option<Peripheral>> {
    let peripherals = adapter.peripherals().await?;

    for peripheral in peripherals {
        if let Ok(Some(props)) = peripheral.properties().await {
            let address = props.address.to_string().to_lowercase();
            let peripheral_id = format_peripheral_id(&peripheral.id()).to_lowercase();

            // Check peripheral ID match (macOS uses UUIDs)
            if peripheral_id.contains(identifier_lower) {
                debug!("Matched by peripheral ID: {}", peripheral_id);
                return Ok(Some(peripheral));
            }

            // Check address match (Linux/Windows use MAC addresses)
            if address != "00:00:00:00:00:00"
                && (address == identifier_lower
                    || address.replace(':', "") == identifier_lower.replace(':', ""))
            {
                debug!("Matched by address: {}", address);
                return Ok(Some(peripheral));
            }

            // Check name match (partial match supported)
            if let Some(name) = &props.local_name
                && name.to_lowercase().contains(identifier_lower)
            {
                debug!("Matched by name: {}", name);
                return Ok(Some(peripheral));
            }
        }
    }

    Ok(None)
}

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

    // ==================== ScanOptions Tests ====================

    #[test]
    fn test_scan_options_default() {
        let options = ScanOptions::default();
        assert_eq!(options.duration, Duration::from_secs(5));
        assert!(options.filter_aranet_only);
    }

    #[test]
    fn test_scan_options_new() {
        let options = ScanOptions::new();
        assert_eq!(options.duration, Duration::from_secs(5));
        assert!(options.filter_aranet_only);
    }

    #[test]
    fn test_scan_options_duration() {
        let options = ScanOptions::new().duration(Duration::from_secs(10));
        assert_eq!(options.duration, Duration::from_secs(10));
    }

    #[test]
    fn test_scan_options_duration_secs() {
        let options = ScanOptions::new().duration_secs(15);
        assert_eq!(options.duration, Duration::from_secs(15));
    }

    #[test]
    fn test_scan_options_filter_aranet_only() {
        let options = ScanOptions::new().filter_aranet_only(false);
        assert!(!options.filter_aranet_only);

        let options = ScanOptions::new().filter_aranet_only(true);
        assert!(options.filter_aranet_only);
    }

    #[test]
    fn test_scan_options_all_devices() {
        let options = ScanOptions::new().all_devices();
        assert!(!options.filter_aranet_only);
    }

    #[test]
    fn test_scan_options_chaining() {
        let options = ScanOptions::new()
            .duration_secs(20)
            .filter_aranet_only(false);

        assert_eq!(options.duration, Duration::from_secs(20));
        assert!(!options.filter_aranet_only);
    }

    #[test]
    fn test_scan_options_clone() {
        let options1 = ScanOptions::new().duration_secs(8);
        let options2 = options1.clone();

        assert_eq!(options1.duration, options2.duration);
        assert_eq!(options1.filter_aranet_only, options2.filter_aranet_only);
    }

    #[test]
    fn test_scan_options_debug() {
        let options = ScanOptions::new();
        let debug = format!("{:?}", options);
        assert!(debug.contains("ScanOptions"));
        assert!(debug.contains("duration"));
        assert!(debug.contains("filter_aranet_only"));
    }

    // ==================== FindProgress Tests ====================

    #[test]
    fn test_find_progress_cache_hit() {
        let progress = FindProgress::CacheHit;
        let debug = format!("{:?}", progress);
        assert!(debug.contains("CacheHit"));
    }

    #[test]
    fn test_find_progress_scan_attempt() {
        let progress = FindProgress::ScanAttempt {
            attempt: 2,
            total: 3,
            duration_secs: 5,
        };

        if let FindProgress::ScanAttempt {
            attempt,
            total,
            duration_secs,
        } = progress
        {
            assert_eq!(attempt, 2);
            assert_eq!(total, 3);
            assert_eq!(duration_secs, 5);
        } else {
            panic!("Expected ScanAttempt variant");
        }
    }

    #[test]
    fn test_find_progress_found() {
        let progress = FindProgress::Found { attempt: 1 };
        assert!(matches!(progress, FindProgress::Found { attempt: 1 }));
    }

    #[test]
    fn test_find_progress_retry_needed() {
        let progress = FindProgress::RetryNeeded { attempt: 2 };
        assert!(matches!(progress, FindProgress::RetryNeeded { attempt: 2 }));
    }

    #[test]
    fn test_find_progress_clone() {
        let progress1 = FindProgress::ScanAttempt {
            attempt: 1,
            total: 3,
            duration_secs: 4,
        };
        let progress2 = progress1.clone();

        assert!(matches!(
            (&progress1, &progress2),
            (
                FindProgress::ScanAttempt {
                    attempt: 1,
                    total: 3,
                    duration_secs: 4,
                },
                FindProgress::ScanAttempt {
                    attempt: 1,
                    total: 3,
                    duration_secs: 4,
                },
            )
        ));
    }

    // ==================== DiscoveredDevice Tests ====================
    // Note: DiscoveredDevice tests are removed because PeripheralId from btleplug
    // has platform-specific implementations that cannot be easily mocked in tests.
    // - macOS: PeripheralId wraps a UUID
    // - Linux: PeripheralId wraps bluez_async::DeviceId (not directly accessible)
    // - Windows: PeripheralId wraps a u64
    //
    // The DiscoveredDevice struct derives Clone and Debug, so these traits are
    // guaranteed to work correctly by the compiler.
}