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// Re-export types and uuid modules from aranet-types for backwards compatibility
91pub use aranet_types::types;
92pub use aranet_types::uuid;
93
94// Core exports
95pub use device::Device;
96pub use error::{ConnectionFailureReason, DeviceNotFoundReason, Error, Result};
97pub use history::{HistoryInfo, HistoryOptions, HistoryParam};
98pub use readings::ExtendedReading;
99pub use scan::{
100 DiscoveredDevice, FindProgress, ProgressCallback, ScanOptions, find_device_with_progress,
101 scan_with_retry,
102};
103pub use settings::{BluetoothRange, CalibrationData, DeviceSettings, MeasurementInterval};
104pub use traits::AranetDevice;
105
106/// Type alias for a shared device reference.
107///
108/// This is the recommended way to share a `Device` across multiple tasks.
109/// Since `Device` intentionally does not implement `Clone` (to prevent
110/// connection ownership ambiguity), wrapping it in `Arc` is the standard
111/// pattern for concurrent access.
112///
113/// # Example
114///
115/// ```no_run
116/// use aranet_core::{Device, SharedDevice};
117/// use std::sync::Arc;
118///
119/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
120/// let device = Device::connect("Aranet4 12345").await?;
121/// let shared: SharedDevice = Arc::new(device);
122///
123/// // Clone the Arc to share across tasks
124/// let shared_clone = Arc::clone(&shared);
125/// tokio::spawn(async move {
126/// let reading = shared_clone.read_current().await;
127/// // ...
128/// });
129/// # Ok(())
130/// # }
131/// ```
132pub type SharedDevice = std::sync::Arc<Device>;
133
134// New module exports
135pub use advertisement::{AdvertisementData, parse_advertisement, parse_advertisement_with_name};
136pub use commands::{
137 HISTORY_V1_REQUEST, HISTORY_V2_REQUEST, SET_BLUETOOTH_RANGE, SET_INTERVAL, SET_SMART_HOME,
138};
139pub use events::{DeviceEvent, EventReceiver, EventSender};
140pub use guard::{DeviceGuard, SharedDeviceGuard};
141pub use manager::{DeviceManager, ManagedDevice, ManagerConfig};
142pub use messages::{CachedDevice, Command, SensorEvent};
143pub use metrics::{ConnectionMetrics, OperationMetrics};
144pub use mock::{MockDevice, MockDeviceBuilder};
145pub use reconnect::{ReconnectOptions, ReconnectingDevice};
146pub use retry::{RetryConfig, with_retry};
147pub use streaming::{ReadingStream, StreamOptions, StreamOptionsBuilder};
148pub use thresholds::{Co2Level, ThresholdConfig, Thresholds};
149pub use util::{create_identifier, format_peripheral_id};
150pub use validation::{ReadingValidator, ValidationResult, ValidationWarning};
151
152// Re-export from aranet-types
153pub use aranet_types::uuid as uuids;
154pub use aranet_types::{CurrentReading, DeviceInfo, DeviceType, HistoryRecord, Status};