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