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 relay;
169pub mod security;
170pub mod sync;
171pub mod transport;
172
173// Re-exports for convenience
174pub use config::{
175 BleConfig, BlePhy, DiscoveryConfig, GattConfig, MeshConfig, PowerProfile, DEFAULT_MESH_ID,
176};
177#[cfg(feature = "std")]
178pub use discovery::Scanner;
179pub use discovery::{Advertiser, HiveBeacon, ScanFilter};
180pub use error::{BleError, Result};
181#[cfg(feature = "std")]
182pub use gatt::HiveGattService;
183pub use gatt::SyncProtocol;
184#[cfg(feature = "std")]
185pub use mesh::MeshManager;
186pub use mesh::{MeshRouter, MeshTopology, TopologyConfig, TopologyEvent};
187pub use phy::{PhyCapabilities, PhyController, PhyStrategy};
188pub use platform::{BleAdapter, ConnectionEvent, DisconnectReason, DiscoveredDevice, StubAdapter};
189
190// Platform-specific adapter re-exports for external crates (hive-ffi)
191// These allow external crates to use platform adapters via feature flags
192#[cfg(all(feature = "linux", target_os = "linux"))]
193pub use platform::linux::BluerAdapter;
194
195#[cfg(feature = "android")]
196pub use platform::android::AndroidAdapter;
197
198#[cfg(any(feature = "macos", feature = "ios"))]
199pub use platform::apple::CoreBluetoothAdapter;
200
201#[cfg(feature = "windows")]
202pub use platform::windows::WinRtBleAdapter;
203
204#[cfg(feature = "std")]
205pub use platform::mock::MockBleAdapter;
206pub use power::{BatteryState, RadioScheduler, SyncPriority};
207pub use sync::{GattSyncProtocol, SyncConfig, SyncState};
208pub use transport::{BleConnection, BluetoothLETransport, MeshTransport, TransportCapabilities};
209
210// New centralized mesh management types
211pub use document::{
212 HiveDocument, MergeResult, ENCRYPTED_MARKER, EXTENDED_MARKER, KEY_EXCHANGE_MARKER,
213 PEER_E2EE_MARKER,
214};
215
216// Security (mesh-wide and per-peer encryption)
217pub use document_sync::{DocumentCheck, DocumentSync};
218#[cfg(feature = "std")]
219pub use hive_mesh::{DataReceivedResult, HiveMesh, HiveMeshConfig, RelayDecision};
220#[cfg(feature = "std")]
221pub use observer::{CollectingObserver, ObserverManager};
222pub use observer::{DisconnectReason as HiveDisconnectReason, HiveEvent, HiveObserver};
223pub use peer::{
224 ConnectionState, ConnectionStateGraph, FullStateCountSummary, HivePeer, IndirectPeer,
225 PeerConnectionState, PeerDegree, PeerManagerConfig, SignalStrength, StateCountSummary,
226 MAX_TRACKED_DEGREE,
227};
228pub use peer_manager::PeerManager;
229// Phase 1: Mesh-wide encryption
230pub use security::{EncryptedDocument, EncryptionError, MeshEncryptionKey};
231// Phase 2: Per-peer E2EE
232#[cfg(feature = "std")]
233pub use security::{
234 KeyExchangeMessage, PeerEncryptedMessage, PeerIdentityKey, PeerSession, PeerSessionKey,
235 PeerSessionManager, SessionState,
236};
237
238// Gossip and persistence abstractions
239#[cfg(feature = "std")]
240pub use gossip::{BroadcastAll, EmergencyAware, GossipStrategy, RandomFanout, SignalBasedFanout};
241#[cfg(feature = "std")]
242pub use persistence::{DocumentStore, FileStore, MemoryStore, SharedStore};
243
244// Multi-hop relay support
245pub use relay::{
246 MessageId, RelayEnvelope, RelayFlags, SeenMessageCache, DEFAULT_MAX_HOPS, DEFAULT_SEEN_TTL_MS,
247 RELAY_ENVELOPE_MARKER,
248};
249
250/// HIVE BLE Service UUID (128-bit)
251///
252/// All HIVE nodes advertise this UUID for discovery.
253pub const HIVE_SERVICE_UUID: uuid::Uuid = uuid::uuid!("f47ac10b-58cc-4372-a567-0e02b2c3d479");
254
255/// HIVE BLE Service UUID (16-bit short form)
256///
257/// Derived from the first two bytes of the 128-bit UUID (0xF47A from f47ac10b).
258/// Used for space-constrained advertising to fit within 31-byte limit.
259pub const HIVE_SERVICE_UUID_16BIT: u16 = 0xF47A;
260
261/// HIVE Node Info Characteristic UUID
262pub const CHAR_NODE_INFO_UUID: u16 = 0x0001;
263
264/// HIVE Sync State Characteristic UUID
265pub const CHAR_SYNC_STATE_UUID: u16 = 0x0002;
266
267/// HIVE Sync Data Characteristic UUID
268pub const CHAR_SYNC_DATA_UUID: u16 = 0x0003;
269
270/// HIVE Command Characteristic UUID
271pub const CHAR_COMMAND_UUID: u16 = 0x0004;
272
273/// HIVE Status Characteristic UUID
274pub const CHAR_STATUS_UUID: u16 = 0x0005;
275
276/// Crate version
277pub const VERSION: &str = env!("CARGO_PKG_VERSION");
278
279/// Node identifier
280///
281/// Represents a unique node in the HIVE mesh. For BLE, this is typically
282/// derived from the Bluetooth MAC address or a configured value.
283#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
284pub struct NodeId {
285 /// 32-bit node identifier
286 id: u32,
287}
288
289impl NodeId {
290 /// Create a new node ID from a 32-bit value
291 pub fn new(id: u32) -> Self {
292 Self { id }
293 }
294
295 /// Get the raw 32-bit ID value
296 pub fn as_u32(&self) -> u32 {
297 self.id
298 }
299
300 /// Create from a string representation (hex format)
301 pub fn parse(s: &str) -> Option<Self> {
302 // Try parsing as hex (with or without 0x prefix)
303 let s = s.trim_start_matches("0x").trim_start_matches("0X");
304 u32::from_str_radix(s, 16).ok().map(Self::new)
305 }
306
307 /// Derive a NodeId from a BLE MAC address.
308 ///
309 /// Uses the last 4 bytes of the 6-byte MAC address as the 32-bit node ID.
310 /// This provides a consistent node ID derived from the device's Bluetooth
311 /// hardware address.
312 ///
313 /// # Arguments
314 /// * `mac` - 6-byte MAC address array (e.g., [0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF])
315 ///
316 /// # Example
317 /// ```
318 /// use hive_btle::NodeId;
319 ///
320 /// let mac = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55];
321 /// let node_id = NodeId::from_mac_address(&mac);
322 /// assert_eq!(node_id.as_u32(), 0x22334455);
323 /// ```
324 pub fn from_mac_address(mac: &[u8; 6]) -> Self {
325 // Use last 4 bytes: mac[2], mac[3], mac[4], mac[5]
326 let id = ((mac[2] as u32) << 24)
327 | ((mac[3] as u32) << 16)
328 | ((mac[4] as u32) << 8)
329 | (mac[5] as u32);
330 Self::new(id)
331 }
332
333 /// Derive a NodeId from a MAC address string.
334 ///
335 /// Parses a MAC address in "AA:BB:CC:DD:EE:FF" format and derives
336 /// the node ID from the last 4 bytes.
337 ///
338 /// # Arguments
339 /// * `mac_str` - MAC address string in colon-separated hex format
340 ///
341 /// # Returns
342 /// `Some(NodeId)` if parsing succeeds, `None` otherwise
343 ///
344 /// # Example
345 /// ```
346 /// use hive_btle::NodeId;
347 ///
348 /// let node_id = NodeId::from_mac_string("00:11:22:33:44:55").unwrap();
349 /// assert_eq!(node_id.as_u32(), 0x22334455);
350 /// ```
351 pub fn from_mac_string(mac_str: &str) -> Option<Self> {
352 let parts: Vec<&str> = mac_str.split(':').collect();
353 if parts.len() != 6 {
354 return None;
355 }
356
357 let mut mac = [0u8; 6];
358 for (i, part) in parts.iter().enumerate() {
359 mac[i] = u8::from_str_radix(part, 16).ok()?;
360 }
361
362 Some(Self::from_mac_address(&mac))
363 }
364}
365
366impl core::fmt::Display for NodeId {
367 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
368 write!(f, "{:08X}", self.id)
369 }
370}
371
372impl From<u32> for NodeId {
373 fn from(id: u32) -> Self {
374 Self::new(id)
375 }
376}
377
378impl From<NodeId> for u32 {
379 fn from(node_id: NodeId) -> Self {
380 node_id.id
381 }
382}
383
384/// Node capability flags
385///
386/// Advertised in the HIVE beacon to indicate what this node can do.
387pub mod capabilities {
388 /// This is a HIVE-Lite node (minimal state, single parent)
389 pub const LITE_NODE: u16 = 0x0001;
390 /// Has accelerometer sensor
391 pub const SENSOR_ACCEL: u16 = 0x0002;
392 /// Has temperature sensor
393 pub const SENSOR_TEMP: u16 = 0x0004;
394 /// Has button input
395 pub const SENSOR_BUTTON: u16 = 0x0008;
396 /// Has LED output
397 pub const ACTUATOR_LED: u16 = 0x0010;
398 /// Has vibration motor
399 pub const ACTUATOR_VIBRATE: u16 = 0x0020;
400 /// Has display
401 pub const HAS_DISPLAY: u16 = 0x0040;
402 /// Can relay messages (not a leaf)
403 pub const CAN_RELAY: u16 = 0x0080;
404 /// Supports Coded PHY
405 pub const CODED_PHY: u16 = 0x0100;
406 /// Has GPS
407 pub const HAS_GPS: u16 = 0x0200;
408}
409
410/// Hierarchy levels in the HIVE mesh
411#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
412#[repr(u8)]
413pub enum HierarchyLevel {
414 /// Platform/soldier level (leaf nodes)
415 #[default]
416 Platform = 0,
417 /// Squad level
418 Squad = 1,
419 /// Platoon level
420 Platoon = 2,
421 /// Company level
422 Company = 3,
423}
424
425impl From<u8> for HierarchyLevel {
426 fn from(value: u8) -> Self {
427 match value {
428 0 => HierarchyLevel::Platform,
429 1 => HierarchyLevel::Squad,
430 2 => HierarchyLevel::Platoon,
431 3 => HierarchyLevel::Company,
432 _ => HierarchyLevel::Platform,
433 }
434 }
435}
436
437impl From<HierarchyLevel> for u8 {
438 fn from(level: HierarchyLevel) -> Self {
439 level as u8
440 }
441}
442
443#[cfg(test)]
444mod tests {
445 use super::*;
446
447 #[test]
448 fn test_node_id() {
449 let id = NodeId::new(0x12345678);
450 assert_eq!(id.as_u32(), 0x12345678);
451 assert_eq!(id.to_string(), "12345678");
452 }
453
454 #[test]
455 fn test_node_id_parse() {
456 assert_eq!(NodeId::parse("12345678").unwrap().as_u32(), 0x12345678);
457 assert_eq!(NodeId::parse("0x12345678").unwrap().as_u32(), 0x12345678);
458 assert!(NodeId::parse("not_hex").is_none());
459 }
460
461 #[test]
462 fn test_node_id_from_mac_address() {
463 // MAC: AA:BB:CC:DD:EE:FF -> NodeId from last 4 bytes: 0xCCDDEEFF
464 let mac = [0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF];
465 let node_id = NodeId::from_mac_address(&mac);
466 assert_eq!(node_id.as_u32(), 0xCCDDEEFF);
467 }
468
469 #[test]
470 fn test_node_id_from_mac_string() {
471 let node_id = NodeId::from_mac_string("AA:BB:CC:DD:EE:FF").unwrap();
472 assert_eq!(node_id.as_u32(), 0xCCDDEEFF);
473
474 // Lowercase should work too
475 let node_id = NodeId::from_mac_string("aa:bb:cc:dd:ee:ff").unwrap();
476 assert_eq!(node_id.as_u32(), 0xCCDDEEFF);
477
478 // Invalid formats
479 assert!(NodeId::from_mac_string("invalid").is_none());
480 assert!(NodeId::from_mac_string("AA:BB:CC:DD:EE").is_none()); // Too short
481 assert!(NodeId::from_mac_string("AA:BB:CC:DD:EE:FF:GG").is_none()); // Too long
482 assert!(NodeId::from_mac_string("ZZ:BB:CC:DD:EE:FF").is_none()); // Invalid hex
483 }
484
485 #[test]
486 fn test_hierarchy_level() {
487 assert_eq!(HierarchyLevel::from(0), HierarchyLevel::Platform);
488 assert_eq!(HierarchyLevel::from(3), HierarchyLevel::Company);
489 assert_eq!(u8::from(HierarchyLevel::Squad), 1);
490 }
491
492 #[test]
493 fn test_service_uuid() {
494 assert_eq!(
495 HIVE_SERVICE_UUID.to_string(),
496 "f47ac10b-58cc-4372-a567-0e02b2c3d479"
497 );
498 }
499
500 #[test]
501 fn test_capabilities() {
502 let caps = capabilities::LITE_NODE | capabilities::SENSOR_ACCEL | capabilities::HAS_GPS;
503 assert_eq!(caps, 0x0203);
504 }
505}