Skip to main content

aranet_core/
lib.rs

1//! Core BLE library for Aranet environmental sensors.
2//!
3//! This crate provides low-level Bluetooth Low Energy (BLE) communication
4//! with Aranet sensors including the Aranet4, Aranet2, AranetRn+ (Radon), and
5//! Aranet Radiation devices.
6//!
7//! # Features
8//!
9//! - **Device discovery**: Scan for nearby Aranet devices via BLE
10//! - **Current readings**: CO₂, temperature, pressure, humidity, radon, radiation
11//! - **Historical data**: Download measurement history with timestamps
12//! - **Device settings**: Read/write measurement interval, Bluetooth range
13//! - **Auto-reconnection**: Configurable backoff and retry logic
14//! - **Real-time streaming**: Subscribe to sensor value changes
15//! - **Multi-device support**: Manage multiple sensors simultaneously
16//!
17//! # Supported Devices
18//!
19//! | Device | Sensors |
20//! |--------|---------|
21//! | Aranet4 | CO₂, Temperature, Pressure, Humidity |
22//! | Aranet2 | Temperature, Humidity |
23//! | AranetRn+ | Radon (Bq/m³), Temperature, Pressure, Humidity |
24//! | Aranet Radiation | Dose Rate (µSv/h), Total Dose (mSv) |
25//!
26//! # Platform Differences
27//!
28//! Device identification varies by platform due to differences in BLE implementations:
29//!
30//! - **macOS**: Devices are identified by a UUID assigned by CoreBluetooth. This UUID
31//!   is stable for a given device on a given Mac, but differs between Macs. The UUID
32//!   is not the same as the device's MAC address.
33//!
34//! - **Linux/Windows**: Devices are identified by their Bluetooth MAC address
35//!   (e.g., `AA:BB:CC:DD:EE:FF`). This is consistent across machines.
36//!
37//! When storing device identifiers for reconnection, be aware that:
38//! - On macOS, the UUID may change if Bluetooth is reset or the device is unpaired
39//! - Cross-platform applications should store both the device name and identifier
40//! - The [`Device::address()`] method returns the appropriate identifier for the platform
41//!
42//! # Quick Start
43//!
44//! ```no_run
45//! use aranet_core::{Device, scan};
46//!
47//! #[tokio::main]
48//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
49//!     // Scan for devices
50//!     let devices = scan::scan_for_devices().await?;
51//!     println!("Found {} devices", devices.len());
52//!
53//!     // Connect to a device
54//!     let device = Device::connect("Aranet4 12345").await?;
55//!
56//!     // Read current values
57//!     let reading = device.read_current().await?;
58//!     println!("CO2: {} ppm", reading.co2);
59//!
60//!     // Read device info
61//!     let info = device.read_device_info().await?;
62//!     println!("Serial: {}", info.serial);
63//!
64//!     Ok(())
65//! }
66//! ```
67
68pub mod advertisement;
69pub mod commands;
70pub mod device;
71pub mod error;
72pub mod events;
73pub mod guard;
74pub mod history;
75pub mod manager;
76pub mod messages;
77pub mod metrics;
78pub mod mock;
79pub mod readings;
80pub mod reconnect;
81pub mod retry;
82pub mod scan;
83pub mod settings;
84pub mod streaming;
85pub mod thresholds;
86pub mod traits;
87pub mod util;
88pub mod validation;
89
90#[cfg(feature = "service-client")]
91pub mod service_client;
92
93// Re-export types and uuid modules from aranet-types for backwards compatibility
94pub use aranet_types::types;
95pub use aranet_types::uuid;
96
97// Core exports
98pub use device::Device;
99pub use error::{ConnectionFailureReason, DeviceNotFoundReason, Error, Result};
100pub use history::{HistoryInfo, HistoryOptions, HistoryParam};
101pub use readings::ExtendedReading;
102pub use scan::{
103    DiscoveredDevice, FindProgress, ProgressCallback, ScanOptions, find_device_with_progress,
104    scan_with_retry,
105};
106pub use settings::{BluetoothRange, CalibrationData, DeviceSettings, MeasurementInterval};
107pub use traits::AranetDevice;
108
109/// Type alias for a shared device reference.
110///
111/// This is the recommended way to share a `Device` across multiple tasks.
112/// Since `Device` intentionally does not implement `Clone` (to prevent
113/// connection ownership ambiguity), wrapping it in `Arc` is the standard
114/// pattern for concurrent access.
115///
116/// # Choosing the Right Device Type
117///
118/// This crate provides several device types for different use cases:
119///
120/// | Type | Use Case | Auto-Reconnect | Thread-Safe |
121/// |------|----------|----------------|-------------|
122/// | [`Device`] | Single command, short-lived | No | Yes (via Arc) |
123/// | [`ReconnectingDevice`] | Long-running apps | Yes | Yes |
124/// | [`SharedDevice`] | Sharing Device across tasks | No | Yes |
125/// | [`DeviceManager`] | Managing multiple devices | Yes | Yes |
126///
127/// ## Decision Guide
128///
129/// ### Use [`Device`] when:
130/// - Running a single command (read, history download)
131/// - Connection lifetime is short and well-defined
132/// - You'll handle reconnection yourself
133///
134/// ```no_run
135/// # async fn example() -> aranet_core::Result<()> {
136/// use aranet_core::Device;
137/// let device = Device::connect("Aranet4 12345").await?;
138/// let reading = device.read_current().await?;
139/// device.disconnect().await?;
140/// # Ok(())
141/// # }
142/// ```
143///
144/// ### Use [`ReconnectingDevice`] when:
145/// - Building a long-running application (daemon, service)
146/// - You want automatic reconnection on connection loss
147/// - Continuous monitoring over extended periods
148///
149/// ```no_run
150/// # async fn example() -> aranet_core::Result<()> {
151/// use aranet_core::{AranetDevice, ReconnectingDevice, ReconnectOptions};
152/// let options = ReconnectOptions::default();
153/// let device = ReconnectingDevice::connect("Aranet4 12345", options).await?;
154/// // Will auto-reconnect on connection loss
155/// let reading = device.read_current().await?;
156/// # Ok(())
157/// # }
158/// ```
159///
160/// ### Use [`SharedDevice`] when:
161/// - Sharing a single [`Device`] across multiple async tasks
162/// - You need concurrent reads but want one connection
163///
164/// ```no_run
165/// # async fn example() -> aranet_core::Result<()> {
166/// use aranet_core::{Device, SharedDevice};
167/// use std::sync::Arc;
168///
169/// let device = Device::connect("Aranet4 12345").await?;
170/// let shared: SharedDevice = Arc::new(device);
171///
172/// let shared_clone = Arc::clone(&shared);
173/// tokio::spawn(async move {
174///     let reading = shared_clone.read_current().await;
175/// });
176/// # Ok(())
177/// # }
178/// ```
179///
180/// ### Use [`DeviceManager`] when:
181/// - Managing multiple devices simultaneously
182/// - Need centralized connection/disconnection handling
183/// - Building a multi-device monitoring application
184///
185/// ```no_run
186/// # async fn example() -> aranet_core::Result<()> {
187/// use aranet_core::DeviceManager;
188/// let manager = DeviceManager::new();
189/// manager.add_device("AA:BB:CC:DD:EE:FF").await?;
190/// manager.add_device("11:22:33:44:55:66").await?;
191/// // Manager handles connections for all devices
192/// # Ok(())
193/// # }
194/// ```
195pub type SharedDevice = std::sync::Arc<Device>;
196
197// New module exports
198pub use advertisement::{AdvertisementData, parse_advertisement, parse_advertisement_with_name};
199pub use commands::{
200    HISTORY_V1_REQUEST, HISTORY_V2_REQUEST, SET_BLUETOOTH_RANGE, SET_INTERVAL, SET_SMART_HOME,
201};
202pub use events::{DeviceEvent, EventReceiver, EventSender};
203pub use guard::{DeviceGuard, SharedDeviceGuard};
204pub use manager::{DeviceManager, ManagedDevice, ManagerConfig};
205pub use messages::{CachedDevice, Command, SensorEvent};
206pub use metrics::{ConnectionMetrics, OperationMetrics};
207pub use mock::{MockDevice, MockDeviceBuilder};
208pub use reconnect::{ReconnectOptions, ReconnectingDevice};
209pub use retry::{RetryConfig, with_retry};
210pub use streaming::{ReadingStream, StreamOptions, StreamOptionsBuilder};
211pub use thresholds::{Co2Level, ThresholdConfig, Thresholds};
212pub use util::{create_identifier, format_peripheral_id};
213pub use validation::{ReadingValidator, ValidationResult, ValidationWarning};
214
215// Re-export from aranet-types
216pub use aranet_types::uuid as uuids;
217pub use aranet_types::{CurrentReading, DeviceInfo, DeviceType, HistoryRecord, Status};