peat-btle 0.3.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
410
411
// 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.

//! WinRT BLE adapter implementation
//!
//! Main adapter that implements the `BleAdapter` trait using Windows BLE APIs.

use std::collections::HashMap;
use std::sync::Arc;

use async_trait::async_trait;
use tokio::sync::RwLock;

use crate::config::{BleConfig, DiscoveryConfig};
use crate::error::{BleError, Result};
use crate::platform::{
    BleAdapter, ConnectionCallback, ConnectionEvent, DisconnectReason, DiscoveredDevice,
    DiscoveryCallback,
};
use crate::transport::BleConnection;
use crate::NodeId;

use super::advertiser::BleAdvertiser;
use super::connection::WinRtConnection;
use super::gatt_server::GattServer;
use super::watcher::BleWatcher;

/// Internal adapter state
struct AdapterState {
    /// Active connections by node ID
    connections: HashMap<NodeId, WinRtConnection>,
    /// Bluetooth address to node ID mapping
    address_to_node: HashMap<u64, NodeId>,
    /// Node ID to Bluetooth address mapping
    node_to_address: HashMap<NodeId, u64>,
}

impl Default for AdapterState {
    fn default() -> Self {
        Self {
            connections: HashMap::new(),
            address_to_node: HashMap::new(),
            node_to_address: HashMap::new(),
        }
    }
}

/// WinRT BLE adapter for Windows
///
/// Implements the `BleAdapter` trait using Windows BLE APIs.
/// Requires Windows 10 version 1703+ for basic functionality,
/// and version 1803+ for GATT server support.
///
/// # Architecture
///
/// The adapter manages:
/// - **BleWatcher**: For scanning/discovering devices
/// - **BleAdvertiser**: For advertising our presence
/// - **GattServer**: For hosting the Peat GATT service
/// - **WinRtConnection**: For connecting to other devices as GATT client
///
/// # Example
///
/// ```ignore
/// let config = BleConfig::new(NodeId::new(0x12345678));
/// let mut adapter = WinRtBleAdapter::new()?;
/// adapter.init(&config).await?;
/// adapter.start().await?;
/// ```
pub struct WinRtBleAdapter {
    /// BLE scanner
    watcher: Arc<RwLock<BleWatcher>>,
    /// BLE advertiser
    advertiser: Arc<RwLock<BleAdvertiser>>,
    /// GATT server
    gatt_server: Arc<RwLock<Option<GattServer>>>,
    /// Configuration
    config: RwLock<Option<BleConfig>>,
    /// Internal state
    state: RwLock<AdapterState>,
    /// Discovery callback
    discovery_callback: RwLock<Option<DiscoveryCallback>>,
    /// Connection callback
    connection_callback: RwLock<Option<ConnectionCallback>>,
    /// Whether the adapter is initialized
    initialized: bool,
}

impl WinRtBleAdapter {
    /// Create a new WinRT BLE adapter
    pub fn new() -> Result<Self> {
        let watcher = BleWatcher::new()?;
        let advertiser = BleAdvertiser::new()?;

        log::info!("WinRtBleAdapter created");

        Ok(Self {
            watcher: Arc::new(RwLock::new(watcher)),
            advertiser: Arc::new(RwLock::new(advertiser)),
            gatt_server: Arc::new(RwLock::new(None)),
            config: RwLock::new(None),
            state: RwLock::new(AdapterState::default()),
            discovery_callback: RwLock::new(None),
            connection_callback: RwLock::new(None),
            initialized: false,
        })
    }

    /// Register a node ID to address mapping
    pub async fn register_node_address(&self, node_id: NodeId, address: u64) {
        let mut state = self.state.write().await;
        state.address_to_node.insert(address, node_id);
        state.node_to_address.insert(node_id, address);
    }

    /// Get address for a node ID
    pub async fn get_node_address(&self, node_id: &NodeId) -> Option<u64> {
        let state = self.state.read().await;
        state.node_to_address.get(node_id).copied()
    }

    /// Get node ID for an address
    pub async fn get_address_node(&self, address: u64) -> Option<NodeId> {
        let state = self.state.read().await;
        state.address_to_node.get(&address).copied()
    }

    /// Process discovered devices and invoke callbacks
    pub async fn process_discoveries(&self) -> Result<()> {
        let watcher = self.watcher.read().await;
        let peat_peripherals = watcher.get_peat_peripherals();

        if let Some(ref callback) = *self.discovery_callback.read().await {
            for peripheral in peat_peripherals {
                // Register the mapping if we have a node ID
                if let Some(node_id) = peripheral.node_id {
                    self.register_node_address(node_id, peripheral.address)
                        .await;
                }

                let device: DiscoveredDevice = peripheral.into();
                callback(device);
            }
        }

        Ok(())
    }
}

#[async_trait]
impl BleAdapter for WinRtBleAdapter {
    async fn init(&mut self, config: &BleConfig) -> Result<()> {
        // Store config
        *self.config.write().await = Some(config.clone());

        // Initialize GATT server
        let mut gatt_server = GattServer::new(config.node_id)?;
        gatt_server.init().await?;
        *self.gatt_server.write().await = Some(gatt_server);

        self.initialized = true;

        log::info!(
            "WinRtBleAdapter initialized for node {:08X}",
            config.node_id.as_u32()
        );

        Ok(())
    }

    async fn start(&self) -> Result<()> {
        let config = self.config.read().await;
        let config = config
            .as_ref()
            .ok_or_else(|| BleError::InvalidState("Adapter not initialized".to_string()))?;

        // Start GATT server advertising
        if let Some(ref mut server) = *self.gatt_server.write().await {
            server.start_advertising()?;
        }

        // Start BLE advertising
        {
            let mut advertiser = self.advertiser.write().await;
            advertiser.start_advertising(config.node_id, &config.discovery)?;
        }

        // Start scanning
        {
            let mut watcher = self.watcher.write().await;
            watcher.start_scan(&config.discovery)?;
        }

        log::info!("WinRtBleAdapter started");
        Ok(())
    }

    async fn stop(&self) -> Result<()> {
        // Stop scanning
        {
            let mut watcher = self.watcher.write().await;
            watcher.stop_scan()?;
        }

        // Stop advertising
        {
            let mut advertiser = self.advertiser.write().await;
            advertiser.stop_advertising()?;
        }

        // Stop GATT server
        if let Some(ref mut server) = *self.gatt_server.write().await {
            server.stop_advertising()?;
        }

        log::info!("WinRtBleAdapter stopped");
        Ok(())
    }

    fn is_powered(&self) -> bool {
        // Windows doesn't provide a simple way to check adapter power state
        // We assume powered if we initialized successfully
        self.initialized
    }

    fn address(&self) -> Option<String> {
        // Windows doesn't easily expose the local Bluetooth address
        // We'd need to enumerate adapters which requires additional code
        None
    }

    async fn start_scan(&self, config: &DiscoveryConfig) -> Result<()> {
        let mut watcher = self.watcher.write().await;
        watcher.start_scan(config)
    }

    async fn stop_scan(&self) -> Result<()> {
        let mut watcher = self.watcher.write().await;
        watcher.stop_scan()
    }

    async fn start_advertising(&self, config: &DiscoveryConfig) -> Result<()> {
        let ble_config = self.config.read().await;
        let ble_config = ble_config
            .as_ref()
            .ok_or_else(|| BleError::InvalidState("Adapter not initialized".to_string()))?;

        let mut advertiser = self.advertiser.write().await;
        advertiser.start_advertising(ble_config.node_id, config)
    }

    async fn stop_advertising(&self) -> Result<()> {
        let mut advertiser = self.advertiser.write().await;
        advertiser.stop_advertising()
    }

    fn set_discovery_callback(&mut self, callback: Option<DiscoveryCallback>) {
        if let Ok(mut cb) = self.discovery_callback.try_write() {
            *cb = callback;
        }
    }

    async fn connect(&self, peer_id: &NodeId) -> Result<Box<dyn BleConnection>> {
        // Look up the Bluetooth address for this node ID
        let address = self
            .get_node_address(peer_id)
            .await
            .ok_or_else(|| BleError::ConnectionFailed(format!("Unknown node ID: {}", peer_id)))?;

        // Create connection
        let mut connection = WinRtConnection::new(*peer_id, address);
        connection.connect().await?;

        // Store connection
        {
            let mut state = self.state.write().await;
            state.connections.insert(*peer_id, connection.clone());
        }

        // Notify callback
        if let Some(ref cb) = *self.connection_callback.read().await {
            cb(
                *peer_id,
                ConnectionEvent::Connected {
                    mtu: connection.mtu(),
                    phy: connection.phy(),
                },
            );
        }

        log::info!("Connected to peer {} at {:012X}", peer_id, address);
        Ok(Box::new(connection))
    }

    async fn disconnect(&self, peer_id: &NodeId) -> Result<()> {
        let connection = {
            let mut state = self.state.write().await;
            state.connections.remove(peer_id)
        };

        if let Some(mut conn) = connection {
            conn.disconnect();

            // Notify callback
            if let Some(ref cb) = *self.connection_callback.read().await {
                cb(
                    *peer_id,
                    ConnectionEvent::Disconnected {
                        reason: DisconnectReason::LocalRequest,
                    },
                );
            }

            log::info!("Disconnected from peer {}", peer_id);
        }

        Ok(())
    }

    fn get_connection(&self, peer_id: &NodeId) -> Option<Box<dyn BleConnection>> {
        if let Ok(state) = self.state.try_read() {
            state
                .connections
                .get(peer_id)
                .map(|c| Box::new(c.clone()) as Box<dyn BleConnection>)
        } else {
            None
        }
    }

    fn peer_count(&self) -> usize {
        if let Ok(state) = self.state.try_read() {
            state.connections.len()
        } else {
            0
        }
    }

    fn connected_peers(&self) -> Vec<NodeId> {
        if let Ok(state) = self.state.try_read() {
            state.connections.keys().copied().collect()
        } else {
            Vec::new()
        }
    }

    fn set_connection_callback(&mut self, callback: Option<ConnectionCallback>) {
        if let Ok(mut cb) = self.connection_callback.try_write() {
            *cb = callback;
        }
    }

    async fn register_gatt_service(&self) -> Result<()> {
        if let Some(ref mut server) = *self.gatt_server.write().await {
            server.start_advertising()?;
        }
        Ok(())
    }

    async fn unregister_gatt_service(&self) -> Result<()> {
        if let Some(ref mut server) = *self.gatt_server.write().await {
            server.stop_advertising()?;
        }
        Ok(())
    }

    fn supports_coded_phy(&self) -> bool {
        // Windows doesn't expose Coded PHY to applications
        false
    }

    fn supports_extended_advertising(&self) -> bool {
        // Extended advertising requires Windows 10 1903+
        // We'd need to check the OS version to be accurate
        true
    }

    fn max_mtu(&self) -> u16 {
        // Windows typically supports up to 512 bytes MTU
        512
    }

    fn max_connections(&self) -> u8 {
        // Windows supports multiple connections (typically 7-10)
        8
    }
}

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

    #[test]
    fn test_adapter_state_default() {
        let state = AdapterState::default();
        assert!(state.connections.is_empty());
        assert!(state.address_to_node.is_empty());
    }
}