aranet_core/device.rs
1//! Aranet device connection and communication.
2//!
3//! This module provides the main interface for connecting to and
4//! communicating with Aranet sensors over Bluetooth Low Energy.
5
6use std::collections::HashMap;
7use std::sync::atomic::{AtomicBool, Ordering};
8use std::time::Duration;
9
10use btleplug::api::{Characteristic, Peripheral as _, WriteType};
11use btleplug::platform::{Adapter, Peripheral};
12use tokio::sync::RwLock;
13use tokio::time::timeout;
14use tracing::{debug, info, warn};
15use uuid::Uuid;
16
17use crate::error::{Error, Result};
18use crate::scan::ScanOptions;
19use crate::traits::AranetDevice;
20use crate::util::{create_identifier, format_peripheral_id, peripheral_name};
21use crate::uuid::{
22 BATTERY_LEVEL, BATTERY_SERVICE, CURRENT_READINGS_DETAIL, CURRENT_READINGS_DETAIL_ALT,
23 DEVICE_INFO_SERVICE, DEVICE_NAME, FIRMWARE_REVISION, GAP_SERVICE, HARDWARE_REVISION,
24 MANUFACTURER_NAME, MODEL_NUMBER, SAF_TEHNIKA_SERVICE_NEW, SAF_TEHNIKA_SERVICE_OLD,
25 SERIAL_NUMBER, SOFTWARE_REVISION,
26};
27use aranet_types::{CurrentReading, DeviceInfo, DeviceType};
28
29/// Represents a connected Aranet device.
30///
31/// # Note on Clone
32///
33/// This struct intentionally does not implement `Clone`. A `Device` represents
34/// an active BLE connection with associated state (services discovered, notification
35/// handlers, etc.). Cloning would create ambiguity about connection ownership and
36/// could lead to resource conflicts. If you need to share a device across multiple
37/// tasks, wrap it in `Arc<Device>`.
38///
39/// # Cleanup
40///
41/// You MUST call [`Device::disconnect`] before dropping the device to properly
42/// release BLE resources. If a Device is dropped without calling disconnect,
43/// a warning will be logged.
44///
45/// # Timeouts
46///
47/// With default settings, [`Device::connect`] gives up after about 30 s of scanning
48/// on a device that the adapter doesn't already know and that isn't advertising. A
49/// device that the adapter still lists (on Linux a paired device, or one seen in the
50/// last 30 s or so; on macOS one that this process found in an earlier scan and
51/// hasn't disconnected from since) is connected to without scanning. If it has gone,
52/// the connect fails within about 20 s (15 s connecting, up to 5 s to confirm the
53/// disconnect). A device that is found by scanning but refuses the connection fails
54/// after about 50 s (30 s scanning, 15 s connecting, up to 5 s to confirm the
55/// disconnect). One that connects slowly and then stops answering fails after at
56/// most about 70 s (adding up to 10 s each for service discovery and for reading its
57/// properties), and the rare retry after an empty service discovery can take about
58/// 102 s. On Linux, service discovery can take up to 20 s instead of 10 s while BlueZ
59/// is still discovering a device it has just connected (a first connection to an
60/// Aranet4, for example), so those two cases can take about 80 s and 122 s there. A
61/// search can also wait for another scan in the same process to finish. Use
62/// [`Device::connect_with_scan_options`] to change the scan time and
63/// [`ConnectionConfig`] to change the connect timeouts.
64///
65/// On Linux, a connection to a sensor that BlueZ doesn't list as paired pairs
66/// it first, which can add up to `connection_timeout` plus the wait for
67/// BlueZ's service discovery (`discovery_timeout`, but at least 20 s), plus
68/// 5 s: 40 s by default. A sensor that refused to pair is connected without
69/// pairing for 10 minutes.
70pub struct Device {
71 /// The BLE adapter used for connection.
72 ///
73 /// This field is stored to keep the adapter alive for the lifetime of the
74 /// peripheral connection. The peripheral may hold internal references to
75 /// the adapter, and dropping the adapter could invalidate the connection.
76 #[allow(dead_code)]
77 adapter: Adapter,
78 /// The underlying BLE peripheral.
79 peripheral: Peripheral,
80 /// Cached device name.
81 name: Option<String>,
82 /// Device address or identifier (MAC address on Linux/Windows, UUID on macOS).
83 address: String,
84 /// Detected device type.
85 device_type: Option<DeviceType>,
86 /// Whether services have been discovered.
87 services_discovered: bool,
88 /// Cache of discovered characteristics by UUID for O(1) lookup.
89 /// Built after service discovery to avoid searching through services on each read.
90 characteristics_cache: RwLock<HashMap<Uuid, Characteristic>>,
91 /// The notification task of each subscribed characteristic.
92 notification_tasks: crate::link::NotificationTasks,
93 /// Whether disconnect has been called (for Drop warning).
94 disconnected: AtomicBool,
95 /// Connection configuration (timeouts, etc.).
96 config: ConnectionConfig,
97}
98
99impl std::fmt::Debug for Device {
100 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101 // Provide a clean debug output that excludes internal BLE details
102 // (adapter, peripheral, notification_tasks, characteristics_cache)
103 // which are not useful for debugging application logic.
104 f.debug_struct("Device")
105 .field("name", &self.name)
106 .field("address", &self.address)
107 .field("device_type", &self.device_type)
108 .field("services_discovered", &self.services_discovered)
109 .finish_non_exhaustive()
110 }
111}
112
113/// Default timeout for BLE characteristic read operations.
114const DEFAULT_READ_TIMEOUT: Duration = Duration::from_secs(10);
115
116/// Default timeout for BLE characteristic write operations.
117const DEFAULT_WRITE_TIMEOUT: Duration = Duration::from_secs(10);
118
119/// Default timeout for BLE connection operations.
120const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(15);
121
122/// Default timeout for service discovery.
123const DEFAULT_DISCOVERY_TIMEOUT: Duration = Duration::from_secs(10);
124
125/// Default timeout for connection validation (keepalive check).
126const DEFAULT_VALIDATION_TIMEOUT: Duration = Duration::from_secs(3);
127
128/// Scan duration of the one device search that `connect`, `connect_with_timeout`,
129/// `connect_with_config` and `connect_with_adapter` run: scans of 5, 10 and 15 s.
130const CONNECT_SCAN_DURATION: Duration = Duration::from_secs(10);
131
132/// Current-readings characteristics to try, in order, for a device type.
133///
134/// Connection checks read them too, instead of Battery Level (0x2A19), which
135/// needs pairing.
136fn readings_characteristics(device_type: Option<DeviceType>) -> &'static [Uuid] {
137 match device_type {
138 Some(DeviceType::Aranet4) => &[CURRENT_READINGS_DETAIL],
139 Some(DeviceType::Aranet2 | DeviceType::AranetRadon | DeviceType::AranetRadiation) => {
140 &[CURRENT_READINGS_DETAIL_ALT]
141 }
142 // Unknown, or a type newer than this crate (`DeviceType` is
143 // `#[non_exhaustive]`): try the Aranet4 characteristic first.
144 None | Some(_) => &[CURRENT_READINGS_DETAIL, CURRENT_READINGS_DETAIL_ALT],
145 }
146}
147
148/// Reads the first of `candidates` that the device has, using `read`.
149///
150/// Moves to the next candidate only when `read` returns `CharacteristicNotFound`.
151/// Any other error, such as a timeout or a lost link, is returned at once.
152async fn read_first_available<F, Fut>(candidates: &[Uuid], mut read: F) -> Result<Vec<u8>>
153where
154 F: FnMut(Uuid) -> Fut,
155 Fut: Future<Output = Result<Vec<u8>>>,
156{
157 let Some((&last, earlier)) = candidates.split_last() else {
158 return Err(Error::Unsupported(
159 "no current-readings characteristic for this device type".into(),
160 ));
161 };
162 for &uuid in earlier {
163 match read(uuid).await {
164 Ok(data) => return Ok(data),
165 Err(Error::CharacteristicNotFound { .. }) => {
166 debug!("Reading characteristic {uuid} not found, trying the next one");
167 }
168 Err(e) => return Err(e),
169 }
170 }
171 read(last).await
172}
173
174/// Configuration for BLE connection timeouts and behavior.
175///
176/// Use this to customize timeout values for different environments.
177/// For example, increase timeouts in challenging RF environments
178/// (concrete walls, electromagnetic interference).
179///
180/// # Example
181///
182/// ```no_run
183/// use std::time::Duration;
184/// use aranet_core::device::ConnectionConfig;
185///
186/// // Create a config for challenging RF environments
187/// let config = ConnectionConfig::default()
188/// .connection_timeout(Duration::from_secs(20))
189/// .read_timeout(Duration::from_secs(15));
190/// ```
191#[derive(Debug, Clone)]
192pub struct ConnectionConfig {
193 /// Timeout for establishing a BLE connection.
194 pub connection_timeout: Duration,
195 /// Timeout for BLE read operations.
196 pub read_timeout: Duration,
197 /// Timeout for BLE write operations.
198 pub write_timeout: Duration,
199 /// Timeout for service discovery after connection.
200 ///
201 /// On macOS this limits the service discovery itself. With btleplug
202 /// 0.13.5 a connect ends when the link is up
203 /// (`src/corebluetooth/peripheral.rs:433-456`) and the services are
204 /// discovered in a step of their own (`:479-500`), so the link has
205 /// `connection_timeout` to come up and the discovery has this limit. A
206 /// discovery that takes longer fails the connect with a "discover
207 /// services" timeout. With btleplug 0.11.8 the discovery ran inside the
208 /// connect, under `connection_timeout`, and this limit had no effect on
209 /// macOS.
210 ///
211 /// On Linux, when BlueZ is still discovering the services of a device it
212 /// has just connected (a first connection to a sensor with many
213 /// characteristics, such as an Aranet4), a connect waits for BlueZ to
214 /// finish for up to this long, but at least 20 s.
215 pub discovery_timeout: Duration,
216 /// Timeout for connection validation (keepalive) checks.
217 pub validation_timeout: Duration,
218}
219
220impl Default for ConnectionConfig {
221 fn default() -> Self {
222 Self {
223 connection_timeout: DEFAULT_CONNECT_TIMEOUT,
224 read_timeout: DEFAULT_READ_TIMEOUT,
225 write_timeout: DEFAULT_WRITE_TIMEOUT,
226 discovery_timeout: DEFAULT_DISCOVERY_TIMEOUT,
227 validation_timeout: DEFAULT_VALIDATION_TIMEOUT,
228 }
229 }
230}
231
232impl ConnectionConfig {
233 /// Create a new connection config with default values.
234 pub fn new() -> Self {
235 Self::default()
236 }
237
238 /// Create a config optimized for the current platform.
239 pub fn for_current_platform() -> Self {
240 let platform = crate::platform::PlatformConfig::for_current_platform();
241 Self {
242 connection_timeout: platform.recommended_connection_timeout,
243 read_timeout: platform.recommended_operation_timeout,
244 write_timeout: platform.recommended_operation_timeout,
245 discovery_timeout: platform.recommended_operation_timeout,
246 validation_timeout: DEFAULT_VALIDATION_TIMEOUT,
247 }
248 }
249
250 /// Create a config for challenging RF environments.
251 ///
252 /// Uses longer timeouts to accommodate signal interference,
253 /// thick walls, or long distances.
254 ///
255 /// These are the connection's timeouts only: [`Device::connect_with_config`]
256 /// still searches with scans of 5, 10 and 15 s (up to about 30 s).
257 /// To search longer for a weak sensor, use [`Device::connect_with_scan_options`]
258 /// with a longer `ScanOptions::duration`.
259 pub fn challenging_environment() -> Self {
260 Self {
261 connection_timeout: Duration::from_secs(90),
262 read_timeout: Duration::from_secs(30),
263 write_timeout: Duration::from_secs(15),
264 discovery_timeout: Duration::from_secs(30),
265 validation_timeout: Duration::from_secs(5),
266 }
267 }
268
269 /// Create a config for fast, reliable environments.
270 ///
271 /// Uses shorter timeouts for quicker failure detection
272 /// when devices are nearby with strong signals.
273 pub fn fast() -> Self {
274 Self {
275 connection_timeout: Duration::from_secs(8),
276 read_timeout: Duration::from_secs(5),
277 write_timeout: Duration::from_secs(5),
278 discovery_timeout: Duration::from_secs(5),
279 validation_timeout: Duration::from_secs(2),
280 }
281 }
282
283 /// Set the connection timeout.
284 #[must_use]
285 pub fn connection_timeout(mut self, timeout: Duration) -> Self {
286 self.connection_timeout = timeout;
287 self
288 }
289
290 /// Set the read timeout.
291 #[must_use]
292 pub fn read_timeout(mut self, timeout: Duration) -> Self {
293 self.read_timeout = timeout;
294 self
295 }
296
297 /// Set the write timeout.
298 #[must_use]
299 pub fn write_timeout(mut self, timeout: Duration) -> Self {
300 self.write_timeout = timeout;
301 self
302 }
303
304 /// Set the service discovery timeout.
305 #[must_use]
306 pub fn discovery_timeout(mut self, timeout: Duration) -> Self {
307 self.discovery_timeout = timeout;
308 self
309 }
310
311 /// Set the validation timeout.
312 #[must_use]
313 pub fn validation_timeout(mut self, timeout: Duration) -> Self {
314 self.validation_timeout = timeout;
315 self
316 }
317}
318
319/// Signal strength quality levels based on RSSI values.
320#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
321pub enum SignalQuality {
322 /// Signal too weak for reliable operation (< -85 dBm).
323 Poor,
324 /// Usable but may have issues (-85 to -75 dBm).
325 Fair,
326 /// Good signal strength (-75 to -60 dBm).
327 Good,
328 /// Excellent signal strength (> -60 dBm).
329 Excellent,
330}
331
332impl SignalQuality {
333 /// Determine signal quality from RSSI value in dBm.
334 ///
335 /// # Arguments
336 ///
337 /// * `rssi` - Signal strength in dBm (typically -30 to -100)
338 ///
339 /// # Returns
340 ///
341 /// The signal quality category.
342 pub fn from_rssi(rssi: i16) -> Self {
343 match rssi {
344 r if r > -60 => SignalQuality::Excellent,
345 r if r > -75 => SignalQuality::Good,
346 r if r > -85 => SignalQuality::Fair,
347 _ => SignalQuality::Poor,
348 }
349 }
350
351 /// Get a human-readable description of the signal quality.
352 pub fn description(&self) -> &'static str {
353 match self {
354 SignalQuality::Excellent => "Excellent signal",
355 SignalQuality::Good => "Good signal",
356 SignalQuality::Fair => "Fair signal - connection may be unstable",
357 SignalQuality::Poor => "Poor signal - consider moving closer",
358 }
359 }
360
361 /// Get recommended read delay for history downloads based on signal quality.
362 pub fn recommended_read_delay(&self) -> Duration {
363 match self {
364 SignalQuality::Excellent => Duration::from_millis(30),
365 SignalQuality::Good => Duration::from_millis(50),
366 SignalQuality::Fair => Duration::from_millis(100),
367 SignalQuality::Poor => Duration::from_millis(200),
368 }
369 }
370
371 /// Check if the signal is strong enough for reliable operations.
372 pub fn is_usable(&self) -> bool {
373 matches!(
374 self,
375 SignalQuality::Excellent | SignalQuality::Good | SignalQuality::Fair
376 )
377 }
378}
379
380impl Device {
381 /// Connect to an Aranet device by its address, identifier or full name.
382 ///
383 /// `identifier` must match exactly, as [`find_device`](crate::scan::find_device)
384 /// describes (case is ignored): a name must be the device's whole name, not part
385 /// of it. On macOS, where Bluetooth doesn't expose MAC addresses, use the
386 /// device's identifier (a CoreBluetooth UUID) or its name.
387 ///
388 /// The device is searched for with scans of 5, 10 and 15 s (up to about 30 s) and
389 /// connected with the default [`ConnectionConfig`]. See the "Timeouts" section of
390 /// [`Device`] for how long that can take.
391 ///
392 /// # Errors
393 ///
394 /// - [`Error::InvalidConfig`] if `identifier` is empty or blank, before
395 /// Bluetooth is used.
396 /// - [`Error::DeviceNotFound`] with
397 /// [`DeviceNotFoundReason::NoAdapter`](crate::error::DeviceNotFoundReason::NoAdapter)
398 /// if there is no Bluetooth adapter.
399 /// - [`Error::DeviceNotFound`] if no nearby device matches `identifier` exactly,
400 /// or several do; its reason says which, as
401 /// [`find_device`](crate::scan::find_device) describes.
402 /// - Otherwise, an error from the Bluetooth adapter or the connection, such as
403 /// [`Error::Timeout`] when a connect step runs out of time.
404 ///
405 /// # Example
406 ///
407 /// ```no_run
408 /// use aranet_core::device::Device;
409 ///
410 /// #[tokio::main]
411 /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
412 /// let device = Device::connect("Aranet4 12345").await?;
413 /// println!("Connected to {:?}", device);
414 /// Ok(())
415 /// }
416 /// ```
417 #[tracing::instrument(level = "info", skip_all, fields(identifier = %identifier))]
418 pub async fn connect(identifier: &str) -> Result<Self> {
419 Self::connect_with_config(identifier, ConnectionConfig::default()).await
420 }
421
422 /// Connect with a custom connection timeout.
423 ///
424 /// `identifier` must match exactly, and errors are returned, as
425 /// [`Device::connect`] describes.
426 ///
427 /// The device search uses scans of 5, 10 and 15 s (up to about 30 s).
428 /// `timeout` replaces only the connect timeout (`connection_timeout`); every other
429 /// timeout keeps its default. Use [`Device::connect_with_scan_options`] to change
430 /// the scan time as well.
431 #[tracing::instrument(level = "info", skip_all, fields(identifier = %identifier, timeout_secs = timeout.as_secs()))]
432 pub async fn connect_with_timeout(identifier: &str, timeout: Duration) -> Result<Self> {
433 Self::connect_with_scan_options(
434 identifier,
435 ScanOptions::default().duration(CONNECT_SCAN_DURATION),
436 ConnectionConfig::default().connection_timeout(timeout),
437 )
438 .await
439 }
440
441 /// Connect to an Aranet device with full configuration.
442 ///
443 /// `identifier` must match exactly, and errors are returned, as
444 /// [`Device::connect`] describes.
445 ///
446 /// `config` sets every timeout of the connection itself. The device is searched for
447 /// with scans of 5, 10 and 15 s (up to about 30 s); use
448 /// [`Device::connect_with_scan_options`] to change the scan time too.
449 ///
450 /// # Example
451 ///
452 /// ```no_run
453 /// use std::time::Duration;
454 /// use aranet_core::device::{Device, ConnectionConfig};
455 ///
456 /// #[tokio::main]
457 /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
458 /// // Longer connect timeouts for a challenging RF environment. They don't
459 /// // lengthen the search for the device.
460 /// let config = ConnectionConfig::challenging_environment();
461 /// let device = Device::connect_with_config("Aranet4 12345", config).await?;
462 /// Ok(())
463 /// }
464 /// ```
465 #[tracing::instrument(level = "info", skip_all, fields(identifier = %identifier))]
466 pub async fn connect_with_config(identifier: &str, config: ConnectionConfig) -> Result<Self> {
467 Self::connect_with_scan_options(
468 identifier,
469 ScanOptions::default().duration(CONNECT_SCAN_DURATION),
470 config,
471 )
472 .await
473 }
474
475 /// Find `identifier` with `scan`, then connect with `config`.
476 ///
477 /// `identifier` must match exactly, and errors are returned, as
478 /// [`Device::connect`] describes.
479 ///
480 /// The search makes up to three scans of `scan.duration / 2`, `scan.duration` and
481 /// `1.5 × scan.duration` (at least 2, 4 and 6 s), so it takes up to about
482 /// 3 × `scan.duration`, plus any wait for another scan in the same process.
483 /// Only `scan.duration` is used: as in
484 /// [`find_device_with_options`](crate::scan::find_device_with_options), the search
485 /// ignores `scan`'s filter flags. On macOS every scan asks the Bluetooth stack
486 /// only for devices that advertise an Aranet service, as every current Aranet
487 /// sensor does.
488 /// A device that the adapter already knows from an earlier scan is used without
489 /// scanning. `config` sets the timeouts of the connection itself; see the
490 /// "Timeouts" section of [`Device`].
491 ///
492 /// # Example
493 ///
494 /// ```no_run
495 /// use std::time::Duration;
496 /// use aranet_core::device::{ConnectionConfig, Device};
497 /// use aranet_core::scan::ScanOptions;
498 ///
499 /// #[tokio::main]
500 /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
501 /// // Scan for 10, 20 and 30 s (up to about 60 s, twice the default
502 /// // search), then allow 30 s to connect.
503 /// let scan = ScanOptions::default().duration(Duration::from_secs(20));
504 /// let config = ConnectionConfig::default().connection_timeout(Duration::from_secs(30));
505 /// let device = Device::connect_with_scan_options("Aranet4 12345", scan, config).await?;
506 /// device.disconnect().await?;
507 /// Ok(())
508 /// }
509 /// ```
510 #[tracing::instrument(level = "info", skip_all, fields(identifier = %identifier, scan_secs = scan.duration.as_secs()))]
511 pub async fn connect_with_scan_options(
512 identifier: &str,
513 scan: ScanOptions,
514 config: ConnectionConfig,
515 ) -> Result<Self> {
516 let (adapter, peripheral) = crate::scan::find_device_with_options(identifier, scan).await?;
517 Self::from_peripheral_with_config(adapter, peripheral, config).await
518 }
519
520 /// Connect to a device using an existing BLE adapter.
521 ///
522 /// This avoids creating a new btleplug `Manager` (and D-Bus connection) on
523 /// every call. Prefer this over [`connect_with_config`](Self::connect_with_config)
524 /// in long-running services that poll devices repeatedly.
525 ///
526 /// Like [`connect_with_config`](Self::connect_with_config), it searches once with
527 /// scans of 5, 10 and 15 s (up to about 30 s), and `config` sets the timeouts of
528 /// the connection itself.
529 ///
530 /// `identifier` must match exactly, and errors are returned, as
531 /// [`Device::connect`] describes.
532 #[tracing::instrument(level = "info", skip_all, fields(identifier = %identifier))]
533 pub async fn connect_with_adapter(
534 adapter: Adapter,
535 identifier: &str,
536 config: ConnectionConfig,
537 ) -> Result<Self> {
538 let peripheral = crate::scan::find_device_with_adapter(
539 &adapter,
540 identifier,
541 ScanOptions::default().duration(CONNECT_SCAN_DURATION),
542 )
543 .await?;
544 Self::from_peripheral_with_config(adapter, peripheral, config).await
545 }
546
547 /// Create a Device from an already-discovered peripheral.
548 #[tracing::instrument(level = "info", skip_all)]
549 pub async fn from_peripheral(adapter: Adapter, peripheral: Peripheral) -> Result<Self> {
550 Self::from_peripheral_with_config(adapter, peripheral, ConnectionConfig::default()).await
551 }
552
553 /// Create a Device from an already-discovered peripheral with custom timeout.
554 #[tracing::instrument(level = "info", skip_all, fields(timeout_secs = connect_timeout.as_secs()))]
555 pub async fn from_peripheral_with_timeout(
556 adapter: Adapter,
557 peripheral: Peripheral,
558 connect_timeout: Duration,
559 ) -> Result<Self> {
560 let config = ConnectionConfig::default().connection_timeout(connect_timeout);
561 Self::from_peripheral_with_config(adapter, peripheral, config).await
562 }
563
564 /// Create a Device from an already-discovered peripheral with full configuration.
565 ///
566 /// If the connect fails or times out, the peripheral is disconnected before
567 /// the error is returned. If this future is dropped before it finishes (a
568 /// caller's timeout, a cancelled task), the peripheral is disconnected in
569 /// the background; that is best effort if the process is exiting. Either
570 /// way the disconnect waits at most 5 s for the Bluetooth stack to confirm
571 /// it.
572 ///
573 /// On Linux, if BlueZ doesn't list the sensor as paired, this pairs it first
574 /// (BlueZ's `Device1.Pair`, through an agent that exists only for that
575 /// pairing and approves only this sensor), which takes at most
576 /// `connection_timeout` plus the wait for BlueZ's service discovery
577 /// (`discovery_timeout`, but at least 20 s), plus 5 s. If pairing fails, a
578 /// warning with the `bluetoothctl` commands that fix it is logged and the
579 /// connection goes ahead unpaired. BlueZ then asks for pairing itself, so on
580 /// a host without a Bluetooth agent this connection's reads can time out. A
581 /// sensor that refused to pair isn't asked again for 10 minutes; after any
582 /// other failure, the next connection pairs again.
583 #[tracing::instrument(level = "info", skip_all, fields(connect_timeout = ?config.connection_timeout))]
584 pub async fn from_peripheral_with_config(
585 adapter: Adapter,
586 peripheral: Peripheral,
587 config: ConnectionConfig,
588 ) -> Result<Self> {
589 let cleanup = crate::link::cleanup_runtime().ok_or_else(|| {
590 Error::Io(std::io::Error::other(
591 "no tokio runtime available for Bluetooth cleanup",
592 ))
593 })?;
594
595 let crate::link::OpenLink {
596 pending,
597 services,
598 properties,
599 } = crate::link::connect(&peripheral, &config, &cleanup).await?;
600
601 // Build characteristics cache for O(1) lookups
602 let mut characteristics_cache = HashMap::new();
603 for service in &services {
604 debug!(" Service: {}", service.uuid);
605 for char in &service.characteristics {
606 debug!(" Characteristic: {}", char.uuid);
607 characteristics_cache.insert(char.uuid, char.clone());
608 }
609 }
610 debug!(
611 "Cached {} characteristics for fast lookup",
612 characteristics_cache.len()
613 );
614
615 let name = properties
616 .as_ref()
617 .and_then(peripheral_name)
618 .map(str::to_owned);
619
620 // Get address - on macOS this may be 00:00:00:00:00:00, so we use peripheral ID as fallback
621 let address = properties
622 .as_ref()
623 .map(|p| create_identifier(&p.address.to_string(), &peripheral.id()))
624 .unwrap_or_else(|| format_peripheral_id(&peripheral.id()));
625
626 // Determine device type from name
627 let device_type = name.as_ref().and_then(|n| DeviceType::from_name(n));
628
629 let device = Self {
630 adapter,
631 peripheral,
632 name,
633 address,
634 device_type,
635 services_discovered: true,
636 characteristics_cache: RwLock::new(characteristics_cache),
637 notification_tasks: crate::link::NotificationTasks::default(),
638 disconnected: AtomicBool::new(false),
639 config,
640 };
641 // Nothing between `connect` returning and here awaits, so the link is
642 // never left without an owner.
643 pending.disarm();
644 Ok(device)
645 }
646
647 /// Check if the device is connected (queries BLE stack state).
648 ///
649 /// Returns `false` if the Bluetooth stack reports an error or doesn't answer
650 /// within the connection's `validation_timeout` (3 s by default, set with
651 /// [`ConnectionConfig::validation_timeout`]). On macOS the limit is only a
652 /// guard: once the sensor has dropped the connection, btleplug 0.13.5
653 /// answers `false` at once (`src/corebluetooth/internal.rs:1318-1332`),
654 /// where 0.11.8 gave no answer.
655 ///
656 /// Note: This only checks the BLE stack's connection state, which may be stale,
657 /// especially on macOS. For a more reliable check, use [`Self::validate_connection`].
658 pub async fn is_connected(&self) -> bool {
659 crate::link::is_connected(&self.peripheral, self.config.validation_timeout).await
660 }
661
662 /// Validate the connection by reading the current measurements.
663 ///
664 /// This reads the characteristic that [`Self::read_current`] uses, so the
665 /// check needs no pairing that a reading doesn't need (unpaired Aranet2 and
666 /// AranetRn+ sensors answer it) and never starts a pairing that a reading
667 /// wouldn't. It fails only if the read fails or takes longer than the
668 /// connection's `validation_timeout` (3 s by default, set with
669 /// [`ConnectionConfig::validation_timeout`]).
670 ///
671 /// This is more reliable than `is_connected()` as it actively verifies
672 /// the connection is working. It detects "zombie connections", where the
673 /// BLE stack thinks it's connected but the device is actually out of range.
674 ///
675 /// # Returns
676 ///
677 /// `true` if the connection is active and responsive, `false` otherwise.
678 pub async fn validate_connection(&self) -> bool {
679 matches!(
680 timeout(self.config.validation_timeout, self.read_current_bytes()).await,
681 Ok(Ok(_))
682 )
683 }
684
685 /// Check if the connection is alive by reading the current measurements.
686 ///
687 /// This is an alias for [`Self::validate_connection`] that better describes
688 /// the intent when used for connection health monitoring. Like it, it needs
689 /// no pairing that a reading doesn't need, and fails only if the read fails
690 /// or takes longer than the connection's `validation_timeout`.
691 ///
692 /// # Example
693 ///
694 /// ```ignore
695 /// // In a health monitor loop
696 /// if !device.is_connection_alive().await {
697 /// // Connection lost, need to reconnect
698 /// }
699 /// ```
700 pub async fn is_connection_alive(&self) -> bool {
701 self.validate_connection().await
702 }
703
704 /// Get the current connection configuration.
705 pub fn config(&self) -> &ConnectionConfig {
706 &self.config
707 }
708
709 /// Get the current signal quality based on RSSI.
710 ///
711 /// Returns `None` if RSSI cannot be read.
712 pub async fn signal_quality(&self) -> Option<SignalQuality> {
713 self.read_rssi().await.ok().map(SignalQuality::from_rssi)
714 }
715
716 /// Disconnect from the device.
717 ///
718 /// This will:
719 /// 1. Abort all active notification handlers
720 /// 2. Disconnect from the BLE peripheral
721 ///
722 /// Returns [`Error::Timeout`] if the Bluetooth stack doesn't confirm the
723 /// disconnect within 5 s. The disconnect runs as a background task on
724 /// aranet-core's own runtime, or on the caller's runtime if aranet-core's
725 /// can't be started, so it completes even if this future is dropped, for
726 /// example by a caller's timeout. Returns [`Error::Io`] if there is no
727 /// runtime to run it on at all, or if the task panicked or its runtime
728 /// shut down before it finished.
729 ///
730 /// **Important:** You MUST call this method before dropping the Device
731 /// to ensure proper cleanup of BLE resources.
732 #[tracing::instrument(level = "info", skip(self), fields(device_name = ?self.name))]
733 pub async fn disconnect(&self) -> Result<()> {
734 info!("Disconnecting from device...");
735 self.disconnected.store(true, Ordering::SeqCst);
736
737 // Stop every notification callback.
738 self.notification_tasks.abort_all();
739
740 // `cleanup_runtime` is `None` only if aranet-core's runtime can't be
741 // started and this future isn't polled on a tokio runtime either.
742 // The time limit needs a tokio timer, so give up instead of panicking.
743 let runtime = crate::link::cleanup_runtime().ok_or_else(|| {
744 Error::Io(std::io::Error::other(
745 "no tokio runtime available to disconnect from the device",
746 ))
747 })?;
748 crate::link::disconnect_detached(&self.peripheral, &runtime).await
749 }
750
751 /// Get the device name.
752 pub fn name(&self) -> Option<&str> {
753 self.name.as_deref()
754 }
755
756 /// Get the device address or identifier.
757 ///
758 /// On Linux and Windows, this returns the Bluetooth MAC address (e.g., "AA:BB:CC:DD:EE:FF").
759 /// On macOS, this returns a UUID identifier since MAC addresses are not exposed.
760 pub fn address(&self) -> &str {
761 &self.address
762 }
763
764 /// Get the detected device type.
765 pub fn device_type(&self) -> Option<DeviceType> {
766 self.device_type
767 }
768
769 /// Read the current RSSI (signal strength) of the connection.
770 ///
771 /// Returns the RSSI in dBm. More negative values indicate weaker signals.
772 /// Typical values range from -30 (strong) to -90 (weak).
773 ///
774 /// Returns [`Error::Timeout`] if the Bluetooth stack doesn't answer within
775 /// the connection's `read_timeout` (10 s by default, set with
776 /// [`ConnectionConfig::read_timeout`]).
777 pub async fn read_rssi(&self) -> Result<i16> {
778 let properties = crate::link::bounded(
779 "read device properties",
780 self.config.read_timeout,
781 self.peripheral.properties(),
782 )
783 .await?;
784 properties
785 .and_then(|p| p.rssi)
786 .ok_or_else(|| Error::InvalidData("RSSI not available".to_string()))
787 }
788
789 /// Find a characteristic by UUID using the cached lookup table.
790 ///
791 /// Uses O(1) lookup from the characteristics cache built during service discovery.
792 /// Falls back to searching through services if the cache is empty (shouldn't happen
793 /// normally, but provides robustness).
794 async fn find_characteristic(&self, uuid: Uuid) -> Result<Characteristic> {
795 // Try cache first (O(1) lookup)
796 {
797 let cache = self.characteristics_cache.read().await;
798 if let Some(char) = cache.get(&uuid) {
799 return Ok(char.clone());
800 }
801
802 // If cache is populated but characteristic not found, it doesn't exist
803 if !cache.is_empty() {
804 return Err(Error::characteristic_not_found(
805 uuid.to_string(),
806 self.peripheral.services().len(),
807 ));
808 }
809 }
810
811 // Fallback: search services directly (shouldn't happen in normal operation)
812 warn!(
813 "Characteristics cache empty, falling back to service search for {}",
814 uuid
815 );
816 let services = self.peripheral.services();
817 let service_count = services.len();
818
819 // First try Aranet-specific services
820 for service in &services {
821 if service.uuid == SAF_TEHNIKA_SERVICE_NEW || service.uuid == SAF_TEHNIKA_SERVICE_OLD {
822 for char in &service.characteristics {
823 if char.uuid == uuid {
824 return Ok(char.clone());
825 }
826 }
827 }
828 }
829
830 // Then try standard services (GAP, Device Info, Battery)
831 for service in &services {
832 if service.uuid == GAP_SERVICE
833 || service.uuid == DEVICE_INFO_SERVICE
834 || service.uuid == BATTERY_SERVICE
835 {
836 for char in &service.characteristics {
837 if char.uuid == uuid {
838 return Ok(char.clone());
839 }
840 }
841 }
842 }
843
844 // Finally search all services
845 for service in &services {
846 for char in &service.characteristics {
847 if char.uuid == uuid {
848 return Ok(char.clone());
849 }
850 }
851 }
852
853 Err(Error::characteristic_not_found(
854 uuid.to_string(),
855 service_count,
856 ))
857 }
858
859 /// Read a characteristic value by UUID.
860 ///
861 /// This method includes a timeout to prevent indefinite hangs on BLE operations.
862 /// The timeout is controlled by [`ConnectionConfig::read_timeout`].
863 pub async fn read_characteristic(&self, uuid: Uuid) -> Result<Vec<u8>> {
864 let characteristic = self.find_characteristic(uuid).await?;
865 let data = timeout(
866 self.config.read_timeout,
867 self.peripheral.read(&characteristic),
868 )
869 .await
870 .map_err(|_| Error::Timeout {
871 operation: format!("read characteristic {}", uuid),
872 duration: self.config.read_timeout,
873 })??;
874 Ok(data)
875 }
876
877 /// Read a characteristic value with a custom timeout.
878 ///
879 /// Use this when you need a different timeout than the default,
880 /// for example when reading large data.
881 pub async fn read_characteristic_with_timeout(
882 &self,
883 uuid: Uuid,
884 read_timeout: Duration,
885 ) -> Result<Vec<u8>> {
886 let characteristic = self.find_characteristic(uuid).await?;
887 let data = timeout(read_timeout, self.peripheral.read(&characteristic))
888 .await
889 .map_err(|_| Error::Timeout {
890 operation: format!("read characteristic {}", uuid),
891 duration: read_timeout,
892 })??;
893 Ok(data)
894 }
895
896 /// Write a value to a characteristic.
897 ///
898 /// This method includes a timeout to prevent indefinite hangs on BLE operations.
899 /// The timeout is controlled by [`ConnectionConfig::write_timeout`].
900 pub async fn write_characteristic(&self, uuid: Uuid, data: &[u8]) -> Result<()> {
901 let characteristic = self.find_characteristic(uuid).await?;
902 timeout(
903 self.config.write_timeout,
904 self.peripheral
905 .write(&characteristic, data, WriteType::WithResponse),
906 )
907 .await
908 .map_err(|_| Error::Timeout {
909 operation: format!("write characteristic {}", uuid),
910 duration: self.config.write_timeout,
911 })??;
912 Ok(())
913 }
914
915 /// Write a value to a characteristic with a custom timeout.
916 pub async fn write_characteristic_with_timeout(
917 &self,
918 uuid: Uuid,
919 data: &[u8],
920 write_timeout: Duration,
921 ) -> Result<()> {
922 let characteristic = self.find_characteristic(uuid).await?;
923 timeout(
924 write_timeout,
925 self.peripheral
926 .write(&characteristic, data, WriteType::WithResponse),
927 )
928 .await
929 .map_err(|_| Error::Timeout {
930 operation: format!("write characteristic {}", uuid),
931 duration: write_timeout,
932 })??;
933 Ok(())
934 }
935
936 /// Raw current-readings bytes; on CharacteristicNotFound tries the next candidate.
937 ///
938 /// Reads the characteristics from `readings_characteristics` in order, as
939 /// `read_first_available` describes.
940 async fn read_current_bytes(&self) -> Result<Vec<u8>> {
941 read_first_available(readings_characteristics(self.device_type), |uuid| {
942 self.read_characteristic(uuid)
943 })
944 .await
945 }
946
947 /// Read current sensor measurements.
948 ///
949 /// Automatically selects the correct characteristic UUID based on device type:
950 /// - Aranet4 uses `f0cd3001`
951 /// - Aranet2, Radon, Radiation use `f0cd3003`
952 /// - an unknown type tries `f0cd3001`, then `f0cd3003` if the device doesn't have it
953 #[tracing::instrument(level = "debug", skip(self), fields(device_name = ?self.name, device_type = ?self.device_type))]
954 pub async fn read_current(&self) -> Result<CurrentReading> {
955 let data = self.read_current_bytes().await?;
956
957 // Parse based on device type.
958 let device_type = match self.device_type {
959 Some(dt) => dt,
960 None => {
961 warn!(
962 "Device type unknown for {}; defaulting to Aranet4 — \
963 readings may be incorrect if this is a different model",
964 self.name().unwrap_or("unknown")
965 );
966 DeviceType::Aranet4
967 }
968 };
969 crate::readings::parse_reading_for_device(&data, device_type)
970 }
971
972 /// Read the battery level (0-100).
973 #[tracing::instrument(level = "debug", skip(self))]
974 pub async fn read_battery(&self) -> Result<u8> {
975 let data = self.read_characteristic(BATTERY_LEVEL).await?;
976 if data.is_empty() {
977 return Err(Error::InvalidData("Empty battery data".to_string()));
978 }
979 Ok(data[0])
980 }
981
982 /// Read device information.
983 ///
984 /// This method reads all device info characteristics in parallel for better performance.
985 #[tracing::instrument(level = "debug", skip(self))]
986 pub async fn read_device_info(&self) -> Result<DeviceInfo> {
987 fn read_string(data: Vec<u8>) -> String {
988 String::from_utf8(data)
989 .unwrap_or_default()
990 .trim_end_matches('\0')
991 .to_string()
992 }
993
994 // Read all characteristics in parallel for better performance
995 let (
996 name_result,
997 model_result,
998 serial_result,
999 firmware_result,
1000 hardware_result,
1001 software_result,
1002 manufacturer_result,
1003 ) = tokio::join!(
1004 self.read_characteristic(DEVICE_NAME),
1005 self.read_characteristic(MODEL_NUMBER),
1006 self.read_characteristic(SERIAL_NUMBER),
1007 self.read_characteristic(FIRMWARE_REVISION),
1008 self.read_characteristic(HARDWARE_REVISION),
1009 self.read_characteristic(SOFTWARE_REVISION),
1010 self.read_characteristic(MANUFACTURER_NAME),
1011 );
1012
1013 let name = name_result
1014 .map(read_string)
1015 .unwrap_or_else(|_| self.name.clone().unwrap_or_default());
1016
1017 let model = model_result.map(read_string).unwrap_or_default();
1018 let serial = serial_result.map(read_string).unwrap_or_default();
1019 let firmware = firmware_result.map(read_string).unwrap_or_default();
1020 let hardware = hardware_result.map(read_string).unwrap_or_default();
1021 let software = software_result.map(read_string).unwrap_or_default();
1022 let manufacturer = manufacturer_result.map(read_string).unwrap_or_default();
1023
1024 Ok(DeviceInfo {
1025 name,
1026 model,
1027 serial,
1028 firmware,
1029 hardware,
1030 software,
1031 manufacturer,
1032 })
1033 }
1034
1035 /// Read essential device information only.
1036 ///
1037 /// This is a faster alternative to [`Self::read_device_info`] that only reads
1038 /// the most critical characteristics: name, serial number, and firmware version.
1039 /// Use this for faster startup when full device info isn't needed immediately.
1040 #[tracing::instrument(level = "debug", skip(self))]
1041 pub async fn read_device_info_essential(&self) -> Result<DeviceInfo> {
1042 fn read_string(data: Vec<u8>) -> String {
1043 String::from_utf8(data)
1044 .unwrap_or_default()
1045 .trim_end_matches('\0')
1046 .to_string()
1047 }
1048
1049 // Only read the essential characteristics in parallel
1050 let (name_result, serial_result, firmware_result) = tokio::join!(
1051 self.read_characteristic(DEVICE_NAME),
1052 self.read_characteristic(SERIAL_NUMBER),
1053 self.read_characteristic(FIRMWARE_REVISION),
1054 );
1055
1056 let name = name_result
1057 .map(read_string)
1058 .unwrap_or_else(|_| self.name.clone().unwrap_or_default());
1059 let serial = serial_result.map(read_string).unwrap_or_default();
1060 let firmware = firmware_result.map(read_string).unwrap_or_default();
1061
1062 Ok(DeviceInfo {
1063 name,
1064 model: String::new(),
1065 serial,
1066 firmware,
1067 hardware: String::new(),
1068 software: String::new(),
1069 manufacturer: String::new(),
1070 })
1071 }
1072
1073 /// Subscribe to notifications on a characteristic.
1074 ///
1075 /// The callback is called on a background task with the value of each
1076 /// notification the characteristic sends, until
1077 /// [`unsubscribe_from_notifications`](Self::unsubscribe_from_notifications)
1078 /// or [`disconnect`](Self::disconnect) is called or the device is dropped.
1079 ///
1080 /// Subscribing to the same characteristic again replaces its callback. If
1081 /// subscribing fails, the previous callback keeps running.
1082 ///
1083 /// Opening the notification stream and enabling notifications on the
1084 /// device each give up with [`Error::Timeout`] after the connection's
1085 /// `write_timeout` (set with [`ConnectionConfig::write_timeout`]).
1086 pub async fn subscribe_to_notifications<F>(&self, uuid: Uuid, callback: F) -> Result<()>
1087 where
1088 F: Fn(&[u8]) + Send + Sync + 'static,
1089 {
1090 let characteristic = self.find_characteristic(uuid).await?;
1091 self.notification_tasks
1092 .subscribe(
1093 &self.peripheral,
1094 &characteristic,
1095 self.config.write_timeout,
1096 callback,
1097 )
1098 .await
1099 }
1100
1101 /// Unsubscribe from notifications on a characteristic.
1102 ///
1103 /// Stops the characteristic's callback first, then tells the device to
1104 /// stop sending notifications. Once this returns, the callback is not
1105 /// called again, even if the device call fails.
1106 ///
1107 /// Waiting for the callback to stop and the device call each give up
1108 /// after the connection's `write_timeout` (set with
1109 /// [`ConnectionConfig::write_timeout`]); the device call then fails with
1110 /// [`Error::Timeout`].
1111 pub async fn unsubscribe_from_notifications(&self, uuid: Uuid) -> Result<()> {
1112 let characteristic = self.find_characteristic(uuid).await?;
1113 self.notification_tasks
1114 .unsubscribe(&self.peripheral, &characteristic, self.config.write_timeout)
1115 .await
1116 }
1117
1118 /// Get the number of cached characteristics.
1119 ///
1120 /// This is useful for debugging and testing to verify service discovery worked.
1121 pub async fn cached_characteristic_count(&self) -> usize {
1122 self.characteristics_cache.read().await.len()
1123 }
1124}
1125
1126// NOTE: Drop performs best-effort cleanup if disconnect() was not called.
1127// The disconnect is spawned on aranet-core's own runtime (`aranet-ble`) when it
1128// can be started, so it runs even if the caller's runtime is shutting down, and
1129// it gives up after 5 s if the Bluetooth stack never confirms. It can still be
1130// cut short when the process exits. For reliable cleanup, callers SHOULD
1131// explicitly call `device.disconnect().await` before dropping the Device.
1132//
1133// The cleanup behavior:
1134// 1. Aborts all notification handlers (sync operation)
1135// 2. Spawns a time-limited disconnect of the peripheral on aranet-core's runtime (best-effort)
1136// 3. Logs a warning about the implicit cleanup
1137//
1138// For automatic cleanup, consider using `ReconnectingDevice` which manages the lifecycle.
1139
1140impl Drop for Device {
1141 fn drop(&mut self) {
1142 if !self.disconnected.load(Ordering::SeqCst) {
1143 // Mark as disconnected to prevent double-cleanup
1144 self.disconnected.store(true, Ordering::SeqCst);
1145
1146 // Log warning about implicit cleanup
1147 warn!(
1148 device_name = ?self.name,
1149 device_address = %self.address,
1150 "Device dropped without calling disconnect() - performing best-effort cleanup. \
1151 For reliable cleanup, call device.disconnect().await before dropping."
1152 );
1153
1154 // Abort every notification task. The task map's lock is never
1155 // held across an await, so unlike the old `try_lock` this is
1156 // never skipped.
1157 self.notification_tasks.abort_all();
1158
1159 // Spawn a best-effort, time-limited disconnect, on aranet-core's own
1160 // runtime when it can be started, so it outlives the caller's runtime
1161 let peripheral = self.peripheral.clone();
1162 let address = self.address.clone();
1163
1164 if let Some(runtime) = crate::link::cleanup_runtime() {
1165 runtime.spawn(async move {
1166 match crate::link::disconnect(&peripheral).await {
1167 Ok(()) => debug!(
1168 device_address = %address,
1169 "Best-effort disconnect completed"
1170 ),
1171 Err(e) => debug!(
1172 device_address = %address,
1173 error = %e,
1174 "Best-effort disconnect failed (device may already be disconnected)"
1175 ),
1176 }
1177 });
1178 }
1179 }
1180 }
1181}
1182
1183impl AranetDevice for Device {
1184 // --- Connection Management ---
1185
1186 async fn is_connected(&self) -> bool {
1187 Device::is_connected(self).await
1188 }
1189
1190 async fn disconnect(&self) -> Result<()> {
1191 Device::disconnect(self).await
1192 }
1193
1194 // --- Device Identity ---
1195
1196 fn name(&self) -> Option<&str> {
1197 Device::name(self)
1198 }
1199
1200 fn address(&self) -> &str {
1201 Device::address(self)
1202 }
1203
1204 fn device_type(&self) -> Option<DeviceType> {
1205 Device::device_type(self)
1206 }
1207
1208 // --- Current Readings ---
1209
1210 async fn read_current(&self) -> Result<CurrentReading> {
1211 Device::read_current(self).await
1212 }
1213
1214 async fn read_device_info(&self) -> Result<DeviceInfo> {
1215 Device::read_device_info(self).await
1216 }
1217
1218 async fn read_rssi(&self) -> Result<i16> {
1219 Device::read_rssi(self).await
1220 }
1221
1222 // --- Battery ---
1223
1224 async fn read_battery(&self) -> Result<u8> {
1225 Device::read_battery(self).await
1226 }
1227
1228 // --- History ---
1229
1230 async fn get_history_info(&self) -> Result<crate::history::HistoryInfo> {
1231 Device::get_history_info(self).await
1232 }
1233
1234 async fn download_history(&self) -> Result<Vec<aranet_types::HistoryRecord>> {
1235 Device::download_history(self).await
1236 }
1237
1238 async fn download_history_with_options(
1239 &self,
1240 options: crate::history::HistoryOptions,
1241 ) -> Result<Vec<aranet_types::HistoryRecord>> {
1242 Device::download_history_with_options(self, options).await
1243 }
1244
1245 // --- Settings ---
1246
1247 async fn get_interval(&self) -> Result<crate::settings::MeasurementInterval> {
1248 Device::get_interval(self).await
1249 }
1250
1251 async fn set_interval(&self, interval: crate::settings::MeasurementInterval) -> Result<()> {
1252 Device::set_interval(self, interval).await
1253 }
1254
1255 async fn get_calibration(&self) -> Result<crate::settings::CalibrationData> {
1256 Device::get_calibration(self).await
1257 }
1258}
1259
1260#[cfg(test)]
1261mod tests {
1262 use super::*;
1263
1264 use futures::FutureExt;
1265
1266 #[test]
1267 fn readings_characteristics_follow_the_device_type() {
1268 assert_eq!(
1269 readings_characteristics(Some(DeviceType::Aranet4)),
1270 &[CURRENT_READINGS_DETAIL]
1271 );
1272 for device_type in [
1273 DeviceType::Aranet2,
1274 DeviceType::AranetRadon,
1275 DeviceType::AranetRadiation,
1276 ] {
1277 assert_eq!(
1278 readings_characteristics(Some(device_type)),
1279 &[CURRENT_READINGS_DETAIL_ALT],
1280 "{device_type:?}"
1281 );
1282 }
1283 // Unknown type: the Aranet4 characteristic first, as `read_current` always did.
1284 assert_eq!(
1285 readings_characteristics(None),
1286 &[CURRENT_READINGS_DETAIL, CURRENT_READINGS_DETAIL_ALT]
1287 );
1288
1289 // Battery Level (0x2A19) needs pairing, so a connection check must never read it.
1290 for device_type in [
1291 None,
1292 Some(DeviceType::Aranet4),
1293 Some(DeviceType::Aranet2),
1294 Some(DeviceType::AranetRadon),
1295 Some(DeviceType::AranetRadiation),
1296 ] {
1297 assert!(
1298 !readings_characteristics(device_type).contains(&BATTERY_LEVEL),
1299 "{device_type:?} reads Battery Level"
1300 );
1301 }
1302 }
1303
1304 /// Runs `read_first_available` over `candidates` with a reader that gives
1305 /// the scripted `answers` in order. Returns the result and the
1306 /// characteristics the reader was asked for.
1307 fn read_scripted(
1308 candidates: &[Uuid],
1309 answers: Vec<Result<Vec<u8>>>,
1310 ) -> (Result<Vec<u8>>, Vec<Uuid>) {
1311 let mut answers = answers.into_iter();
1312 let mut asked = Vec::new();
1313 let result = read_first_available(candidates, |uuid| {
1314 asked.push(uuid);
1315 std::future::ready(answers.next().expect("read more often than scripted"))
1316 })
1317 .now_or_never()
1318 .expect("scripted reads finish at once");
1319 (result, asked)
1320 }
1321
1322 fn not_found(uuid: Uuid) -> Error {
1323 Error::characteristic_not_found(uuid.to_string(), 6)
1324 }
1325
1326 #[test]
1327 fn a_missing_characteristic_moves_on_to_the_next_candidate() {
1328 let both = [CURRENT_READINGS_DETAIL, CURRENT_READINGS_DETAIL_ALT];
1329
1330 let (result, asked) = read_scripted(&both, vec![Ok(vec![1])]);
1331 assert_eq!(result.unwrap(), [1]);
1332 assert_eq!(asked, [CURRENT_READINGS_DETAIL]);
1333
1334 let (result, asked) = read_scripted(
1335 &both,
1336 vec![Err(not_found(CURRENT_READINGS_DETAIL)), Ok(vec![2])],
1337 );
1338 assert_eq!(result.unwrap(), [2]);
1339 assert_eq!(asked, both);
1340 }
1341
1342 #[test]
1343 fn any_other_error_ends_the_search() {
1344 let (result, asked) = read_scripted(
1345 &[CURRENT_READINGS_DETAIL, CURRENT_READINGS_DETAIL_ALT],
1346 vec![Err(Error::timeout(
1347 "read characteristic f0cd3001",
1348 Duration::from_secs(10),
1349 ))],
1350 );
1351 assert!(matches!(result, Err(Error::Timeout { .. })), "{result:?}");
1352 assert_eq!(asked, [CURRENT_READINGS_DETAIL]);
1353 }
1354
1355 #[test]
1356 fn the_readings_read_never_asks_for_battery_level() {
1357 for device_type in [
1358 None,
1359 Some(DeviceType::Aranet4),
1360 Some(DeviceType::Aranet2),
1361 Some(DeviceType::AranetRadon),
1362 Some(DeviceType::AranetRadiation),
1363 ] {
1364 let candidates = readings_characteristics(device_type);
1365 let answers = candidates
1366 .iter()
1367 .map(|&uuid| Err(not_found(uuid)))
1368 .collect();
1369 let (result, asked) = read_scripted(candidates, answers);
1370 assert!(
1371 matches!(result, Err(Error::CharacteristicNotFound { .. })),
1372 "{device_type:?}: {result:?}"
1373 );
1374 assert_eq!(asked, candidates, "{device_type:?}");
1375 assert!(!asked.contains(&BATTERY_LEVEL), "{device_type:?}");
1376 }
1377 }
1378}