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// ADR-059 cross-transport bridging — `BleTranslator` + the
181// `peat_mesh::transport::Translator` impl. Gated behind the
182// `mesh-translator` Cargo feature so standalone BLE consumers
183// (Bitchat-style, embedded sensors) keep peat-mesh out of their dep
184// graph. See `translator.rs` module docs for the placement rule.
185#[cfg(feature = "mesh-translator")]
186pub mod translator;
187
188/// Receives [`MeshDocument`]s decoded from inbound BLE translator frames
189/// (ADR-059 Amendment 1).
190///
191/// Invoked by peat-btle's GATT receive dispatch after a 0xB6 frame is
192/// successfully routed through `BleTranslator::decode_inbound`. The
193/// callback is expected to be **non-blocking and panic-free**; consumers
194/// that need async ingest into `peat_mesh::Node::publish_with_origin`
195/// should spawn their own task.
196///
197/// `collection` is the BleTranslator collection name (e.g. `"tracks"`),
198/// suitable for direct use as the first argument to
199/// `Node::publish_with_origin`. `peer` carries the BLE peer's identifier
200/// for diagnostics and `target_nodes` checks (ADR-046).
201///
202/// Storage on `PeatMesh` is `Option<Arc<dyn DecodedDocumentCallback>>`
203/// initialized to `None` — the slice's specified release-skew window
204/// between peat-btle (1.b.3) shipping and peat-ffi (1.b.4) installing
205/// the callback is real. The no-callback path is no-op-drop *plus* a
206/// `PeatEvent::TranslatorNoCallback { collection, peer }` event on the
207/// observer channel, so the gap is operator-observable in real time
208/// rather than buried behind a `log::debug!` line.
209#[cfg(feature = "mesh-translator")]
210pub trait DecodedDocumentCallback: Send + Sync + 'static {
211 /// Invoked once per successfully-decoded inbound translator frame.
212 fn on_document(&self, collection: &str, doc: MeshDocument, peer: Option<&str>);
213}
214
215/// Re-export of `peat_mesh::sync::Document` as `MeshDocument`.
216///
217/// The local `crate::peat_mesh` module (containing the `PeatMesh` facade)
218/// shadows the extern crate name in any inline path written from
219/// `lib.rs`. The leading `::` forces extern_prelude resolution to reach
220/// the external `peat_mesh` crate, sidestepping the shadow. Identical
221/// to the alias used inside `crate::translator` (where the submodule
222/// scope reaches extern_prelude without the `::` prefix).
223#[cfg(feature = "mesh-translator")]
224pub use ::peat_mesh::sync::Document as MeshDocument;
225
226// UniFFI bindings (generates Kotlin + Swift)
227#[cfg(feature = "uniffi")]
228pub mod uniffi_bindings;
229
230// UniFFI scaffolding - must be at crate root
231#[cfg(feature = "uniffi")]
232uniffi::setup_scaffolding!();
233
234// Re-exports for convenience
235pub use config::{
236 BleConfig, BlePhy, DiscoveryConfig, GattConfig, MeshConfig, PowerProfile, DEFAULT_MESH_ID,
237};
238#[cfg(feature = "std")]
239pub use discovery::Scanner;
240pub use discovery::{Advertiser, PeatBeacon, ScanFilter};
241pub use error::{BleError, Result};
242#[cfg(feature = "std")]
243pub use gatt::PeatGattService;
244pub use gatt::SyncProtocol;
245#[cfg(feature = "std")]
246pub use mesh::MeshManager;
247pub use mesh::{MeshRouter, MeshTopology, TopologyConfig, TopologyEvent};
248pub use phy::{PhyCapabilities, PhyController, PhyStrategy};
249pub use platform::{BleAdapter, ConnectionEvent, DisconnectReason, DiscoveredDevice, StubAdapter};
250
251// Platform-specific adapter re-exports for external crates (peat-ffi)
252// These allow external crates to use platform adapters via feature flags
253#[cfg(all(feature = "linux", target_os = "linux"))]
254pub use platform::linux::BluerAdapter;
255
256#[cfg(feature = "android")]
257pub use platform::android::AndroidAdapter;
258
259#[cfg(any(feature = "macos", feature = "ios"))]
260pub use platform::apple::CoreBluetoothAdapter;
261
262#[cfg(feature = "windows")]
263pub use platform::windows::WinRtBleAdapter;
264
265#[cfg(feature = "std")]
266pub use platform::mock::MockBleAdapter;
267pub use power::{BatteryState, RadioScheduler, SyncPriority};
268pub use sync::{GattSyncProtocol, SyncConfig, SyncState};
269pub use transport::{BleConnection, BluetoothLETransport, MeshTransport, TransportCapabilities};
270
271// New centralized mesh management types
272pub use document::{
273 MergeResult, PeatDocument, ENCRYPTED_MARKER, EXTENDED_MARKER, KEY_EXCHANGE_MARKER,
274 PEER_E2EE_MARKER,
275};
276
277// Security (mesh-wide and per-peer encryption)
278pub use document_sync::{DocumentCheck, DocumentSync};
279#[cfg(feature = "std")]
280pub use observer::{CollectingObserver, ObserverManager};
281pub use observer::{DisconnectReason as PeatDisconnectReason, PeatEvent, PeatObserver};
282#[cfg(feature = "std")]
283pub use peat_mesh::{DataReceivedResult, PeatMesh, PeatMeshConfig, RelayDecision};
284pub use peer::{
285 ConnectionState, ConnectionStateGraph, FullStateCountSummary, IndirectPeer, PeatPeer,
286 PeerConnectionState, PeerDegree, PeerManagerConfig, SignalStrength, StateCountSummary,
287 MAX_TRACKED_DEGREE,
288};
289pub use peer_manager::PeerManager;
290
291// Device identity and attestation
292pub use security::{
293 DeviceIdentity, IdentityAttestation, IdentityError, IdentityRecord, IdentityRegistry,
294 RegistryResult,
295};
296// Mesh genesis and credentials
297pub use security::{MembershipPolicy, MeshCredentials, MeshGenesis};
298
299// Phase 1: Mesh-wide encryption
300pub use security::{EncryptedDocument, EncryptionError, MeshEncryptionKey};
301// Phase 2: Per-peer E2EE
302#[cfg(feature = "std")]
303pub use security::{
304 KeyExchangeMessage, PeerEncryptedMessage, PeerIdentityKey, PeerSession, PeerSessionKey,
305 PeerSessionManager, SessionState,
306};
307
308// Credential persistence
309#[cfg(feature = "std")]
310pub use security::{
311 MemoryStorage, PersistedState, PersistenceError, SecureStorage, PERSISTED_STATE_VERSION,
312};
313
314// Gossip and persistence abstractions
315#[cfg(feature = "std")]
316pub use gossip::{BroadcastAll, EmergencyAware, GossipStrategy, RandomFanout, SignalBasedFanout};
317#[cfg(feature = "std")]
318pub use persistence::{DocumentStore, FileStore, MemoryStore, SharedStore};
319
320// Multi-hop relay support
321pub use relay::{
322 MessageId, RelayEnvelope, RelayFlags, SeenMessageCache, DEFAULT_MAX_HOPS, DEFAULT_SEEN_TTL_MS,
323 RELAY_ENVELOPE_MARKER,
324};
325
326// Extensible document registry for app-layer types
327pub use registry::{
328 decode_header, decode_typed, encode_with_header, AppOperation, DocumentRegistry, DocumentType,
329 APP_OP_BASE, APP_TYPE_MAX, APP_TYPE_MIN,
330};
331
332/// Peat BLE Service UUID (128-bit)
333///
334/// All Peat nodes advertise this UUID for discovery.
335pub const PEAT_SERVICE_UUID: uuid::Uuid = uuid::uuid!("a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d");
336
337/// Peat BLE Service UUID (16-bit short form)
338///
339/// Derived from the first two bytes of the 128-bit UUID (0xA1B2 from a1b2c3d4).
340/// Used for space-constrained advertising to fit within 31-byte limit.
341pub const PEAT_SERVICE_UUID_16BIT: u16 = 0xA1B2;
342
343/// PEAT Node Info Characteristic UUID
344pub const CHAR_NODE_INFO_UUID: u16 = 0x0001;
345
346/// PEAT Sync State Characteristic UUID
347pub const CHAR_SYNC_STATE_UUID: u16 = 0x0002;
348
349/// PEAT Sync Data Characteristic UUID
350pub const CHAR_SYNC_DATA_UUID: u16 = 0x0003;
351
352/// PEAT Command Characteristic UUID
353pub const CHAR_COMMAND_UUID: u16 = 0x0004;
354
355/// PEAT Status Characteristic UUID
356pub const CHAR_STATUS_UUID: u16 = 0x0005;
357
358/// Crate version
359pub const VERSION: &str = env!("CARGO_PKG_VERSION");
360
361/// Node identifier
362///
363/// Represents a unique node in the Peat mesh. For BLE, this is typically
364/// derived from the Bluetooth MAC address or a configured value.
365#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
366pub struct NodeId {
367 /// 32-bit node identifier
368 id: u32,
369}
370
371impl NodeId {
372 /// Create a new node ID from a 32-bit value
373 pub fn new(id: u32) -> Self {
374 Self { id }
375 }
376
377 /// Get the raw 32-bit ID value
378 pub fn as_u32(&self) -> u32 {
379 self.id
380 }
381
382 /// Create from a string representation (hex format)
383 pub fn parse(s: &str) -> Option<Self> {
384 // Try parsing as hex (with or without 0x prefix)
385 let s = s.trim_start_matches("0x").trim_start_matches("0X");
386 u32::from_str_radix(s, 16).ok().map(Self::new)
387 }
388
389 /// Derive a NodeId from a BLE MAC address.
390 ///
391 /// Uses the last 4 bytes of the 6-byte MAC address as the 32-bit node ID.
392 /// This provides a consistent node ID derived from the device's Bluetooth
393 /// hardware address.
394 ///
395 /// # Arguments
396 /// * `mac` - 6-byte MAC address array (e.g., [0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF])
397 ///
398 /// # Example
399 /// ```
400 /// use peat_btle::NodeId;
401 ///
402 /// let mac = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55];
403 /// let node_id = NodeId::from_mac_address(&mac);
404 /// assert_eq!(node_id.as_u32(), 0x22334455);
405 /// ```
406 pub fn from_mac_address(mac: &[u8; 6]) -> Self {
407 // Use last 4 bytes: mac[2], mac[3], mac[4], mac[5]
408 let id = ((mac[2] as u32) << 24)
409 | ((mac[3] as u32) << 16)
410 | ((mac[4] as u32) << 8)
411 | (mac[5] as u32);
412 Self::new(id)
413 }
414
415 /// Derive a NodeId from a MAC address string.
416 ///
417 /// Parses a MAC address in "AA:BB:CC:DD:EE:FF" format and derives
418 /// the node ID from the last 4 bytes.
419 ///
420 /// # Arguments
421 /// * `mac_str` - MAC address string in colon-separated hex format
422 ///
423 /// # Returns
424 /// `Some(NodeId)` if parsing succeeds, `None` otherwise
425 ///
426 /// # Example
427 /// ```
428 /// use peat_btle::NodeId;
429 ///
430 /// let node_id = NodeId::from_mac_string("00:11:22:33:44:55").unwrap();
431 /// assert_eq!(node_id.as_u32(), 0x22334455);
432 /// ```
433 pub fn from_mac_string(mac_str: &str) -> Option<Self> {
434 let parts: Vec<&str> = mac_str.split(':').collect();
435 if parts.len() != 6 {
436 return None;
437 }
438
439 let mut mac = [0u8; 6];
440 for (i, part) in parts.iter().enumerate() {
441 mac[i] = u8::from_str_radix(part, 16).ok()?;
442 }
443
444 Some(Self::from_mac_address(&mac))
445 }
446}
447
448impl core::fmt::Display for NodeId {
449 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
450 write!(f, "{:08X}", self.id)
451 }
452}
453
454impl From<u32> for NodeId {
455 fn from(id: u32) -> Self {
456 Self::new(id)
457 }
458}
459
460impl From<NodeId> for u32 {
461 fn from(node_id: NodeId) -> Self {
462 node_id.id
463 }
464}
465
466/// Node capability flags
467///
468/// Advertised in the Peat beacon to indicate what this node can do.
469pub mod capabilities {
470 /// This is an Peat-Lite node (minimal state, single parent)
471 pub const LITE_NODE: u16 = 0x0001;
472 /// Has accelerometer sensor
473 pub const SENSOR_ACCEL: u16 = 0x0002;
474 /// Has temperature sensor
475 pub const SENSOR_TEMP: u16 = 0x0004;
476 /// Has button input
477 pub const SENSOR_BUTTON: u16 = 0x0008;
478 /// Has LED output
479 pub const ACTUATOR_LED: u16 = 0x0010;
480 /// Has vibration motor
481 pub const ACTUATOR_VIBRATE: u16 = 0x0020;
482 /// Has display
483 pub const HAS_DISPLAY: u16 = 0x0040;
484 /// Can relay messages (not a leaf)
485 pub const CAN_RELAY: u16 = 0x0080;
486 /// Supports Coded PHY
487 pub const CODED_PHY: u16 = 0x0100;
488 /// Has GPS
489 pub const HAS_GPS: u16 = 0x0200;
490}
491
492/// Hierarchy levels in the Peat mesh
493#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default)]
494#[repr(u8)]
495pub enum HierarchyLevel {
496 /// Platform/soldier level (leaf nodes)
497 #[default]
498 Platform = 0,
499 /// Squad level
500 Squad = 1,
501 /// Platoon level
502 Platoon = 2,
503 /// Company level
504 Company = 3,
505}
506
507impl From<u8> for HierarchyLevel {
508 fn from(value: u8) -> Self {
509 match value {
510 0 => HierarchyLevel::Platform,
511 1 => HierarchyLevel::Squad,
512 2 => HierarchyLevel::Platoon,
513 3 => HierarchyLevel::Company,
514 _ => HierarchyLevel::Platform,
515 }
516 }
517}
518
519impl From<HierarchyLevel> for u8 {
520 fn from(level: HierarchyLevel) -> Self {
521 level as u8
522 }
523}
524
525#[cfg(test)]
526mod tests {
527 use super::*;
528
529 #[test]
530 fn test_node_id() {
531 let id = NodeId::new(0x12345678);
532 assert_eq!(id.as_u32(), 0x12345678);
533 assert_eq!(id.to_string(), "12345678");
534 }
535
536 #[test]
537 fn test_node_id_parse() {
538 assert_eq!(NodeId::parse("12345678").unwrap().as_u32(), 0x12345678);
539 assert_eq!(NodeId::parse("0x12345678").unwrap().as_u32(), 0x12345678);
540 assert!(NodeId::parse("not_hex").is_none());
541 }
542
543 #[test]
544 fn test_node_id_from_mac_address() {
545 // MAC: AA:BB:CC:DD:EE:FF -> NodeId from last 4 bytes: 0xCCDDEEFF
546 let mac = [0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF];
547 let node_id = NodeId::from_mac_address(&mac);
548 assert_eq!(node_id.as_u32(), 0xCCDDEEFF);
549 }
550
551 #[test]
552 fn test_node_id_from_mac_string() {
553 let node_id = NodeId::from_mac_string("AA:BB:CC:DD:EE:FF").unwrap();
554 assert_eq!(node_id.as_u32(), 0xCCDDEEFF);
555
556 // Lowercase should work too
557 let node_id = NodeId::from_mac_string("aa:bb:cc:dd:ee:ff").unwrap();
558 assert_eq!(node_id.as_u32(), 0xCCDDEEFF);
559
560 // Invalid formats
561 assert!(NodeId::from_mac_string("invalid").is_none());
562 assert!(NodeId::from_mac_string("AA:BB:CC:DD:EE").is_none()); // Too short
563 assert!(NodeId::from_mac_string("AA:BB:CC:DD:EE:FF:GG").is_none()); // Too long
564 assert!(NodeId::from_mac_string("ZZ:BB:CC:DD:EE:FF").is_none()); // Invalid hex
565 }
566
567 #[test]
568 fn test_hierarchy_level() {
569 assert_eq!(HierarchyLevel::from(0), HierarchyLevel::Platform);
570 assert_eq!(HierarchyLevel::from(3), HierarchyLevel::Company);
571 assert_eq!(u8::from(HierarchyLevel::Squad), 1);
572 }
573
574 #[test]
575 fn test_service_uuid() {
576 assert_eq!(
577 PEAT_SERVICE_UUID.to_string(),
578 "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d"
579 );
580 }
581
582 #[test]
583 fn test_capabilities() {
584 let caps = capabilities::LITE_NODE | capabilities::SENSOR_ACCEL | capabilities::HAS_GPS;
585 assert_eq!(caps, 0x0203);
586 }
587}