1use std::ops::ControlFlow;
12use std::sync::{Arc, LazyLock};
13use std::time::Duration;
14
15use btleplug::api::{Central, Manager as _, Peripheral as _, ScanFilter};
16use btleplug::platform::{Adapter, Manager, Peripheral, PeripheralId};
17use tokio::runtime::Handle;
18use tokio::sync::RwLock;
19use tokio::time::sleep;
20use tokio_util::sync::CancellationToken;
21use tracing::{debug, info, warn};
22
23static MANAGER: RwLock<Option<Manager>> = RwLock::const_new(None);
29
30async fn shared_manager() -> Result<Manager> {
32 {
34 let guard = MANAGER.read().await;
35 if let Some(m) = guard.as_ref() {
36 return Ok(m.clone());
37 }
38 }
39 let mut guard = MANAGER.write().await;
41 if let Some(m) = guard.as_ref() {
43 return Ok(m.clone());
44 }
45 let m = crate::runtime::run(Manager::new()).await??;
50 *guard = Some(m.clone());
51 Ok(m)
52}
53
54async fn reset_manager() {
59 let mut guard = MANAGER.write().await;
60 if guard.take().is_some() {
61 warn!("BLE manager reset — next operation will create a new D-Bus connection");
62 }
63}
64
65use crate::error::{Error, Result};
66use crate::util::{create_identifier, peripheral_name};
67use crate::uuid::{MANUFACTURER_ID, SAF_TEHNIKA_SERVICE_NEW, SAF_TEHNIKA_SERVICE_OLD};
68use aranet_types::DeviceType;
69
70#[derive(Debug, Clone)]
72pub enum FindProgress {
73 CacheHit,
77 ScanAttempt {
79 attempt: u32,
81 total: u32,
83 duration_secs: u64,
85 },
86 Found { attempt: u32 },
88 RetryNeeded { attempt: u32 },
90}
91
92pub type ProgressCallback = Box<dyn Fn(FindProgress) + Send + Sync>;
94
95#[derive(Debug, Clone)]
97pub struct DiscoveredDevice {
98 pub name: Option<String>,
100 pub id: PeripheralId,
102 pub address: String,
104 pub identifier: String,
106 pub rssi: Option<i16>,
108 pub device_type: Option<DeviceType>,
110 pub is_aranet: bool,
112 pub manufacturer_data: Option<Vec<u8>>,
114}
115
116#[derive(Debug, Clone)]
118pub struct ScanOptions {
119 pub duration: Duration,
121 pub filter_aranet_only: bool,
123 pub use_service_filter: bool,
126}
127
128impl Default for ScanOptions {
129 fn default() -> Self {
130 Self {
131 duration: Duration::from_secs(5),
132 filter_aranet_only: true,
133 use_service_filter: false,
136 }
137 }
138}
139
140impl ScanOptions {
141 pub fn new() -> Self {
143 Self::default()
144 }
145
146 pub fn duration(mut self, duration: Duration) -> Self {
148 self.duration = duration;
149 self
150 }
151
152 pub fn duration_secs(mut self, secs: u64) -> Self {
154 self.duration = Duration::from_secs(secs);
155 self
156 }
157
158 pub fn filter_aranet_only(mut self, filter: bool) -> Self {
160 self.filter_aranet_only = filter;
161 self
162 }
163
164 pub fn all_devices(self) -> Self {
166 self.filter_aranet_only(false)
167 }
168
169 pub fn use_service_filter(mut self, enable: bool) -> Self {
177 self.use_service_filter = enable;
178 self
179 }
180
181 pub fn optimized() -> Self {
185 Self {
186 duration: Duration::from_secs(3),
187 filter_aranet_only: true,
188 use_service_filter: true,
189 }
190 }
191}
192
193static ADAPTER: RwLock<Option<Adapter>> = RwLock::const_new(None);
208
209pub async fn get_adapter() -> Result<Adapter> {
216 if cfg!(target_os = "macos") {
217 cached_adapter().await
218 } else {
219 crate::runtime::run(create_adapter()).await?
220 }
221}
222
223async fn cached_adapter() -> Result<Adapter> {
224 let cached = ADAPTER.read().await.clone();
225 if let Some(adapter) = cached
226 && adapter_thread_is_running(&adapter).await
227 {
228 return Ok(adapter);
229 }
230 let mut guard = ADAPTER.write().await;
231 if let Some(adapter) = guard.as_ref() {
232 if adapter_thread_is_running(adapter).await {
233 return Ok(adapter.clone());
234 }
235 warn!("CoreBluetooth adapter thread has stopped; creating a new adapter");
236 }
237 let adapter = crate::runtime::run(create_adapter()).await??;
238 *guard = Some(adapter.clone());
239 Ok(adapter)
240}
241
242async fn adapter_thread_is_running(adapter: &Adapter) -> bool {
255 let adapter = adapter.clone();
256 let state = crate::runtime::run(async move {
259 tokio::time::timeout(Duration::from_secs(2), adapter.adapter_state()).await
260 })
261 .await;
262 match state {
263 Ok(Ok(Err(e))) => {
264 debug!("Cached Bluetooth adapter is unusable: {e}");
265 false
266 }
267 _ => true,
268 }
269}
270
271async fn create_adapter() -> Result<Adapter> {
272 use crate::error::DeviceNotFoundReason;
273
274 let manager = shared_manager().await?;
275 let adapters = match manager.adapters().await {
276 Ok(a) => a,
277 Err(e) => {
278 reset_manager().await;
281 return Err(e.into());
282 }
283 };
284
285 adapters
286 .into_iter()
287 .next()
288 .ok_or(Error::DeviceNotFound(DeviceNotFoundReason::NoAdapter))
289}
290
291pub(crate) trait ScanControl: Clone + Send + Sync + 'static {
294 fn start(&self, filter: ScanFilter) -> impl Future<Output = Result<()>> + Send;
297
298 fn stop(&self) -> impl Future<Output = Result<()>> + Send;
300}
301
302impl ScanControl for Adapter {
303 async fn start(&self, filter: ScanFilter) -> Result<()> {
304 Central::start_scan(self, filter).await?;
305 Ok(())
306 }
307
308 async fn stop(&self) -> Result<()> {
309 Central::stop_scan(self).await?;
310 Ok(())
311 }
312}
313
314#[derive(Clone, Default)]
322pub(crate) struct ScanLock(Arc<tokio::sync::Mutex<()>>);
323
324impl ScanLock {
325 pub(crate) async fn acquire(&self) -> ScanPermit {
327 ScanPermit {
328 _guard: Arc::clone(&self.0).lock_owned().await,
329 }
330 }
331}
332
333pub(crate) struct ScanPermit {
341 _guard: tokio::sync::OwnedMutexGuard<()>,
342}
343
344static SCAN_LOCK: LazyLock<ScanLock> = LazyLock::new(ScanLock::default);
345
346pub(crate) fn scan_lock() -> &'static ScanLock {
349 &SCAN_LOCK
350}
351
352async fn scan_window<S: ScanControl>(
360 runtime: &Handle,
361 scanner: &S,
362 permit: ScanPermit,
363 filter: ScanFilter,
364 duration: Duration,
365) -> Result<()> {
366 let scanner = scanner.clone();
367 let cancel = CancellationToken::new();
368 let _end_early_on_drop = cancel.clone().drop_guard();
370 let window = runtime.spawn(async move {
371 let _permit = permit; if cancel.is_cancelled() {
373 return Ok(());
374 }
375 scanner.start(filter).await?; let _ = cancel.run_until_cancelled(sleep(duration)).await;
377 let stopped = scanner.stop().await;
378 if let Err(e) = &stopped {
379 warn!("Failed to stop the Bluetooth scan: {e}");
381 }
382 stopped
383 });
384 window.await.map_err(std::io::Error::from)?
385}
386
387pub(crate) async fn run_scan<S: ScanControl>(
391 scanner: &S,
392 permit: ScanPermit,
393 filter: ScanFilter,
394 duration: Duration,
395) -> Result<()> {
396 scan_window(
397 &crate::runtime::handle()?,
398 scanner,
399 permit,
400 filter,
401 duration,
402 )
403 .await
404}
405
406pub async fn scan_for_devices() -> Result<Vec<DiscoveredDevice>> {
418 scan_with_options(ScanOptions::default()).await
419}
420
421pub async fn scan_with_options(options: ScanOptions) -> Result<Vec<DiscoveredDevice>> {
423 let adapter = get_adapter().await?;
424 scan_with_adapter(&adapter, options).await
425}
426
427pub async fn scan_with_retry(
450 options: ScanOptions,
451 max_retries: u32,
452 retry_on_empty: bool,
453) -> Result<Vec<DiscoveredDevice>> {
454 let mut attempt = 0;
455 let mut delay = Duration::from_millis(500);
456
457 loop {
458 match scan_with_options(options.clone()).await {
459 Ok(devices) if devices.is_empty() && retry_on_empty && attempt < max_retries => {
460 attempt += 1;
461 warn!(
462 "No devices found, retrying ({}/{})...",
463 attempt, max_retries
464 );
465 sleep(delay).await;
466 delay = delay.saturating_mul(2).min(Duration::from_secs(5));
467 }
468 Ok(devices) => return Ok(devices),
469 Err(e) if attempt < max_retries => {
470 attempt += 1;
471 warn!(
472 "Scan failed ({}), retrying ({}/{})...",
473 e, attempt, max_retries
474 );
475 sleep(delay).await;
476 delay = delay.saturating_mul(2).min(Duration::from_secs(5));
477 }
478 Err(e) => return Err(e),
479 }
480 }
481}
482
483pub async fn scan_with_adapter(
485 adapter: &Adapter,
486 options: ScanOptions,
487) -> Result<Vec<DiscoveredDevice>> {
488 info!(
489 "Starting BLE scan for {} seconds (service_filter={})...",
490 options.duration.as_secs(),
491 options.use_service_filter
492 );
493
494 let scan_filter = if options.use_service_filter {
496 aranet_service_filter()
497 } else {
498 ScanFilter::default()
499 };
500
501 let permit = scan_lock().acquire().await;
502 run_scan(adapter, permit, scan_filter, options.duration).await?;
503
504 let peripherals = adapter.peripherals().await?;
506 let mut discovered = Vec::new();
507
508 for peripheral in peripherals {
509 match process_peripheral(&peripheral, options.filter_aranet_only).await {
510 Ok(Some(device)) => {
511 info!("Found Aranet device: {:?}", device.name);
512 discovered.push(device);
513 }
514 Ok(None) => {
515 }
517 Err(e) => {
518 debug!("Error processing peripheral: {}", e);
519 }
520 }
521 }
522
523 info!("Scan complete. Found {} device(s)", discovered.len());
524 Ok(discovered)
525}
526
527async fn process_peripheral(
529 peripheral: &Peripheral,
530 filter_aranet_only: bool,
531) -> Result<Option<DiscoveredDevice>> {
532 let properties = peripheral.properties().await?;
533 let properties = match properties {
534 Some(p) => p,
535 None => return Ok(None),
536 };
537
538 let id = peripheral.id();
539 let address = properties.address.to_string();
540 let name = peripheral_name(&properties).map(str::to_owned);
541 let rssi = properties.rssi;
542
543 let is_aranet = is_aranet_device(&properties);
545
546 if filter_aranet_only && !is_aranet {
547 return Ok(None);
548 }
549
550 let device_type = name.as_ref().and_then(|n| DeviceType::from_name(n));
552
553 let manufacturer_data = properties.manufacturer_data.get(&MANUFACTURER_ID).cloned();
555
556 let identifier = create_identifier(&address, &id);
559
560 Ok(Some(DiscoveredDevice {
561 name,
562 id,
563 address,
564 identifier,
565 rssi,
566 device_type,
567 is_aranet,
568 manufacturer_data,
569 }))
570}
571
572fn is_aranet_device(properties: &btleplug::api::PeripheralProperties) -> bool {
574 if properties.manufacturer_data.contains_key(&MANUFACTURER_ID) {
576 return true;
577 }
578
579 for service_uuid in properties.service_data.keys() {
581 if *service_uuid == SAF_TEHNIKA_SERVICE_NEW || *service_uuid == SAF_TEHNIKA_SERVICE_OLD {
582 return true;
583 }
584 }
585
586 for service_uuid in &properties.services {
588 if *service_uuid == SAF_TEHNIKA_SERVICE_NEW || *service_uuid == SAF_TEHNIKA_SERVICE_OLD {
589 return true;
590 }
591 }
592
593 if let Some(name) = peripheral_name(properties) {
595 let name_lower = name.to_lowercase();
596 if name_lower.contains("aranet") {
597 return true;
598 }
599 }
600
601 false
602}
603
604fn aranet_service_filter() -> ScanFilter {
607 ScanFilter {
608 services: vec![SAF_TEHNIKA_SERVICE_NEW, SAF_TEHNIKA_SERVICE_OLD],
609 }
610}
611
612const FILTER_SEARCH_WINDOWS: bool = cfg!(target_os = "macos");
646
647fn search_filter(aranet_only: bool) -> ScanFilter {
651 if aranet_only {
652 aranet_service_filter()
653 } else {
654 ScanFilter::default()
655 }
656}
657
658fn after_missed_scan(
671 query: &str,
672 similar: Vec<String>,
673 attempt: u32,
674 max_attempts: u32,
675) -> ControlFlow<Error> {
676 use crate::error::DeviceNotFoundReason;
677
678 if !similar.is_empty() {
679 return ControlFlow::Break(Error::DeviceNotFound(DeviceNotFoundReason::NoExactMatch {
680 identifier: query.to_string(),
681 similar,
682 }));
683 }
684 if attempt < max_attempts {
685 return ControlFlow::Continue(());
686 }
687 ControlFlow::Break(Error::device_not_found(query))
688}
689
690pub async fn find_device(identifier: &str) -> Result<(Adapter, Peripheral)> {
724 find_device_with_options(identifier, ScanOptions::default()).await
725}
726
727pub async fn find_device_with_options(
743 identifier: &str,
744 options: ScanOptions,
745) -> Result<(Adapter, Peripheral)> {
746 find_device_with_progress(identifier, options, None).await
747}
748
749pub async fn find_device_with_adapter(
757 adapter: &Adapter,
758 identifier: &str,
759 options: ScanOptions,
760) -> Result<Peripheral> {
761 find_device_with_adapter_progress(adapter, identifier, options, None).await
762}
763
764pub async fn find_device_with_adapter_progress(
769 adapter: &Adapter,
770 identifier: &str,
771 options: ScanOptions,
772 progress: Option<ProgressCallback>,
773) -> Result<Peripheral> {
774 let query = parse_query(identifier)?;
775
776 info!("Looking for device: {}", identifier);
777
778 if let Search::Found(peripheral) = search_known_peripherals(adapter, query).await? {
779 info!("Found device in cache (no scan needed)");
780 if let Some(ref cb) = progress {
781 cb(FindProgress::CacheHit);
782 }
783 return Ok(peripheral);
784 }
785
786 let max_attempts: u32 = 3;
787 let base_duration = options.duration.as_millis() as u64 / 2;
788 let base_duration = Duration::from_millis(base_duration.max(2000));
789
790 let mut attempt = 0;
793 loop {
794 attempt += 1;
795 let scan_duration = base_duration * attempt;
796 let duration_secs = scan_duration.as_secs();
797
798 let permit = scan_lock().acquire().await;
799 if let Search::Found(peripheral) = search_known_peripherals(adapter, query).await? {
801 info!("Found device while waiting to scan");
802 if let Some(ref cb) = progress {
803 cb(FindProgress::CacheHit);
804 }
805 return Ok(peripheral);
806 }
807
808 info!(
809 "Scan attempt {}/{} ({}s)...",
810 attempt, max_attempts, duration_secs
811 );
812 let filter = search_filter(FILTER_SEARCH_WINDOWS);
813 debug!(
814 "Scan attempt {}/{} ({}s, {})",
815 attempt,
816 max_attempts,
817 duration_secs,
818 if filter.services.is_empty() {
819 "all devices"
820 } else {
821 "Aranet sensors only"
822 }
823 );
824
825 if let Some(ref cb) = progress {
826 cb(FindProgress::ScanAttempt {
827 attempt,
828 total: max_attempts,
829 duration_secs,
830 });
831 }
832
833 run_scan(adapter, permit, filter, scan_duration).await?;
834
835 let similar = match search_known_peripherals(adapter, query).await? {
836 Search::Found(peripheral) => {
837 info!("Found device on attempt {}", attempt);
838 if let Some(ref cb) = progress {
839 cb(FindProgress::Found { attempt });
840 }
841 return Ok(peripheral);
842 }
843 Search::Missing { similar } => similar,
844 };
845
846 match after_missed_scan(query, similar, attempt, max_attempts) {
847 ControlFlow::Break(error) => {
848 warn!(
849 "Device not found after {} of {} attempts: {}",
850 attempt, max_attempts, identifier
851 );
852 return Err(error);
853 }
854 ControlFlow::Continue(()) => {
855 warn!("Device not found, retrying...");
856 if let Some(ref cb) = progress {
857 cb(FindProgress::RetryNeeded { attempt });
858 }
859 }
860 }
861 }
862}
863
864pub async fn find_device_with_progress(
872 identifier: &str,
873 options: ScanOptions,
874 progress: Option<ProgressCallback>,
875) -> Result<(Adapter, Peripheral)> {
876 parse_query(identifier)?;
878 let adapter = get_adapter().await?;
879 let peripheral =
880 find_device_with_adapter_progress(&adapter, identifier, options, progress).await?;
881 Ok((adapter, peripheral))
882}
883
884const UNKNOWN_ADDRESS: &str = "00:00:00:00:00:00";
887
888#[derive(Debug, Clone, PartialEq, Eq)]
890struct KnownPeripheral {
891 identifier: String,
894 peripheral_id: String,
898 address: String,
900 name: Option<String>,
904}
905
906#[derive(Debug, PartialEq, Eq)]
908enum Lookup {
909 Found(usize),
911 Ambiguous(Vec<usize>),
913 NotFound { similar: Vec<usize> },
916}
917
918fn parse_query(identifier: &str) -> Result<&str> {
921 let query = identifier.trim();
922 if query.is_empty() {
923 return Err(Error::invalid_config("device identifier is empty"));
924 }
925 Ok(query)
926}
927
928fn lookup(query: &str, known: &[KnownPeripheral]) -> Lookup {
948 let query = query.to_lowercase();
949 let bare_query = query.replace(':', "");
950
951 let by_identifier = matching(known, |peripheral| {
952 peripheral.identifier.to_lowercase() == query
953 || peripheral.peripheral_id.to_lowercase() == query
954 || (peripheral.address != UNKNOWN_ADDRESS
955 && peripheral.address.to_lowercase().replace(':', "") == bare_query)
956 });
957 if let Some(found) = decide(by_identifier) {
958 return found;
959 }
960
961 let by_name = matching(known, |peripheral| {
962 peripheral
963 .name
964 .as_deref()
965 .is_some_and(|name| name_matches(name, &query))
966 });
967 if let Some(found) = decide(by_name) {
968 return found;
969 }
970
971 let mut similar = matching(known, |peripheral| {
972 peripheral.name.as_deref().is_some_and(|name| {
973 let name = name.to_lowercase();
974 name.contains("aranet") && name.contains(&query)
975 })
976 });
977 similar.sort_by_key(|&index| (&known[index].name, &known[index].identifier));
978 Lookup::NotFound { similar }
979}
980
981fn matching(known: &[KnownPeripheral], predicate: impl Fn(&KnownPeripheral) -> bool) -> Vec<usize> {
983 known
984 .iter()
985 .enumerate()
986 .filter_map(|(index, peripheral)| predicate(peripheral).then_some(index))
987 .collect()
988}
989
990fn decide(indices: Vec<usize>) -> Option<Lookup> {
992 match indices.len() {
993 0 => None,
994 1 => Some(Lookup::Found(indices[0])),
995 _ => Some(Lookup::Ambiguous(indices)),
996 }
997}
998
999fn name_matches(name: &str, query: &str) -> bool {
1002 name.trim().to_lowercase() == query
1003}
1004
1005#[derive(Debug, PartialEq, Eq)]
1007enum Search<T> {
1008 Found(T),
1010 Missing { similar: Vec<String> },
1013}
1014
1015fn resolve(query: &str, known: &[KnownPeripheral]) -> Result<Search<usize>> {
1022 use crate::error::DeviceNotFoundReason;
1023
1024 match lookup(query, known) {
1025 Lookup::Found(index) => Ok(Search::Found(index)),
1026 Lookup::Ambiguous(indices) => {
1027 let mut candidates: Vec<String> = indices
1028 .iter()
1029 .map(|&index| {
1030 let device = &known[index];
1031 let name = device.name.as_deref().unwrap_or("unnamed");
1032 format!("{name} ({})", device.identifier)
1033 })
1034 .collect();
1035 candidates.sort();
1036 Err(Error::DeviceNotFound(DeviceNotFoundReason::Ambiguous {
1037 identifier: query.to_string(),
1038 candidates,
1039 }))
1040 }
1041 Lookup::NotFound { similar } => {
1042 let mut names: Vec<String> = similar
1043 .iter()
1044 .filter_map(|&index| known[index].name.as_deref())
1045 .map(|name| name.trim().to_string())
1046 .collect();
1047 names.sort();
1048 names.dedup();
1049 Ok(Search::Missing { similar: names })
1050 }
1051 }
1052}
1053
1054async fn search_known_peripherals(adapter: &Adapter, query: &str) -> Result<Search<Peripheral>> {
1057 let mut peripherals = Vec::new();
1058 let mut known = Vec::new();
1059 for peripheral in adapter.peripherals().await? {
1060 if let Ok(Some(props)) = peripheral.properties().await {
1061 let id = peripheral.id();
1062 let address = props.address.to_string();
1063 known.push(KnownPeripheral {
1064 identifier: create_identifier(&address, &id),
1065 peripheral_id: id.to_string(),
1066 address,
1067 name: peripheral_name(&props).map(str::to_owned),
1068 });
1069 peripherals.push(peripheral);
1070 }
1071 }
1072
1073 match resolve(query, &known)? {
1074 Search::Found(index) => {
1075 let device = &known[index];
1076 debug!("Matched {:?} ({})", device.name, device.identifier);
1077 Ok(Search::Found(peripherals.swap_remove(index)))
1078 }
1079 Search::Missing { similar } => Ok(Search::Missing { similar }),
1080 }
1081}
1082
1083#[cfg(test)]
1084mod tests {
1085 use super::*;
1086
1087 use std::sync::atomic::{AtomicBool, Ordering};
1088
1089 use futures::FutureExt;
1090
1091 use crate::error::DeviceNotFoundReason;
1092 use crate::test_support::within;
1093
1094 #[test]
1097 fn test_scan_options_default() {
1098 let options = ScanOptions::default();
1099 assert_eq!(options.duration, Duration::from_secs(5));
1100 assert!(options.filter_aranet_only);
1101 }
1102
1103 #[test]
1104 fn test_scan_options_new() {
1105 let options = ScanOptions::new();
1106 assert_eq!(options.duration, Duration::from_secs(5));
1107 assert!(options.filter_aranet_only);
1108 }
1109
1110 #[test]
1111 fn test_scan_options_duration() {
1112 let options = ScanOptions::new().duration(Duration::from_secs(10));
1113 assert_eq!(options.duration, Duration::from_secs(10));
1114 }
1115
1116 #[test]
1117 fn test_scan_options_duration_secs() {
1118 let options = ScanOptions::new().duration_secs(15);
1119 assert_eq!(options.duration, Duration::from_secs(15));
1120 }
1121
1122 #[test]
1123 fn test_scan_options_filter_aranet_only() {
1124 let options = ScanOptions::new().filter_aranet_only(false);
1125 assert!(!options.filter_aranet_only);
1126
1127 let options = ScanOptions::new().filter_aranet_only(true);
1128 assert!(options.filter_aranet_only);
1129 }
1130
1131 #[test]
1132 fn test_scan_options_all_devices() {
1133 let options = ScanOptions::new().all_devices();
1134 assert!(!options.filter_aranet_only);
1135 }
1136
1137 #[test]
1138 fn test_scan_options_chaining() {
1139 let options = ScanOptions::new()
1140 .duration_secs(20)
1141 .filter_aranet_only(false);
1142
1143 assert_eq!(options.duration, Duration::from_secs(20));
1144 assert!(!options.filter_aranet_only);
1145 }
1146
1147 #[test]
1148 fn test_scan_options_clone() {
1149 let options1 = ScanOptions::new().duration_secs(8);
1150 let options2 = options1.clone();
1151
1152 assert_eq!(options1.duration, options2.duration);
1153 assert_eq!(options1.filter_aranet_only, options2.filter_aranet_only);
1154 }
1155
1156 #[test]
1157 fn test_scan_options_debug() {
1158 let options = ScanOptions::new();
1159 let debug = format!("{:?}", options);
1160 assert!(debug.contains("ScanOptions"));
1161 assert!(debug.contains("duration"));
1162 assert!(debug.contains("filter_aranet_only"));
1163 }
1164
1165 #[test]
1168 fn test_find_progress_cache_hit() {
1169 let progress = FindProgress::CacheHit;
1170 let debug = format!("{:?}", progress);
1171 assert!(debug.contains("CacheHit"));
1172 }
1173
1174 #[test]
1175 fn test_find_progress_scan_attempt() {
1176 let progress = FindProgress::ScanAttempt {
1177 attempt: 2,
1178 total: 3,
1179 duration_secs: 5,
1180 };
1181
1182 if let FindProgress::ScanAttempt {
1183 attempt,
1184 total,
1185 duration_secs,
1186 } = progress
1187 {
1188 assert_eq!(attempt, 2);
1189 assert_eq!(total, 3);
1190 assert_eq!(duration_secs, 5);
1191 } else {
1192 panic!("Expected ScanAttempt variant");
1193 }
1194 }
1195
1196 #[test]
1197 fn test_find_progress_found() {
1198 let progress = FindProgress::Found { attempt: 1 };
1199 assert!(matches!(progress, FindProgress::Found { attempt: 1 }));
1200 }
1201
1202 #[test]
1203 fn test_find_progress_retry_needed() {
1204 let progress = FindProgress::RetryNeeded { attempt: 2 };
1205 assert!(matches!(progress, FindProgress::RetryNeeded { attempt: 2 }));
1206 }
1207
1208 #[test]
1209 fn test_find_progress_clone() {
1210 let progress1 = FindProgress::ScanAttempt {
1211 attempt: 1,
1212 total: 3,
1213 duration_secs: 4,
1214 };
1215 let progress2 = progress1.clone();
1216
1217 assert!(matches!(
1218 (&progress1, &progress2),
1219 (
1220 FindProgress::ScanAttempt {
1221 attempt: 1,
1222 total: 3,
1223 duration_secs: 4,
1224 },
1225 FindProgress::ScanAttempt {
1226 attempt: 1,
1227 total: 3,
1228 duration_secs: 4,
1229 },
1230 )
1231 ));
1232 }
1233
1234 #[cfg(target_os = "linux")]
1247 #[test]
1248 #[ignore = "needs a system D-Bus (BlueZ not required)"]
1249 fn manager_still_answers_after_its_first_runtime_shuts_down() {
1250 let runtime = || {
1251 tokio::runtime::Builder::new_current_thread()
1252 .enable_all()
1253 .build()
1254 .unwrap()
1255 };
1256
1257 let first = runtime();
1258 let manager = first.block_on(shared_manager()).expect("manager");
1259 drop(first);
1260
1261 let second = runtime();
1262 let answered = second.block_on(async {
1263 tokio::time::timeout(Duration::from_secs(5), manager.adapters()).await
1264 });
1265 assert!(
1266 answered.is_ok(),
1267 "the manager's D-Bus connection died with the runtime that created it"
1268 );
1269 }
1270
1271 const TEST_LIMIT: Duration = Duration::from_secs(600);
1275
1276 fn secs(n: u64) -> Duration {
1277 Duration::from_secs(n)
1278 }
1279
1280 #[derive(Clone)]
1284 struct FakeScanner {
1285 started_at: tokio::time::Instant,
1286 log: Arc<std::sync::Mutex<Vec<(Duration, &'static str)>>>,
1287 scanning: Arc<AtomicBool>,
1288 fail_start: bool,
1289 stop_latency: Duration,
1292 on_stop: Option<std::sync::mpsc::Sender<()>>,
1293 }
1294
1295 impl FakeScanner {
1296 fn new() -> Self {
1297 Self {
1298 started_at: tokio::time::Instant::now(),
1299 log: Arc::default(),
1300 scanning: Arc::default(),
1301 fail_start: false,
1302 stop_latency: Duration::ZERO,
1303 on_stop: None,
1304 }
1305 }
1306
1307 fn record(&self, event: &'static str) {
1308 self.log
1309 .lock()
1310 .unwrap()
1311 .push((self.started_at.elapsed(), event));
1312 }
1313
1314 fn log(&self) -> Vec<(Duration, &'static str)> {
1315 self.log.lock().unwrap().clone()
1316 }
1317
1318 fn is_scanning(&self) -> bool {
1319 self.scanning.load(Ordering::SeqCst)
1320 }
1321 }
1322
1323 impl ScanControl for FakeScanner {
1324 async fn start(&self, _filter: ScanFilter) -> Result<()> {
1325 if self.fail_start {
1326 return Err(Error::InvalidData("start failed".into()));
1327 }
1328 if self.scanning.swap(true, Ordering::SeqCst) {
1329 return Err(Error::InvalidData("org.bluez.Error.InProgress".into()));
1330 }
1331 self.record("start");
1332 Ok(())
1333 }
1334
1335 async fn stop(&self) -> Result<()> {
1336 self.record("stop");
1337 sleep(self.stop_latency).await;
1338 self.scanning.store(false, Ordering::SeqCst);
1339 if let Some(on_stop) = &self.on_stop {
1340 let _ = on_stop.send(());
1341 }
1342 Ok(())
1343 }
1344 }
1345
1346 #[tokio::test(start_paused = true)]
1347 async fn scan_window_stops_the_scan_when_the_window_ends() {
1348 within(TEST_LIMIT, async {
1349 let rt = tokio::runtime::Handle::current();
1350 let lock = ScanLock::default();
1351 let scanner = FakeScanner::new();
1352
1353 let permit = lock.acquire().await;
1354 scan_window(&rt, &scanner, permit, ScanFilter::default(), secs(5))
1355 .await
1356 .unwrap();
1357
1358 assert_eq!(scanner.log(), [(secs(0), "start"), (secs(5), "stop")]);
1359 assert!(!scanner.is_scanning());
1360 })
1361 .await;
1362 }
1363
1364 #[tokio::test(start_paused = true)]
1365 async fn dropping_the_caller_stops_the_scan_immediately() {
1366 within(TEST_LIMIT, async {
1367 let rt = tokio::runtime::Handle::current();
1368 let lock = ScanLock::default();
1369 let scanner = FakeScanner::new();
1370
1371 let permit = lock.acquire().await;
1372 let window = scan_window(&rt, &scanner, permit, ScanFilter::default(), secs(5));
1373 assert!(tokio::time::timeout(secs(1), window).await.is_err());
1374 tokio::time::sleep(Duration::from_millis(10)).await;
1375
1376 assert_eq!(scanner.log(), [(secs(0), "start"), (secs(1), "stop")]);
1377 assert!(!scanner.is_scanning());
1378 })
1379 .await;
1380 }
1381
1382 #[tokio::test(start_paused = true)]
1383 async fn aborting_the_task_stops_the_scan() {
1384 within(TEST_LIMIT, async {
1385 let rt = tokio::runtime::Handle::current();
1386 let lock = ScanLock::default();
1387 let scanner = FakeScanner::new();
1388
1389 let task = tokio::spawn({
1391 let scanner = scanner.clone();
1392 let lock = lock.clone();
1393 async move {
1394 let permit = lock.acquire().await;
1395 scan_window(&rt, &scanner, permit, ScanFilter::default(), secs(5)).await
1396 }
1397 });
1398 tokio::time::sleep(secs(1)).await;
1399 task.abort();
1400 assert!(task.await.unwrap_err().is_cancelled());
1401 tokio::time::sleep(Duration::from_millis(10)).await;
1402
1403 assert_eq!(scanner.log(), [(secs(0), "start"), (secs(1), "stop")]);
1404 assert!(!scanner.is_scanning());
1405 })
1406 .await;
1407 }
1408
1409 #[tokio::test(start_paused = true)]
1410 async fn failed_start_releases_the_permit_without_stopping() {
1411 within(TEST_LIMIT, async {
1412 let rt = tokio::runtime::Handle::current();
1413 let lock = ScanLock::default();
1414 let scanner = FakeScanner {
1415 fail_start: true,
1416 ..FakeScanner::new()
1417 };
1418
1419 let permit = lock.acquire().await;
1420 let result = scan_window(&rt, &scanner, permit, ScanFilter::default(), secs(5)).await;
1421
1422 assert!(matches!(result, Err(Error::InvalidData(ref m)) if m == "start failed"));
1423 assert!(
1424 scanner.log().is_empty(),
1425 "a scan that never started must not be stopped"
1426 );
1427 within(secs(1), lock.acquire()).await;
1428 })
1429 .await;
1430 }
1431
1432 #[test]
1433 fn scan_stops_after_the_callers_runtime_shuts_down() {
1434 let (tx, rx) = std::sync::mpsc::channel();
1435 let caller = tokio::runtime::Builder::new_current_thread()
1436 .enable_all()
1437 .build()
1438 .unwrap();
1439
1440 caller.block_on(async {
1441 let lock = ScanLock::default();
1442 let scanner = FakeScanner {
1443 on_stop: Some(tx),
1444 ..FakeScanner::new()
1445 };
1446 let permit = lock.acquire().await;
1447 let window = run_scan(&scanner, permit, ScanFilter::default(), secs(10));
1449 let started = async {
1450 while !scanner.is_scanning() {
1451 tokio::time::sleep(Duration::from_millis(1)).await;
1452 }
1453 };
1454 tokio::select! {
1457 result = window => panic!("the 10 s window ended early: {result:?}"),
1458 started = tokio::time::timeout(secs(5), started) => {
1459 started.expect("the scan never started");
1460 }
1461 }
1462 });
1463 drop(caller);
1464
1465 rx.recv_timeout(secs(5))
1466 .expect("scan never stopped after the caller's runtime shut down");
1467 }
1468
1469 #[tokio::test(start_paused = true)]
1470 async fn concurrent_scans_run_one_after_another() {
1471 within(TEST_LIMIT, async {
1472 let rt = tokio::runtime::Handle::current();
1473 let lock = ScanLock::default();
1474 let scanner = FakeScanner {
1475 stop_latency: Duration::from_millis(100),
1476 ..FakeScanner::new()
1477 };
1478 let scan = || async {
1479 let permit = lock.acquire().await;
1480 scan_window(&rt, &scanner, permit, ScanFilter::default(), secs(2)).await
1481 };
1482
1483 let (first, second) = tokio::join!(scan(), scan());
1484
1485 first.expect("first scan");
1486 second.expect("second scan should wait for the first instead of failing");
1487 assert_eq!(
1488 scanner.log(),
1489 [
1490 (secs(0), "start"),
1491 (secs(2), "stop"),
1492 (Duration::from_millis(2100), "start"),
1493 (Duration::from_millis(4100), "stop"),
1494 ]
1495 );
1496 })
1497 .await;
1498 }
1499
1500 #[tokio::test(start_paused = true)]
1501 async fn next_scan_waits_until_a_cancelled_scan_has_stopped() {
1502 within(TEST_LIMIT, async {
1503 let rt = tokio::runtime::Handle::current();
1504 let lock = ScanLock::default();
1505 let scanner = FakeScanner::new();
1506
1507 let first = tokio::time::timeout(secs(1), async {
1508 let permit = lock.acquire().await;
1509 scan_window(&rt, &scanner, permit, ScanFilter::default(), secs(5)).await
1510 });
1511 let second = async {
1512 tokio::task::yield_now().await;
1513 let permit = lock.acquire().await;
1514 scan_window(&rt, &scanner, permit, ScanFilter::default(), secs(2)).await
1515 };
1516 let (first, second) = tokio::join!(first, second);
1517
1518 assert!(first.is_err(), "the first scan should have been cancelled");
1519 second.expect("the second scan should start after the first has stopped");
1520 assert_eq!(
1521 scanner.log(),
1522 [
1523 (secs(0), "start"),
1524 (secs(1), "stop"),
1525 (secs(1), "start"),
1526 (secs(3), "stop"),
1527 ]
1528 );
1529 })
1530 .await;
1531 }
1532
1533 #[tokio::test(start_paused = true)]
1534 async fn cancelling_while_waiting_for_the_permit_never_starts_a_scan() {
1535 within(TEST_LIMIT, async {
1536 let rt = tokio::runtime::Handle::current();
1537 let lock = ScanLock::default();
1538 let scanner = FakeScanner::new();
1539
1540 let permit = lock.acquire().await;
1541 let first = tokio::spawn({
1542 let (rt, scanner) = (rt.clone(), scanner.clone());
1543 async move {
1544 scan_window(&rt, &scanner, permit, ScanFilter::default(), secs(5)).await
1545 }
1546 });
1547 let second = tokio::time::timeout(secs(1), async {
1548 let permit = lock.acquire().await;
1549 scan_window(&rt, &scanner, permit, ScanFilter::default(), secs(1)).await
1550 });
1551 assert!(
1552 second.await.is_err(),
1553 "the second scan should still be waiting for the permit"
1554 );
1555 tokio::time::sleep(secs(6)).await;
1556 first.await.unwrap().unwrap();
1557 assert_eq!(scanner.log(), [(secs(0), "start"), (secs(5), "stop")]);
1558
1559 let permit = lock.acquire().await;
1562 let window = scan_window(&rt, &scanner, permit, ScanFilter::default(), secs(1));
1563 assert!(window.now_or_never().is_none());
1564 tokio::time::sleep(Duration::from_millis(10)).await;
1565 assert_eq!(scanner.log(), [(secs(0), "start"), (secs(5), "stop")]);
1566 within(secs(1), lock.acquire()).await;
1567 })
1568 .await;
1569 }
1570
1571 fn search_filters(windows: u32, aranet_only: bool) -> Vec<ScanFilter> {
1576 (1..=windows).map(|_| search_filter(aranet_only)).collect()
1577 }
1578
1579 #[test]
1580 fn search_filter_asks_only_for_aranet_sensors_in_every_window() {
1581 let aranet = ScanFilter {
1582 services: vec![SAF_TEHNIKA_SERVICE_NEW, SAF_TEHNIKA_SERVICE_OLD],
1583 };
1584 for windows in 1..=3 {
1585 assert_eq!(
1586 search_filters(windows, true),
1587 vec![aranet.clone(); windows as usize],
1588 "{windows}-window search"
1589 );
1590 }
1591 }
1592
1593 #[test]
1594 fn search_filter_asks_for_every_device_when_not_filtering() {
1595 for windows in 1..=3 {
1596 assert_eq!(
1597 search_filters(windows, false),
1598 vec![ScanFilter::default(); windows as usize],
1599 "{windows}-window search"
1600 );
1601 }
1602 }
1603
1604 #[test]
1607 fn a_search_fails_after_the_first_scan_that_finds_only_similar_names() {
1608 for attempt in 1..=3 {
1611 let similar = vec!["Aranet4 12345".to_string(), "Aranet4 1ABCD".to_string()];
1612 match after_missed_scan("Aranet4", similar, attempt, 3) {
1613 ControlFlow::Break(Error::DeviceNotFound(DeviceNotFoundReason::NoExactMatch {
1614 identifier,
1615 similar,
1616 })) => {
1617 assert_eq!(identifier, "Aranet4", "attempt {attempt}");
1618 assert_eq!(
1619 similar,
1620 ["Aranet4 12345", "Aranet4 1ABCD"],
1621 "attempt {attempt}"
1622 );
1623 }
1624 other => panic!("attempt {attempt} of 3: {other:?}"),
1625 }
1626 }
1627 }
1628
1629 #[test]
1630 fn a_search_without_similar_names_scans_until_its_last_attempt() {
1631 for attempt in 1..3 {
1632 let decision = after_missed_scan("Aranet4 12345", Vec::new(), attempt, 3);
1633 assert!(
1634 matches!(decision, ControlFlow::Continue(())),
1635 "attempt {attempt} of 3: {decision:?}"
1636 );
1637 }
1638 match after_missed_scan("Aranet4 12345", Vec::new(), 3, 3) {
1639 ControlFlow::Break(Error::DeviceNotFound(DeviceNotFoundReason::NotFound {
1640 identifier,
1641 })) => assert_eq!(identifier, "Aranet4 12345"),
1642 other => panic!("attempt 3 of 3: {other:?}"),
1643 }
1644 }
1645
1646 fn named(local_name: &str, advertisement_name: &str) -> btleplug::api::PeripheralProperties {
1650 btleplug::api::PeripheralProperties {
1651 local_name: Some(local_name.to_string()),
1652 advertisement_name: Some(advertisement_name.to_string()),
1653 ..Default::default()
1654 }
1655 }
1656
1657 #[test]
1658 fn is_aranet_device_recognises_a_sensor_by_its_name_alone() {
1659 assert!(is_aranet_device(&named("Aranet4 12345", "Aranet4 12345")));
1665 assert!(is_aranet_device(&named("ARANET2 2751B", "ARANET2 2751B")));
1666 assert!(!is_aranet_device(&named("Standing desk", "Standing desk")));
1667 let unnamed = btleplug::api::PeripheralProperties::default();
1668 assert!(!is_aranet_device(&unnamed));
1669 }
1670
1671 #[test]
1672 fn is_aranet_device_takes_the_name_from_peripheral_name() {
1673 assert!(is_aranet_device(&named("Kitchen", "Aranet4 12345")));
1676 assert!(!is_aranet_device(&named("Aranet shelf", "Standing desk")));
1678 }
1679
1680 const UUID_1: &str = "1f8893bf-9f7e-02b4-ef4a-7718f4f5d4be";
1685 const UUID_2: &str = "387c18c7-299f-cc32-d01c-6cf29a8d3ca5";
1686 const UUID_3: &str = "5b0e4c1d-7a3f-4e2b-9c6d-8f1a2b3c4d5e";
1687 const UUID_4: &str = "c4a7e2d9-3b1f-4c8e-a6d5-2f9b8e7c1a04";
1688
1689 fn known(
1690 identifier: &str,
1691 peripheral_id: &str,
1692 address: &str,
1693 name: Option<&str>,
1694 ) -> KnownPeripheral {
1695 KnownPeripheral {
1696 identifier: identifier.to_string(),
1697 peripheral_id: peripheral_id.to_string(),
1698 address: address.to_string(),
1699 name: name.map(str::to_string),
1700 }
1701 }
1702
1703 fn on_macos(uuid: &str, name: &str) -> KnownPeripheral {
1705 known(uuid, uuid, UNKNOWN_ADDRESS, Some(name))
1706 }
1707
1708 fn on_linux(address: &str, name: &str) -> KnownPeripheral {
1711 let device_id = format!("hci0/dev_{}", address.replace(':', "_"));
1712 known(address, &device_id, address, Some(name))
1713 }
1714
1715 fn outcome(query: &str, known: &[KnownPeripheral]) -> (&'static str, Vec<String>) {
1718 let (kind, indices) = match lookup(query, known) {
1719 Lookup::Found(index) => ("found", vec![index]),
1720 Lookup::Ambiguous(indices) => ("ambiguous", indices),
1721 Lookup::NotFound { similar } => ("not found", similar),
1722 };
1723 let mut identifiers: Vec<String> = indices
1724 .iter()
1725 .map(|&index| known[index].identifier.clone())
1726 .collect();
1727 if kind == "ambiguous" {
1728 identifiers.sort();
1730 }
1731 (kind, identifiers)
1732 }
1733
1734 fn candidates(query: &str, known: &[KnownPeripheral]) -> Vec<String> {
1736 match resolve(query, known) {
1737 Err(Error::DeviceNotFound(crate::error::DeviceNotFoundReason::Ambiguous {
1738 identifier,
1739 candidates,
1740 })) => {
1741 assert_eq!(identifier, query);
1742 candidates
1743 }
1744 other => panic!("{query:?} is not ambiguous: {other:?}"),
1745 }
1746 }
1747
1748 #[test]
1749 fn lookup_does_not_match_part_of_a_name() {
1750 let devices = [
1751 on_macos(UUID_1, "Aranet4 12345"),
1752 on_macos(UUID_2, "Aranet4 1ABCD"),
1753 ];
1754 assert_eq!(
1755 lookup("Aranet4 1", &devices),
1756 Lookup::NotFound {
1757 similar: vec![0, 1]
1758 }
1759 );
1760 }
1761
1762 #[test]
1763 fn lookup_does_not_match_part_of_a_uuid() {
1764 let devices = [on_macos(UUID_1, "Aranet2 2751B")];
1765 for query in ["4", "1f8893bf"] {
1766 assert_eq!(
1767 lookup(query, &devices),
1768 Lookup::NotFound { similar: vec![] },
1769 "{query:?}"
1770 );
1771 }
1772 }
1773
1774 #[test]
1775 fn lookup_ignores_linux_object_path_fragments() {
1776 let devices = [on_linux("AA:BB:CC:DD:EE:FF", "Aranet4 12345")];
1777 for query in ["hci0", "dev"] {
1778 assert_eq!(
1779 lookup(query, &devices),
1780 Lookup::NotFound { similar: vec![] },
1781 "{query:?}"
1782 );
1783 }
1784 }
1785
1786 #[test]
1787 fn lookup_matches_the_bluez_device_id_display_form() {
1788 let devices = [
1791 on_linux("11:22:33:44:55:66", "Aranet2 2751B"),
1792 on_linux("AA:BB:CC:DD:EE:FF", "Aranet4 12345"),
1793 ];
1794 for query in ["hci0/dev_AA_BB_CC_DD_EE_FF", "hci0/dev_aa_bb_cc_dd_ee_ff"] {
1795 assert_eq!(lookup(query, &devices), Lookup::Found(1), "{query:?}");
1796 }
1797 }
1798
1799 #[test]
1800 fn lookup_matches_the_full_name_ignoring_case_and_whitespace() {
1801 let devices = [
1802 on_macos(UUID_2, "AranetRn+ 306B8"),
1803 on_macos(UUID_1, "Aranet2 2751B"),
1804 ];
1805 let query = parse_query(" aranet2 2751b ").unwrap();
1806 assert_eq!(lookup(query, &devices), Lookup::Found(1));
1807 }
1808
1809 #[test]
1810 fn lookup_matches_a_uuid_in_any_case() {
1811 let devices = [
1812 on_macos(UUID_2, "AranetRn+ 306B8"),
1813 on_macos(UUID_1, "Aranet2 2751B"),
1814 ];
1815 assert_eq!(
1816 lookup("1F8893BF-9F7E-02B4-EF4A-7718F4F5D4BE", &devices),
1817 Lookup::Found(1)
1818 );
1819 }
1820
1821 #[test]
1822 fn lookup_matches_an_address_with_or_without_colons() {
1823 let devices = [
1824 on_linux("11:22:33:44:55:66", "Aranet2 2751B"),
1825 on_linux("AA:BB:CC:DD:EE:FF", "Aranet4 12345"),
1826 ];
1827 for query in ["aa:bb:cc:dd:ee:ff", "AABBCCDDEEFF"] {
1828 assert_eq!(lookup(query, &devices), Lookup::Found(1), "{query:?}");
1829 }
1830 }
1831
1832 #[test]
1833 fn lookup_never_matches_the_all_zero_address() {
1834 let devices = [on_macos(UUID_1, "Aranet2 2751B")];
1835 for query in ["00:00:00:00:00:00", "000000000000"] {
1836 assert_eq!(
1837 lookup(query, &devices),
1838 Lookup::NotFound { similar: vec![] },
1839 "{query:?}"
1840 );
1841 }
1842 }
1843
1844 #[test]
1849 fn lookup_matches_a_name_with_a_bracketed_part_only_as_a_whole() {
1850 let devices = [
1851 on_macos(UUID_2, "AranetRn+ 306B8"),
1852 on_macos(UUID_1, "Kitchen [Aranet4 1A2B3]"),
1853 ];
1854 assert_eq!(
1855 lookup("kitchen [aranet4 1a2b3]", &devices),
1856 Lookup::Found(1)
1857 );
1858 for half in ["Kitchen", "Aranet4 1A2B3"] {
1859 assert_eq!(
1860 lookup(half, &devices),
1861 Lookup::NotFound { similar: vec![1] },
1862 "{half:?}"
1863 );
1864 }
1865 }
1866
1867 #[test]
1868 fn lookup_ignores_spaces_around_a_device_name() {
1869 let devices = [on_macos(UUID_1, " Aranet2 2751B ")];
1870 assert_eq!(lookup("aranet2 2751b", &devices), Lookup::Found(0));
1871 }
1872
1873 #[test]
1874 fn lookup_prefers_an_identifier_match_over_a_name_match() {
1875 let devices = [
1876 on_macos(UUID_1, "AA:BB:CC:DD:EE:FF"),
1877 on_linux("AA:BB:CC:DD:EE:FF", "Aranet4 12345"),
1878 ];
1879 assert_eq!(lookup("aa:bb:cc:dd:ee:ff", &devices), Lookup::Found(1));
1880 }
1881
1882 #[test]
1883 fn lookup_reports_duplicate_names_as_ambiguous() {
1884 let devices = [
1885 on_macos(UUID_1, "Aranet4 12345"),
1886 on_macos(UUID_2, "Aranet4 12345"),
1887 ];
1888 assert_eq!(
1889 lookup("Aranet4 12345", &devices),
1890 Lookup::Ambiguous(vec![0, 1])
1891 );
1892 }
1893
1894 #[test]
1895 fn lookup_suggests_only_aranet_names() {
1896 let devices = [
1898 on_macos(UUID_1, "Aranet4 12345"),
1899 on_macos(UUID_2, "Standing desk"),
1900 on_macos(UUID_3, "Aranet2 2751B"),
1901 ];
1902 assert_eq!(
1903 lookup("an", &devices),
1904 Lookup::NotFound {
1905 similar: vec![2, 0]
1906 }
1907 );
1908 }
1909
1910 fn orders(n: usize) -> Vec<Vec<usize>> {
1912 if n == 0 {
1913 return vec![Vec::new()];
1914 }
1915 let mut all = Vec::new();
1916 for shorter in orders(n - 1) {
1917 for at in 0..n {
1918 let mut order = shorter.clone();
1919 order.insert(at, n - 1);
1920 all.push(order);
1921 }
1922 }
1923 all
1924 }
1925
1926 #[test]
1927 fn lookup_result_is_independent_of_order() {
1928 let devices = [
1929 on_macos(UUID_1, "Aranet4 12345"),
1930 on_macos(UUID_2, "Aranet4 1ABCD"),
1931 on_macos(UUID_3, "Aranet2 2751B"),
1932 on_macos(UUID_4, "Aranet4 12345"),
1934 ];
1935 let cases = [
1936 ("Aranet4 1", "not found", vec![UUID_1, UUID_4, UUID_2]),
1937 ("aranet2 2751b", "found", vec![UUID_3]),
1938 ("Aranet4", "not found", vec![UUID_1, UUID_4, UUID_2]),
1939 ("Aranet4 12345", "ambiguous", vec![UUID_1, UUID_4]),
1940 ];
1941 for (query, kind, identifiers) in cases {
1942 let outcomes: Vec<(&str, Vec<String>)> = orders(devices.len())
1943 .iter()
1944 .map(|order| {
1945 let shuffled: Vec<KnownPeripheral> =
1946 order.iter().map(|&index| devices[index].clone()).collect();
1947 outcome(query, &shuffled)
1948 })
1949 .collect();
1950 assert!(
1951 outcomes.iter().all(|answer| *answer == outcomes[0]),
1952 "the answer for {query:?} depends on the order: {outcomes:?}"
1953 );
1954 assert_eq!(outcomes[0].0, kind, "{query:?}");
1955 assert_eq!(outcomes[0].1, identifiers, "{query:?}");
1956 }
1957 }
1958
1959 #[test]
1960 fn resolve_lists_candidates_and_similar_names_sorted() {
1961 let same_name = [
1963 on_macos(UUID_2, "Aranet4 12345"),
1964 on_macos(UUID_1, "Aranet4 12345"),
1965 ];
1966 assert_eq!(
1967 candidates("Aranet4 12345", &same_name),
1968 [
1969 format!("Aranet4 12345 ({UUID_1})"),
1970 format!("Aranet4 12345 ({UUID_2})"),
1971 ]
1972 );
1973
1974 let one_address = [
1976 known(
1977 "AA:BB:CC:DD:EE:FF",
1978 "hci1/dev_AA_BB_CC_DD_EE_FF",
1979 "AA:BB:CC:DD:EE:FF",
1980 None,
1981 ),
1982 on_linux("AA:BB:CC:DD:EE:FF", "Aranet4 12345"),
1983 ];
1984 assert_eq!(
1985 candidates("aa:bb:cc:dd:ee:ff", &one_address),
1986 [
1987 "Aranet4 12345 (AA:BB:CC:DD:EE:FF)",
1988 "unnamed (AA:BB:CC:DD:EE:FF)",
1989 ]
1990 );
1991
1992 let similar = [
1994 on_macos(UUID_1, "Aranet4 1ABCD "),
1995 on_macos(UUID_2, "Aranet4 12345"),
1996 on_macos(UUID_3, "Aranet4 1ABCD"),
1997 ];
1998 assert_eq!(
1999 resolve("aranet4 1", &similar).unwrap(),
2000 Search::Missing {
2001 similar: vec!["Aranet4 12345".to_string(), "Aranet4 1ABCD".to_string()]
2002 }
2003 );
2004 }
2005
2006 #[test]
2007 fn parse_query_rejects_empty_and_blank_identifiers() {
2008 for identifier in ["", " ", "\t\n"] {
2009 assert!(
2010 matches!(parse_query(identifier), Err(Error::InvalidConfig(_))),
2011 "{identifier:?}"
2012 );
2013 }
2014 assert_eq!(parse_query(" x ").unwrap(), "x");
2015 }
2016
2017 #[tokio::test]
2018 async fn find_device_rejects_an_empty_identifier_without_bluetooth() {
2019 let found = within(Duration::from_secs(5), find_device("")).await;
2026 assert!(
2027 matches!(found, Err(Error::InvalidConfig(_))),
2028 "{:?}",
2029 found.err()
2030 );
2031
2032 let connected = within(Duration::from_secs(5), crate::device::Device::connect(" ")).await;
2033 assert!(
2034 matches!(connected, Err(Error::InvalidConfig(_))),
2035 "{:?}",
2036 connected.err()
2037 );
2038 }
2039
2040 }