hive_btle/
lib.rs

1// Copyright (c) 2025-2026 (r)evolve - Revolve Team LLC
2// SPDX-License-Identifier: Apache-2.0
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! HIVE-BTLE: Bluetooth Low Energy mesh transport for HIVE Protocol
17//!
18//! This crate provides BLE-based peer-to-peer mesh networking for HIVE,
19//! supporting discovery, advertisement, connectivity, and HIVE-Lite sync.
20//!
21//! ## Overview
22//!
23//! HIVE-BTLE implements the pluggable transport abstraction (ADR-032) for
24//! Bluetooth Low Energy, enabling HIVE Protocol to operate over BLE in
25//! resource-constrained environments like smartwatches.
26//!
27//! ## Key Features
28//!
29//! - **Cross-platform**: Linux, Android, macOS, iOS, Windows, ESP32
30//! - **Power efficient**: Designed for 18+ hour battery life on watches
31//! - **Long range**: Coded PHY support for 300m+ range
32//! - **HIVE-Lite sync**: Optimized CRDT sync over GATT
33//!
34//! ## Architecture
35//!
36//! ```text
37//! ┌─────────────────────────────────────────────────┐
38//! │                  Application                     │
39//! ├─────────────────────────────────────────────────┤
40//! │           BluetoothLETransport                   │
41//! │  (implements MeshTransport from ADR-032)        │
42//! ├─────────────────────────────────────────────────┤
43//! │              BleAdapter Trait                    │
44//! ├──────────┬──────────┬──────────┬────────────────┤
45//! │  Linux   │ Android  │  Apple   │    Windows     │
46//! │ (BlueZ)  │  (JNI)   │(CoreBT)  │    (WinRT)     │
47//! └──────────┴──────────┴──────────┴────────────────┘
48//! ```
49//!
50//! ## Quick Start
51//!
52//! ```ignore
53//! use hive_btle::{BleConfig, BluetoothLETransport, NodeId};
54//!
55//! // Create HIVE-Lite optimized config for battery efficiency
56//! let config = BleConfig::hive_lite(NodeId::new(0x12345678));
57//!
58//! // Create transport with platform adapter
59//! #[cfg(feature = "linux")]
60//! let adapter = hive_btle::platform::linux::BluerAdapter::new()?;
61//!
62//! let transport = BluetoothLETransport::new(config, adapter);
63//!
64//! // Start advertising and scanning
65//! transport.start().await?;
66//!
67//! // Connect to a peer
68//! let conn = transport.connect(&peer_id).await?;
69//! ```
70//!
71//! ## Feature Flags
72//!
73//! - `std` (default): Standard library support
74//! - `linux`: Linux/BlueZ support via `bluer`
75//! - `android`: Android support via JNI
76//! - `macos`: macOS support via CoreBluetooth
77//! - `ios`: iOS support via CoreBluetooth
78//! - `windows`: Windows support via WinRT
79//! - `embedded`: Embedded/no_std support
80//! - `coded-phy`: Enable Coded PHY for extended range
81//! - `extended-adv`: Enable extended advertising
82//!
83//! ## External Crate Usage (hive-ffi)
84//!
85//! This crate exports platform adapters for use by external crates like `hive-ffi`.
86//! Each platform adapter is conditionally exported based on feature flags:
87//!
88//! ```toml
89//! # In your Cargo.toml
90//! [dependencies]
91//! hive-btle = { version = "0.0.5", features = ["linux"] }
92//! ```
93//!
94//! Then use the appropriate adapter:
95//!
96//! ```ignore
97//! use hive_btle::{BleConfig, BluerAdapter, HiveMesh, NodeId};
98//!
99//! // Platform adapter is automatically available via feature flag
100//! let adapter = BluerAdapter::new().await?;
101//! let config = BleConfig::hive_lite(NodeId::new(0x12345678));
102//! ```
103//!
104//! ### Platform → Adapter Mapping
105//!
106//! | Feature | Target | Adapter Type |
107//! |---------|--------|--------------|
108//! | `linux` | Linux | `BluerAdapter` |
109//! | `android` | Android | `AndroidAdapter` |
110//! | `macos` | macOS | `CoreBluetoothAdapter` |
111//! | `ios` | iOS | `CoreBluetoothAdapter` |
112//! | `windows` | Windows | `WinRtBleAdapter` |
113//!
114//! ### Document Encoding for Translation Layer
115//!
116//! For translating between Automerge (full HIVE) and hive-btle documents:
117//!
118//! ```ignore
119//! use hive_btle::HiveDocument;
120//!
121//! // Decode bytes received from BLE
122//! let doc = HiveDocument::from_bytes(&received_bytes)?;
123//!
124//! // Encode for BLE transmission
125//! let bytes = doc.to_bytes();
126//! ```
127//!
128//! ## Power Profiles
129//!
130//! | Profile | Duty Cycle | Watch Battery |
131//! |---------|------------|---------------|
132//! | Aggressive | 20% | ~6 hours |
133//! | Balanced | 10% | ~12 hours |
134//! | **LowPower** | **2%** | **~20+ hours** |
135//!
136//! ## Related ADRs
137//!
138//! - ADR-039: HIVE-BTLE Mesh Transport Crate
139//! - ADR-032: Pluggable Transport Abstraction
140//! - ADR-035: HIVE-Lite Embedded Nodes
141//! - ADR-037: Resource-Constrained Device Optimization
142
143#![cfg_attr(not(feature = "std"), no_std)]
144#![warn(missing_docs)]
145#![warn(rustdoc::missing_crate_level_docs)]
146
147#[cfg(not(feature = "std"))]
148extern crate alloc;
149
150pub mod config;
151pub mod discovery;
152pub mod document;
153pub mod document_sync;
154pub mod error;
155pub mod gatt;
156#[cfg(feature = "std")]
157pub mod gossip;
158pub mod hive_mesh;
159pub mod mesh;
160pub mod observer;
161pub mod peer;
162pub mod peer_manager;
163#[cfg(feature = "std")]
164pub mod persistence;
165pub mod phy;
166pub mod platform;
167pub mod power;
168pub mod security;
169pub mod sync;
170pub mod transport;
171
172// Re-exports for convenience
173pub use config::{
174    BleConfig, BlePhy, DiscoveryConfig, GattConfig, MeshConfig, PowerProfile, DEFAULT_MESH_ID,
175};
176#[cfg(feature = "std")]
177pub use discovery::Scanner;
178pub use discovery::{Advertiser, HiveBeacon, ScanFilter};
179pub use error::{BleError, Result};
180#[cfg(feature = "std")]
181pub use gatt::HiveGattService;
182pub use gatt::SyncProtocol;
183#[cfg(feature = "std")]
184pub use mesh::MeshManager;
185pub use mesh::{MeshRouter, MeshTopology, TopologyConfig, TopologyEvent};
186pub use phy::{PhyCapabilities, PhyController, PhyStrategy};
187pub use platform::{BleAdapter, ConnectionEvent, DisconnectReason, DiscoveredDevice, StubAdapter};
188
189// Platform-specific adapter re-exports for external crates (hive-ffi)
190// These allow external crates to use platform adapters via feature flags
191#[cfg(all(feature = "linux", target_os = "linux"))]
192pub use platform::linux::BluerAdapter;
193
194#[cfg(feature = "android")]
195pub use platform::android::AndroidAdapter;
196
197#[cfg(any(feature = "macos", feature = "ios"))]
198pub use platform::apple::CoreBluetoothAdapter;
199
200#[cfg(feature = "windows")]
201pub use platform::windows::WinRtBleAdapter;
202
203#[cfg(feature = "std")]
204pub use platform::mock::MockBleAdapter;
205pub use power::{BatteryState, RadioScheduler, SyncPriority};
206pub use sync::{GattSyncProtocol, SyncConfig, SyncState};
207pub use transport::{BleConnection, BluetoothLETransport, MeshTransport, TransportCapabilities};
208
209// New centralized mesh management types
210pub use document::{
211    HiveDocument, MergeResult, ENCRYPTED_MARKER, EXTENDED_MARKER, KEY_EXCHANGE_MARKER,
212    PEER_E2EE_MARKER,
213};
214
215// Security (mesh-wide and per-peer encryption)
216pub use document_sync::{DocumentCheck, DocumentSync};
217#[cfg(feature = "std")]
218pub use hive_mesh::{DataReceivedResult, HiveMesh, HiveMeshConfig};
219#[cfg(feature = "std")]
220pub use observer::{CollectingObserver, ObserverManager};
221pub use observer::{DisconnectReason as HiveDisconnectReason, HiveEvent, HiveObserver};
222pub use peer::{
223    ConnectionState, ConnectionStateGraph, HivePeer, PeerConnectionState, PeerManagerConfig,
224    SignalStrength, StateCountSummary,
225};
226pub use peer_manager::PeerManager;
227// Phase 1: Mesh-wide encryption
228pub use security::{EncryptedDocument, EncryptionError, MeshEncryptionKey};
229// Phase 2: Per-peer E2EE
230#[cfg(feature = "std")]
231pub use security::{
232    KeyExchangeMessage, PeerEncryptedMessage, PeerIdentityKey, PeerSession, PeerSessionKey,
233    PeerSessionManager, SessionState,
234};
235
236// Gossip and persistence abstractions
237#[cfg(feature = "std")]
238pub use gossip::{BroadcastAll, EmergencyAware, GossipStrategy, RandomFanout, SignalBasedFanout};
239#[cfg(feature = "std")]
240pub use persistence::{DocumentStore, FileStore, MemoryStore, SharedStore};
241
242/// HIVE BLE Service UUID (128-bit)
243///
244/// All HIVE nodes advertise this UUID for discovery.
245pub const HIVE_SERVICE_UUID: uuid::Uuid = uuid::uuid!("f47ac10b-58cc-4372-a567-0e02b2c3d479");
246
247/// HIVE BLE Service UUID (16-bit short form)
248///
249/// Derived from the first two bytes of the 128-bit UUID (0xF47A from f47ac10b).
250/// Used for space-constrained advertising to fit within 31-byte limit.
251pub const HIVE_SERVICE_UUID_16BIT: u16 = 0xF47A;
252
253/// HIVE Node Info Characteristic UUID
254pub const CHAR_NODE_INFO_UUID: u16 = 0x0001;
255
256/// HIVE Sync State Characteristic UUID
257pub const CHAR_SYNC_STATE_UUID: u16 = 0x0002;
258
259/// HIVE Sync Data Characteristic UUID
260pub const CHAR_SYNC_DATA_UUID: u16 = 0x0003;
261
262/// HIVE Command Characteristic UUID
263pub const CHAR_COMMAND_UUID: u16 = 0x0004;
264
265/// HIVE Status Characteristic UUID
266pub const CHAR_STATUS_UUID: u16 = 0x0005;
267
268/// Crate version
269pub const VERSION: &str = env!("CARGO_PKG_VERSION");
270
271/// Node identifier
272///
273/// Represents a unique node in the HIVE mesh. For BLE, this is typically
274/// derived from the Bluetooth MAC address or a configured value.
275#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
276pub struct NodeId {
277    /// 32-bit node identifier
278    id: u32,
279}
280
281impl NodeId {
282    /// Create a new node ID from a 32-bit value
283    pub fn new(id: u32) -> Self {
284        Self { id }
285    }
286
287    /// Get the raw 32-bit ID value
288    pub fn as_u32(&self) -> u32 {
289        self.id
290    }
291
292    /// Create from a string representation (hex format)
293    pub fn parse(s: &str) -> Option<Self> {
294        // Try parsing as hex (with or without 0x prefix)
295        let s = s.trim_start_matches("0x").trim_start_matches("0X");
296        u32::from_str_radix(s, 16).ok().map(Self::new)
297    }
298
299    /// Derive a NodeId from a BLE MAC address.
300    ///
301    /// Uses the last 4 bytes of the 6-byte MAC address as the 32-bit node ID.
302    /// This provides a consistent node ID derived from the device's Bluetooth
303    /// hardware address.
304    ///
305    /// # Arguments
306    /// * `mac` - 6-byte MAC address array (e.g., [0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF])
307    ///
308    /// # Example
309    /// ```
310    /// use hive_btle::NodeId;
311    ///
312    /// let mac = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55];
313    /// let node_id = NodeId::from_mac_address(&mac);
314    /// assert_eq!(node_id.as_u32(), 0x22334455);
315    /// ```
316    pub fn from_mac_address(mac: &[u8; 6]) -> Self {
317        // Use last 4 bytes: mac[2], mac[3], mac[4], mac[5]
318        let id = ((mac[2] as u32) << 24)
319            | ((mac[3] as u32) << 16)
320            | ((mac[4] as u32) << 8)
321            | (mac[5] as u32);
322        Self::new(id)
323    }
324
325    /// Derive a NodeId from a MAC address string.
326    ///
327    /// Parses a MAC address in "AA:BB:CC:DD:EE:FF" format and derives
328    /// the node ID from the last 4 bytes.
329    ///
330    /// # Arguments
331    /// * `mac_str` - MAC address string in colon-separated hex format
332    ///
333    /// # Returns
334    /// `Some(NodeId)` if parsing succeeds, `None` otherwise
335    ///
336    /// # Example
337    /// ```
338    /// use hive_btle::NodeId;
339    ///
340    /// let node_id = NodeId::from_mac_string("00:11:22:33:44:55").unwrap();
341    /// assert_eq!(node_id.as_u32(), 0x22334455);
342    /// ```
343    pub fn from_mac_string(mac_str: &str) -> Option<Self> {
344        let parts: Vec<&str> = mac_str.split(':').collect();
345        if parts.len() != 6 {
346            return None;
347        }
348
349        let mut mac = [0u8; 6];
350        for (i, part) in parts.iter().enumerate() {
351            mac[i] = u8::from_str_radix(part, 16).ok()?;
352        }
353
354        Some(Self::from_mac_address(&mac))
355    }
356}
357
358impl core::fmt::Display for NodeId {
359    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
360        write!(f, "{:08X}", self.id)
361    }
362}
363
364impl From<u32> for NodeId {
365    fn from(id: u32) -> Self {
366        Self::new(id)
367    }
368}
369
370impl From<NodeId> for u32 {
371    fn from(node_id: NodeId) -> Self {
372        node_id.id
373    }
374}
375
376/// Node capability flags
377///
378/// Advertised in the HIVE beacon to indicate what this node can do.
379pub mod capabilities {
380    /// This is a HIVE-Lite node (minimal state, single parent)
381    pub const LITE_NODE: u16 = 0x0001;
382    /// Has accelerometer sensor
383    pub const SENSOR_ACCEL: u16 = 0x0002;
384    /// Has temperature sensor
385    pub const SENSOR_TEMP: u16 = 0x0004;
386    /// Has button input
387    pub const SENSOR_BUTTON: u16 = 0x0008;
388    /// Has LED output
389    pub const ACTUATOR_LED: u16 = 0x0010;
390    /// Has vibration motor
391    pub const ACTUATOR_VIBRATE: u16 = 0x0020;
392    /// Has display
393    pub const HAS_DISPLAY: u16 = 0x0040;
394    /// Can relay messages (not a leaf)
395    pub const CAN_RELAY: u16 = 0x0080;
396    /// Supports Coded PHY
397    pub const CODED_PHY: u16 = 0x0100;
398    /// Has GPS
399    pub const HAS_GPS: u16 = 0x0200;
400}
401
402/// Hierarchy levels in the HIVE mesh
403#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
404#[repr(u8)]
405pub enum HierarchyLevel {
406    /// Platform/soldier level (leaf nodes)
407    #[default]
408    Platform = 0,
409    /// Squad level
410    Squad = 1,
411    /// Platoon level
412    Platoon = 2,
413    /// Company level
414    Company = 3,
415}
416
417impl From<u8> for HierarchyLevel {
418    fn from(value: u8) -> Self {
419        match value {
420            0 => HierarchyLevel::Platform,
421            1 => HierarchyLevel::Squad,
422            2 => HierarchyLevel::Platoon,
423            3 => HierarchyLevel::Company,
424            _ => HierarchyLevel::Platform,
425        }
426    }
427}
428
429impl From<HierarchyLevel> for u8 {
430    fn from(level: HierarchyLevel) -> Self {
431        level as u8
432    }
433}
434
435#[cfg(test)]
436mod tests {
437    use super::*;
438
439    #[test]
440    fn test_node_id() {
441        let id = NodeId::new(0x12345678);
442        assert_eq!(id.as_u32(), 0x12345678);
443        assert_eq!(id.to_string(), "12345678");
444    }
445
446    #[test]
447    fn test_node_id_parse() {
448        assert_eq!(NodeId::parse("12345678").unwrap().as_u32(), 0x12345678);
449        assert_eq!(NodeId::parse("0x12345678").unwrap().as_u32(), 0x12345678);
450        assert!(NodeId::parse("not_hex").is_none());
451    }
452
453    #[test]
454    fn test_node_id_from_mac_address() {
455        // MAC: AA:BB:CC:DD:EE:FF -> NodeId from last 4 bytes: 0xCCDDEEFF
456        let mac = [0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF];
457        let node_id = NodeId::from_mac_address(&mac);
458        assert_eq!(node_id.as_u32(), 0xCCDDEEFF);
459    }
460
461    #[test]
462    fn test_node_id_from_mac_string() {
463        let node_id = NodeId::from_mac_string("AA:BB:CC:DD:EE:FF").unwrap();
464        assert_eq!(node_id.as_u32(), 0xCCDDEEFF);
465
466        // Lowercase should work too
467        let node_id = NodeId::from_mac_string("aa:bb:cc:dd:ee:ff").unwrap();
468        assert_eq!(node_id.as_u32(), 0xCCDDEEFF);
469
470        // Invalid formats
471        assert!(NodeId::from_mac_string("invalid").is_none());
472        assert!(NodeId::from_mac_string("AA:BB:CC:DD:EE").is_none()); // Too short
473        assert!(NodeId::from_mac_string("AA:BB:CC:DD:EE:FF:GG").is_none()); // Too long
474        assert!(NodeId::from_mac_string("ZZ:BB:CC:DD:EE:FF").is_none()); // Invalid hex
475    }
476
477    #[test]
478    fn test_hierarchy_level() {
479        assert_eq!(HierarchyLevel::from(0), HierarchyLevel::Platform);
480        assert_eq!(HierarchyLevel::from(3), HierarchyLevel::Company);
481        assert_eq!(u8::from(HierarchyLevel::Squad), 1);
482    }
483
484    #[test]
485    fn test_service_uuid() {
486        assert_eq!(
487            HIVE_SERVICE_UUID.to_string(),
488            "f47ac10b-58cc-4372-a567-0e02b2c3d479"
489        );
490    }
491
492    #[test]
493    fn test_capabilities() {
494        let caps = capabilities::LITE_NODE | capabilities::SENSOR_ACCEL | capabilities::HAS_GPS;
495        assert_eq!(caps, 0x0203);
496    }
497}