peat_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//! PEAT-BTLE: Bluetooth Low Energy mesh transport for Peat Protocol
17//!
18//! This crate provides BLE-based peer-to-peer mesh networking for Peat,
19//! supporting discovery, advertisement, connectivity, and Peat-Lite sync.
20//!
21//! ## Overview
22//!
23//! PEAT-BTLE implements the pluggable transport abstraction (ADR-032) for
24//! Bluetooth Low Energy, enabling Peat 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//! - **Peat-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 peat_btle::{BleConfig, BluetoothLETransport, NodeId};
54//!
55//! // Create Peat-Lite optimized config for battery efficiency
56//! let config = BleConfig::peat_lite(NodeId::new(0x12345678));
57//!
58//! // Create transport with platform adapter
59//! #[cfg(feature = "linux")]
60//! let adapter = peat_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//! - `transport-only`: Pure BLE transport, no app-layer CRDTs
75//! - `legacy-chat`: Deprecated ChatCRDT support (will be removed in 0.2.0)
76//! - `linux`: Linux/BlueZ support via `bluer`
77//! - `android`: Android support via JNI
78//! - `macos`: macOS support via CoreBluetooth
79//! - `ios`: iOS support via CoreBluetooth
80//! - `windows`: Windows support via WinRT
81//! - `embedded`: Embedded/no_std support
82//! - `coded-phy`: Enable Coded PHY for extended range
83//! - `extended-adv`: Enable extended advertising
84//!
85//! ## External Crate Usage (peat-ffi)
86//!
87//! This crate exports platform adapters for use by external crates like `peat-ffi`.
88//! Each platform adapter is conditionally exported based on feature flags:
89//!
90//! ```toml
91//! # In your Cargo.toml
92//! [dependencies]
93//! peat-btle = { version = "0.2.0", features = ["linux"] }
94//! ```
95//!
96//! Then use the appropriate adapter:
97//!
98//! ```ignore
99//! use peat_btle::{BleConfig, BluerAdapter, PeatMesh, NodeId};
100//!
101//! // Platform adapter is automatically available via feature flag
102//! let adapter = BluerAdapter::new().await?;
103//! let config = BleConfig::peat_lite(NodeId::new(0x12345678));
104//! ```
105//!
106//! ### Platform → Adapter Mapping
107//!
108//! | Feature | Target | Adapter Type |
109//! |---------|--------|--------------|
110//! | `linux` | Linux | `BluerAdapter` |
111//! | `android` | Android | `AndroidAdapter` |
112//! | `macos` | macOS | `CoreBluetoothAdapter` |
113//! | `ios` | iOS | `CoreBluetoothAdapter` |
114//! | `windows` | Windows | `WinRtBleAdapter` |
115//!
116//! ### Document Encoding for Translation Layer
117//!
118//! For translating between Automerge (full Peat) and peat-btle documents:
119//!
120//! ```ignore
121//! use peat_btle::PeatDocument;
122//!
123//! // Decode bytes received from BLE
124//! let doc = PeatDocument::from_bytes(&received_bytes)?;
125//!
126//! // Encode for BLE transmission
127//! let bytes = doc.to_bytes();
128//! ```
129//!
130//! ## Power Profiles
131//!
132//! | Profile | Duty Cycle | Watch Battery |
133//! |---------|------------|---------------|
134//! | Aggressive | 20% | ~6 hours |
135//! | Balanced | 10% | ~12 hours |
136//! | **LowPower** | **2%** | **~20+ hours** |
137//!
138//! ## Related ADRs
139//!
140//! - ADR-039: PEAT-BTLE Mesh Transport Crate
141//! - ADR-032: Pluggable Transport Abstraction
142//! - ADR-035: Peat-Lite Embedded Nodes
143//! - ADR-037: Resource-Constrained Device Optimization
144
145#![cfg_attr(not(feature = "std"), no_std)]
146#![warn(missing_docs)]
147#![warn(rustdoc::missing_crate_level_docs)]
148
149#[cfg(not(feature = "std"))]
150extern crate alloc;
151
152pub mod address_rotation;
153pub mod config;
154pub mod discovery;
155pub mod document;
156pub mod document_sync;
157pub mod error;
158pub mod gatt;
159#[cfg(feature = "std")]
160pub mod gossip;
161pub mod mesh;
162pub mod observer;
163pub mod peat_mesh;
164pub mod peer;
165pub mod peer_lifetime;
166pub mod peer_manager;
167#[cfg(feature = "std")]
168pub mod persistence;
169pub mod phy;
170pub mod platform;
171pub mod power;
172pub mod reconnect;
173pub mod registry;
174pub mod relay;
175
176pub mod security;
177pub mod sync;
178pub mod transport;
179
180// UniFFI bindings (generates Kotlin + Swift)
181#[cfg(feature = "uniffi")]
182pub mod uniffi_bindings;
183
184// UniFFI scaffolding - must be at crate root
185#[cfg(feature = "uniffi")]
186uniffi::setup_scaffolding!();
187
188// Re-exports for convenience
189pub use config::{
190 BleConfig, BlePhy, DiscoveryConfig, GattConfig, MeshConfig, PowerProfile, DEFAULT_MESH_ID,
191};
192#[cfg(feature = "std")]
193pub use discovery::Scanner;
194pub use discovery::{Advertiser, PeatBeacon, ScanFilter};
195pub use error::{BleError, Result};
196#[cfg(feature = "std")]
197pub use gatt::PeatGattService;
198pub use gatt::SyncProtocol;
199#[cfg(feature = "std")]
200pub use mesh::MeshManager;
201pub use mesh::{MeshRouter, MeshTopology, TopologyConfig, TopologyEvent};
202pub use phy::{PhyCapabilities, PhyController, PhyStrategy};
203pub use platform::{BleAdapter, ConnectionEvent, DisconnectReason, DiscoveredDevice, StubAdapter};
204
205// Platform-specific adapter re-exports for external crates (peat-ffi)
206// These allow external crates to use platform adapters via feature flags
207#[cfg(all(feature = "linux", target_os = "linux"))]
208pub use platform::linux::BluerAdapter;
209
210#[cfg(feature = "android")]
211pub use platform::android::AndroidAdapter;
212
213#[cfg(any(feature = "macos", feature = "ios"))]
214pub use platform::apple::CoreBluetoothAdapter;
215
216#[cfg(feature = "windows")]
217pub use platform::windows::WinRtBleAdapter;
218
219#[cfg(feature = "std")]
220pub use platform::mock::MockBleAdapter;
221pub use power::{BatteryState, RadioScheduler, SyncPriority};
222pub use sync::{GattSyncProtocol, SyncConfig, SyncState};
223pub use transport::{BleConnection, BluetoothLETransport, MeshTransport, TransportCapabilities};
224
225// New centralized mesh management types
226pub use document::{
227 MergeResult, PeatDocument, ENCRYPTED_MARKER, EXTENDED_MARKER, KEY_EXCHANGE_MARKER,
228 PEER_E2EE_MARKER,
229};
230
231// Security (mesh-wide and per-peer encryption)
232pub use document_sync::{DocumentCheck, DocumentSync};
233#[cfg(feature = "std")]
234pub use observer::{CollectingObserver, ObserverManager};
235pub use observer::{DisconnectReason as PeatDisconnectReason, PeatEvent, PeatObserver};
236#[cfg(feature = "std")]
237pub use peat_mesh::{DataReceivedResult, PeatMesh, PeatMeshConfig, RelayDecision};
238pub use peer::{
239 ConnectionState, ConnectionStateGraph, FullStateCountSummary, IndirectPeer, PeatPeer,
240 PeerConnectionState, PeerDegree, PeerManagerConfig, SignalStrength, StateCountSummary,
241 MAX_TRACKED_DEGREE,
242};
243pub use peer_manager::PeerManager;
244
245// Device identity and attestation
246pub use security::{
247 DeviceIdentity, IdentityAttestation, IdentityError, IdentityRecord, IdentityRegistry,
248 RegistryResult,
249};
250// Mesh genesis and credentials
251pub use security::{MembershipPolicy, MeshCredentials, MeshGenesis};
252
253// Phase 1: Mesh-wide encryption
254pub use security::{EncryptedDocument, EncryptionError, MeshEncryptionKey};
255// Phase 2: Per-peer E2EE
256#[cfg(feature = "std")]
257pub use security::{
258 KeyExchangeMessage, PeerEncryptedMessage, PeerIdentityKey, PeerSession, PeerSessionKey,
259 PeerSessionManager, SessionState,
260};
261
262// Credential persistence
263#[cfg(feature = "std")]
264pub use security::{
265 MemoryStorage, PersistedState, PersistenceError, SecureStorage, PERSISTED_STATE_VERSION,
266};
267
268// Gossip and persistence abstractions
269#[cfg(feature = "std")]
270pub use gossip::{BroadcastAll, EmergencyAware, GossipStrategy, RandomFanout, SignalBasedFanout};
271#[cfg(feature = "std")]
272pub use persistence::{DocumentStore, FileStore, MemoryStore, SharedStore};
273
274// Multi-hop relay support
275pub use relay::{
276 MessageId, RelayEnvelope, RelayFlags, SeenMessageCache, DEFAULT_MAX_HOPS, DEFAULT_SEEN_TTL_MS,
277 RELAY_ENVELOPE_MARKER,
278};
279
280// Extensible document registry for app-layer types
281pub use registry::{
282 decode_header, decode_typed, encode_with_header, AppOperation, DocumentRegistry, DocumentType,
283 APP_OP_BASE, APP_TYPE_MAX, APP_TYPE_MIN,
284};
285
286/// Peat BLE Service UUID (128-bit)
287///
288/// All Peat nodes advertise this UUID for discovery.
289pub const PEAT_SERVICE_UUID: uuid::Uuid = uuid::uuid!("a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d");
290
291/// Peat BLE Service UUID (16-bit short form)
292///
293/// Derived from the first two bytes of the 128-bit UUID (0xA1B2 from a1b2c3d4).
294/// Used for space-constrained advertising to fit within 31-byte limit.
295pub const PEAT_SERVICE_UUID_16BIT: u16 = 0xA1B2;
296
297/// PEAT Node Info Characteristic UUID
298pub const CHAR_NODE_INFO_UUID: u16 = 0x0001;
299
300/// PEAT Sync State Characteristic UUID
301pub const CHAR_SYNC_STATE_UUID: u16 = 0x0002;
302
303/// PEAT Sync Data Characteristic UUID
304pub const CHAR_SYNC_DATA_UUID: u16 = 0x0003;
305
306/// PEAT Command Characteristic UUID
307pub const CHAR_COMMAND_UUID: u16 = 0x0004;
308
309/// PEAT Status Characteristic UUID
310pub const CHAR_STATUS_UUID: u16 = 0x0005;
311
312/// Crate version
313pub const VERSION: &str = env!("CARGO_PKG_VERSION");
314
315/// Node identifier
316///
317/// Represents a unique node in the Peat mesh. For BLE, this is typically
318/// derived from the Bluetooth MAC address or a configured value.
319#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
320pub struct NodeId {
321 /// 32-bit node identifier
322 id: u32,
323}
324
325impl NodeId {
326 /// Create a new node ID from a 32-bit value
327 pub fn new(id: u32) -> Self {
328 Self { id }
329 }
330
331 /// Get the raw 32-bit ID value
332 pub fn as_u32(&self) -> u32 {
333 self.id
334 }
335
336 /// Create from a string representation (hex format)
337 pub fn parse(s: &str) -> Option<Self> {
338 // Try parsing as hex (with or without 0x prefix)
339 let s = s.trim_start_matches("0x").trim_start_matches("0X");
340 u32::from_str_radix(s, 16).ok().map(Self::new)
341 }
342
343 /// Derive a NodeId from a BLE MAC address.
344 ///
345 /// Uses the last 4 bytes of the 6-byte MAC address as the 32-bit node ID.
346 /// This provides a consistent node ID derived from the device's Bluetooth
347 /// hardware address.
348 ///
349 /// # Arguments
350 /// * `mac` - 6-byte MAC address array (e.g., [0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF])
351 ///
352 /// # Example
353 /// ```
354 /// use peat_btle::NodeId;
355 ///
356 /// let mac = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55];
357 /// let node_id = NodeId::from_mac_address(&mac);
358 /// assert_eq!(node_id.as_u32(), 0x22334455);
359 /// ```
360 pub fn from_mac_address(mac: &[u8; 6]) -> Self {
361 // Use last 4 bytes: mac[2], mac[3], mac[4], mac[5]
362 let id = ((mac[2] as u32) << 24)
363 | ((mac[3] as u32) << 16)
364 | ((mac[4] as u32) << 8)
365 | (mac[5] as u32);
366 Self::new(id)
367 }
368
369 /// Derive a NodeId from a MAC address string.
370 ///
371 /// Parses a MAC address in "AA:BB:CC:DD:EE:FF" format and derives
372 /// the node ID from the last 4 bytes.
373 ///
374 /// # Arguments
375 /// * `mac_str` - MAC address string in colon-separated hex format
376 ///
377 /// # Returns
378 /// `Some(NodeId)` if parsing succeeds, `None` otherwise
379 ///
380 /// # Example
381 /// ```
382 /// use peat_btle::NodeId;
383 ///
384 /// let node_id = NodeId::from_mac_string("00:11:22:33:44:55").unwrap();
385 /// assert_eq!(node_id.as_u32(), 0x22334455);
386 /// ```
387 pub fn from_mac_string(mac_str: &str) -> Option<Self> {
388 let parts: Vec<&str> = mac_str.split(':').collect();
389 if parts.len() != 6 {
390 return None;
391 }
392
393 let mut mac = [0u8; 6];
394 for (i, part) in parts.iter().enumerate() {
395 mac[i] = u8::from_str_radix(part, 16).ok()?;
396 }
397
398 Some(Self::from_mac_address(&mac))
399 }
400}
401
402impl core::fmt::Display for NodeId {
403 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
404 write!(f, "{:08X}", self.id)
405 }
406}
407
408impl From<u32> for NodeId {
409 fn from(id: u32) -> Self {
410 Self::new(id)
411 }
412}
413
414impl From<NodeId> for u32 {
415 fn from(node_id: NodeId) -> Self {
416 node_id.id
417 }
418}
419
420/// Node capability flags
421///
422/// Advertised in the Peat beacon to indicate what this node can do.
423pub mod capabilities {
424 /// This is an Peat-Lite node (minimal state, single parent)
425 pub const LITE_NODE: u16 = 0x0001;
426 /// Has accelerometer sensor
427 pub const SENSOR_ACCEL: u16 = 0x0002;
428 /// Has temperature sensor
429 pub const SENSOR_TEMP: u16 = 0x0004;
430 /// Has button input
431 pub const SENSOR_BUTTON: u16 = 0x0008;
432 /// Has LED output
433 pub const ACTUATOR_LED: u16 = 0x0010;
434 /// Has vibration motor
435 pub const ACTUATOR_VIBRATE: u16 = 0x0020;
436 /// Has display
437 pub const HAS_DISPLAY: u16 = 0x0040;
438 /// Can relay messages (not a leaf)
439 pub const CAN_RELAY: u16 = 0x0080;
440 /// Supports Coded PHY
441 pub const CODED_PHY: u16 = 0x0100;
442 /// Has GPS
443 pub const HAS_GPS: u16 = 0x0200;
444}
445
446/// Hierarchy levels in the Peat mesh
447#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
448#[repr(u8)]
449pub enum HierarchyLevel {
450 /// Platform/soldier level (leaf nodes)
451 #[default]
452 Platform = 0,
453 /// Squad level
454 Squad = 1,
455 /// Platoon level
456 Platoon = 2,
457 /// Company level
458 Company = 3,
459}
460
461impl From<u8> for HierarchyLevel {
462 fn from(value: u8) -> Self {
463 match value {
464 0 => HierarchyLevel::Platform,
465 1 => HierarchyLevel::Squad,
466 2 => HierarchyLevel::Platoon,
467 3 => HierarchyLevel::Company,
468 _ => HierarchyLevel::Platform,
469 }
470 }
471}
472
473impl From<HierarchyLevel> for u8 {
474 fn from(level: HierarchyLevel) -> Self {
475 level as u8
476 }
477}
478
479#[cfg(test)]
480mod tests {
481 use super::*;
482
483 #[test]
484 fn test_node_id() {
485 let id = NodeId::new(0x12345678);
486 assert_eq!(id.as_u32(), 0x12345678);
487 assert_eq!(id.to_string(), "12345678");
488 }
489
490 #[test]
491 fn test_node_id_parse() {
492 assert_eq!(NodeId::parse("12345678").unwrap().as_u32(), 0x12345678);
493 assert_eq!(NodeId::parse("0x12345678").unwrap().as_u32(), 0x12345678);
494 assert!(NodeId::parse("not_hex").is_none());
495 }
496
497 #[test]
498 fn test_node_id_from_mac_address() {
499 // MAC: AA:BB:CC:DD:EE:FF -> NodeId from last 4 bytes: 0xCCDDEEFF
500 let mac = [0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF];
501 let node_id = NodeId::from_mac_address(&mac);
502 assert_eq!(node_id.as_u32(), 0xCCDDEEFF);
503 }
504
505 #[test]
506 fn test_node_id_from_mac_string() {
507 let node_id = NodeId::from_mac_string("AA:BB:CC:DD:EE:FF").unwrap();
508 assert_eq!(node_id.as_u32(), 0xCCDDEEFF);
509
510 // Lowercase should work too
511 let node_id = NodeId::from_mac_string("aa:bb:cc:dd:ee:ff").unwrap();
512 assert_eq!(node_id.as_u32(), 0xCCDDEEFF);
513
514 // Invalid formats
515 assert!(NodeId::from_mac_string("invalid").is_none());
516 assert!(NodeId::from_mac_string("AA:BB:CC:DD:EE").is_none()); // Too short
517 assert!(NodeId::from_mac_string("AA:BB:CC:DD:EE:FF:GG").is_none()); // Too long
518 assert!(NodeId::from_mac_string("ZZ:BB:CC:DD:EE:FF").is_none()); // Invalid hex
519 }
520
521 #[test]
522 fn test_hierarchy_level() {
523 assert_eq!(HierarchyLevel::from(0), HierarchyLevel::Platform);
524 assert_eq!(HierarchyLevel::from(3), HierarchyLevel::Company);
525 assert_eq!(u8::from(HierarchyLevel::Squad), 1);
526 }
527
528 #[test]
529 fn test_service_uuid() {
530 assert_eq!(
531 PEAT_SERVICE_UUID.to_string(),
532 "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d"
533 );
534 }
535
536 #[test]
537 fn test_capabilities() {
538 let caps = capabilities::LITE_NODE | capabilities::SENSOR_ACCEL | capabilities::HAS_GPS;
539 assert_eq!(caps, 0x0203);
540 }
541}