peat-btle 0.4.0

Bluetooth Low Energy mesh transport for Peat Protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
// Copyright (c) 2025-2026 (r)evolve - Revolve Team LLC
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Transport trait implementation for PEAT-BTLE
//!
//! Implements the pluggable transport abstraction (ADR-032) for Bluetooth LE,
//! providing the `BluetoothLETransport` struct that can be registered with
//! the `TransportManager`.

#[cfg(not(feature = "std"))]
use alloc::{boxed::Box, vec::Vec};

use async_trait::async_trait;
use core::time::Duration;

use crate::config::{BleConfig, BlePhy};
use crate::error::Result;
use crate::platform::BleAdapter;
use crate::NodeId;

/// Transport capabilities for Bluetooth LE
///
/// Advertises what this transport can do, allowing the TransportManager
/// to select the best transport for each message.
#[derive(Debug, Clone)]
pub struct TransportCapabilities {
    /// Maximum bandwidth in bytes/second
    pub max_bandwidth_bps: u64,
    /// Typical latency in milliseconds
    pub typical_latency_ms: u32,
    /// Maximum practical range in meters
    pub max_range_meters: u32,
    /// Supports bidirectional communication
    pub bidirectional: bool,
    /// Supports reliable delivery
    pub reliable: bool,
    /// Battery impact score (0-100, higher = more power)
    pub battery_impact: u8,
    /// Supports broadcast/advertising
    pub supports_broadcast: bool,
    /// Requires pairing before use
    pub requires_pairing: bool,
    /// Maximum message size in bytes
    pub max_message_size: usize,
}

impl TransportCapabilities {
    /// Create default BLE capabilities
    pub fn bluetooth_le() -> Self {
        Self {
            max_bandwidth_bps: 250_000, // ~250 KB/s practical throughput
            typical_latency_ms: 30,
            max_range_meters: 100,
            bidirectional: true,
            reliable: true,
            battery_impact: 15,
            supports_broadcast: true,
            requires_pairing: false,
            max_message_size: 512,
        }
    }

    /// Create capabilities for Coded PHY (long range)
    pub fn bluetooth_le_coded() -> Self {
        Self {
            max_bandwidth_bps: 125_000, // Coded S=8
            typical_latency_ms: 100,
            max_range_meters: 400,
            bidirectional: true,
            reliable: true,
            battery_impact: 20, // Slightly higher due to longer TX time
            supports_broadcast: true,
            requires_pairing: false,
            max_message_size: 512,
        }
    }

    /// Update capabilities based on PHY
    pub fn for_phy(phy: BlePhy) -> Self {
        match phy {
            BlePhy::Le1M => Self::bluetooth_le(),
            BlePhy::Le2M => Self {
                max_bandwidth_bps: 500_000,
                typical_latency_ms: 20,
                max_range_meters: 50,
                ..Self::bluetooth_le()
            },
            BlePhy::LeCodedS2 => Self {
                max_bandwidth_bps: 250_000,
                typical_latency_ms: 50,
                max_range_meters: 200,
                ..Self::bluetooth_le()
            },
            BlePhy::LeCodedS8 => Self::bluetooth_le_coded(),
        }
    }
}

impl Default for TransportCapabilities {
    fn default() -> Self {
        Self::bluetooth_le()
    }
}

/// Connection to a BLE peer
///
/// Represents an active GATT connection to a remote device.
pub trait BleConnection: Send + Sync {
    /// Get the remote peer's node ID
    fn peer_id(&self) -> &NodeId;

    /// Check if connection is still alive
    fn is_alive(&self) -> bool;

    /// Get the negotiated MTU
    fn mtu(&self) -> u16;

    /// Get the current PHY
    fn phy(&self) -> BlePhy;

    /// Get RSSI (signal strength) in dBm
    fn rssi(&self) -> Option<i8>;

    /// Get connection duration
    fn connected_duration(&self) -> Duration;
}

/// Bluetooth LE mesh transport
///
/// Implements the transport abstraction for BLE, providing:
/// - Peer discovery via advertising/scanning
/// - GATT-based data exchange
/// - Connection management
/// - PHY selection
///
/// # Example
///
/// ```ignore
/// use peat_btle::{BluetoothLETransport, BleConfig, NodeId};
///
/// let config = BleConfig::peat_lite(NodeId::new(0x12345678));
/// let transport = BluetoothLETransport::new(config)?;
///
/// transport.start().await?;
/// let conn = transport.connect(&peer_id).await?;
/// ```
pub struct BluetoothLETransport<A: BleAdapter> {
    /// Configuration
    config: BleConfig,
    /// Platform-specific adapter
    adapter: A,
    /// Current capabilities (may change with PHY)
    capabilities: TransportCapabilities,
}

impl<A: BleAdapter> BluetoothLETransport<A> {
    /// Create a new BLE transport with the given adapter
    pub fn new(config: BleConfig, adapter: A) -> Self {
        let capabilities = TransportCapabilities::for_phy(config.phy.preferred_phy);
        Self {
            config,
            adapter,
            capabilities,
        }
    }

    /// Get the current configuration
    pub fn config(&self) -> &BleConfig {
        &self.config
    }

    /// Get the current capabilities
    pub fn capabilities(&self) -> &TransportCapabilities {
        &self.capabilities
    }

    /// Get the node ID
    pub fn node_id(&self) -> &NodeId {
        &self.config.node_id
    }

    /// Per-peer link info for ADR-032 §Amendment A consumers.
    ///
    /// Delegates to the underlying platform adapter. The default
    /// `BleAdapter::peer_link_info` returns `None`; adapters that
    /// track per-peer state surface it through this pass-through,
    /// where peat-mesh's `PeatBleTransport::peer_link_state` reads it
    /// and synthesises a unified `LinkState`.
    pub fn peer_link_info(&self, peer_id: &NodeId) -> Option<crate::peer::BlePeerLinkInfo> {
        self.adapter.peer_link_info(peer_id)
    }
}

/// Async transport operations
///
/// These are the core transport operations that integrate with
/// the Peat protocol's transport abstraction (ADR-032).
#[async_trait]
pub trait MeshTransport: Send + Sync {
    /// Start the transport layer
    async fn start(&self) -> Result<()>;

    /// Stop the transport layer
    async fn stop(&self) -> Result<()>;

    /// Connect to a peer by node ID
    async fn connect(&self, peer_id: &NodeId) -> Result<Box<dyn BleConnection>>;

    /// Disconnect from a peer
    async fn disconnect(&self, peer_id: &NodeId) -> Result<()>;

    /// Get an existing connection
    fn get_connection(&self, peer_id: &NodeId) -> Option<Box<dyn BleConnection>>;

    /// Get the number of connected peers
    fn peer_count(&self) -> usize;

    /// Get list of connected peer IDs
    fn connected_peers(&self) -> Vec<NodeId>;

    /// Check if connected to a specific peer
    fn is_connected(&self, peer_id: &NodeId) -> bool {
        self.get_connection(peer_id).is_some()
    }

    /// Send data to a connected peer
    ///
    /// Fragments the payload based on the connection's negotiated MTU
    /// and writes each fragment to the peer's sync data characteristic.
    ///
    /// Returns the number of application bytes sent (original payload size).
    async fn send_to(&self, peer_id: &NodeId, data: &[u8]) -> Result<usize> {
        let _ = (peer_id, data);
        Err(crate::error::BleError::NotSupported(
            "send_to not implemented".into(),
        ))
    }

    /// Get transport capabilities
    fn capabilities(&self) -> &TransportCapabilities;
}

/// Construct a full 128-bit UUID from a BLE 16-bit short UUID
///
/// Uses the Bluetooth Base UUID: `0000xxxx-0000-1000-8000-00805F9B34FB`
fn ble_uuid_from_u16(short: u16) -> uuid::Uuid {
    uuid::Uuid::from_fields(
        short as u32,
        0x0000,
        0x1000,
        &[0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB],
    )
}

#[async_trait]
impl<A: BleAdapter + Send + Sync> MeshTransport for BluetoothLETransport<A> {
    async fn start(&self) -> Result<()> {
        // Start advertising and scanning via adapter
        self.adapter.start().await
    }

    async fn stop(&self) -> Result<()> {
        self.adapter.stop().await
    }

    async fn connect(&self, peer_id: &NodeId) -> Result<Box<dyn BleConnection>> {
        self.adapter.connect(peer_id).await
    }

    async fn disconnect(&self, peer_id: &NodeId) -> Result<()> {
        self.adapter.disconnect(peer_id).await
    }

    fn get_connection(&self, peer_id: &NodeId) -> Option<Box<dyn BleConnection>> {
        self.adapter.get_connection(peer_id)
    }

    fn peer_count(&self) -> usize {
        self.adapter.peer_count()
    }

    fn connected_peers(&self) -> Vec<NodeId> {
        self.adapter.connected_peers()
    }

    async fn send_to(&self, peer_id: &NodeId, data: &[u8]) -> Result<usize> {
        use crate::sync::protocol::chunk_data;

        // Get connection for MTU
        let conn = self.get_connection(peer_id).ok_or_else(|| {
            crate::error::BleError::ConnectionFailed(format!("No connection to {}", peer_id))
        })?;
        let mtu = conn.mtu() as usize;

        // Fragment data into MTU-sized chunks with reassembly headers
        let chunks = chunk_data(data, mtu, 0);

        // Write each chunk to the sync data characteristic
        let char_uuid = ble_uuid_from_u16(crate::CHAR_SYNC_DATA_UUID);
        for chunk in &chunks {
            self.adapter
                .write_to_peer(peer_id, char_uuid, &chunk.encode())
                .await?;
        }

        Ok(data.len())
    }

    fn capabilities(&self) -> &TransportCapabilities {
        &self.capabilities
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_capabilities_for_phy() {
        let caps = TransportCapabilities::for_phy(BlePhy::LeCodedS8);
        assert_eq!(caps.max_range_meters, 400);
        assert_eq!(caps.max_bandwidth_bps, 125_000);
    }

    #[test]
    fn test_capabilities_le2m() {
        let caps = TransportCapabilities::for_phy(BlePhy::Le2M);
        assert_eq!(caps.max_range_meters, 50);
        assert_eq!(caps.max_bandwidth_bps, 500_000);
    }

    #[test]
    fn test_ble_uuid_from_u16() {
        let uuid = ble_uuid_from_u16(0x0003);
        assert_eq!(uuid.to_string(), "00000003-0000-1000-8000-00805f9b34fb");
    }

    #[test]
    fn test_send_to_default_returns_error() {
        // Verify the default trait impl returns NotSupported
        use crate::platform::StubAdapter;

        let config = BleConfig::default();
        let adapter = StubAdapter::default();
        let transport = BluetoothLETransport::new(config, adapter);

        // send_to without a connection should fail
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();
        let result = rt.block_on(transport.send_to(&NodeId::new(0x222), b"hello"));
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_mock_send_to() {
        use crate::platform::mock::{MockBleAdapter, MockNetwork};

        let network = MockNetwork::new();
        let mut adapter1 = MockBleAdapter::new(NodeId::new(0x111), network.clone());
        let mut adapter2 = MockBleAdapter::new(NodeId::new(0x222), network.clone());

        adapter1.init(&BleConfig::default()).await.unwrap();
        adapter2.init(&BleConfig::default()).await.unwrap();
        adapter2
            .start_advertising(&crate::config::DiscoveryConfig::default())
            .await
            .unwrap();

        // Connect
        let _conn = adapter1.connect(&NodeId::new(0x222)).await.unwrap();

        // Create transport and send data
        let transport = BluetoothLETransport::new(BleConfig::default(), adapter1);
        let result = transport.send_to(&NodeId::new(0x222), b"hello mesh").await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 10);

        // Verify data was queued in the network
        let packets = network.receive_data(&NodeId::new(0x222));
        assert!(!packets.is_empty());
    }

    #[tokio::test]
    async fn test_send_to_disconnected_peer() {
        use crate::platform::mock::{MockBleAdapter, MockNetwork};

        let network = MockNetwork::new();
        let adapter = MockBleAdapter::new(NodeId::new(0x111), network);
        let transport = BluetoothLETransport::new(BleConfig::default(), adapter);

        // Sending to a peer we're not connected to should fail
        let result = transport.send_to(&NodeId::new(0x999), b"hello").await;
        assert!(result.is_err());
    }
}