bcms 0.1.7

Bluetooth Client Manager Service for IoT device management
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
use crate::config::Config;
use crate::devices::{DeviceInfo, DeviceMemory};
use crate::data::{IoTData, BloodPressureData, HeartRateData, BatteryLevelData, DataType, DataStore, TemperatureData, PressureData, AlertData};
use crate::pairing::BluetoothPairing;
use crate::{Error, Result};
use bluer::{Address, AdapterEvent, Device, Session, Adapter};
use futures::stream::StreamExt;
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tokio::time::{sleep, interval, timeout};
use uuid::Uuid;
use chrono::Utc;
use tracing::{info, warn, error, debug};
use std::str::FromStr;

/// BLE Manager for device discovery and connection
pub struct BleManager {
    session: Session,
    adapter: Adapter,
    config: Config,
    device_memory: Arc<DeviceMemory>,
    bluetooth_pairing: Arc<BluetoothPairing>,
    data_store: Arc<DataStore>,
}

impl BleManager {
    pub async fn new(config: Config, device_memory: Arc<DeviceMemory>, data_store: Arc<DataStore>) -> Result<Self> {
        let session = Session::new().await
            .map_err(|e| Error::General(format!("Failed to create Bluetooth session: {}", e)))?;
        
        let adapter = session.default_adapter().await
            .map_err(|e| Error::General(format!("No Bluetooth adapter found: {}", e)))?;

        let bluetooth_pairing = Arc::new(BluetoothPairing::new().await?);

        Ok(Self {
            session,
            adapter,
            config,
            device_memory,
            bluetooth_pairing,
            data_store,
        })
    }

    /// Start device discovery loop
    pub async fn start_discovery_loop(&self) -> Result<()> {
        let mut discovery_interval = interval(self.config.bluetooth_scan_duration());
        
        loop {
            discovery_interval.tick().await;
            
            if let Err(e) = self.scan_for_devices().await {
                error!("Error during device scan: {}", e);
            }
        }
    }

    /// Scan for BLE devices with continuous advertisement monitoring
    pub async fn scan_for_devices(&self) -> Result<Vec<DeviceInfo>> {
        info!("Starting BLE scan with advertisement monitoring...");
        
        let mut discovered_devices = Vec::new();
        
        // Start discovery and create event stream
        let discover = self.adapter.discover_devices().await?;
        let mut events = discover.take(20); // Limit to 20 events to avoid infinite scanning
        
        // Use timeout to limit scanning duration
        let scan_result = timeout(Duration::from_secs(5), async {
            while let Some(event) = events.next().await {
                match event {
                    AdapterEvent::DeviceAdded(addr) => {
                        let device = self.adapter.device(addr)?;
                        
                        // Try to get device name and properties
                        if let Ok(name) = device.name().await {
                            if let Some(name) = name {
                                let address = addr.to_string();
                                let now = Utc::now().timestamp();
                                
                                // Use discovery-specific update to preserve approval status
                                if let Err(e) = self.device_memory.update_device_from_discovery(
                                    address.clone(), 
                                    name.clone(), 
                                    now
                                ).await {
                                    warn!("Failed to update device from discovery: {}", e);
                                } else {
                                    let device_info = DeviceInfo::new(address.clone(), name.clone());
                                    discovered_devices.push(device_info);
                                    info!("Discovered device: {} ({})", name, address);
                                }
                                
                                // Check for advertisement data and process it
                                if let Err(e) = self.process_device_advertisements(&device, &address).await {
                                    debug!("Failed to process advertisement data for {}: {}", address, e);
                                }
                            }
                        }
                    }
                    _ => {} // Ignore other events
                }
            }
            Ok::<Vec<DeviceInfo>, Error>(discovered_devices.clone())
        }).await;
        
        match scan_result {
            Ok(result) => {
                info!("Scan completed. Found {} devices", result?.len());
                Ok(discovered_devices)
            }
            Err(_) => {
                info!("Scan timed out. Found {} devices", discovered_devices.len());
                Ok(discovered_devices)
            }
        }
    }
    
    /// Process advertisement data from a discovered device
    async fn process_device_advertisements(&self, device: &Device, device_address: &str) -> Result<()> {
        // Check if device is approved before processing its data
        if !self.should_process_device_data(device_address).await {
            return Ok(());
        }
        
        // Get advertisement data - this is a simplified approach
        // In a real implementation with proper bluer monitor support, we would:
        // 1. Use adapter.monitor() to create a monitoring session
        // 2. Parse the raw advertisement packets for service data
        // 3. Extract service UUIDs and their associated data
        
        // For now, we simulate this by checking if device is connectable and has services
        if let Ok(services) = device.uuids().await {
            let mut service_data = HashMap::new();
            
            for service_uuid in services.unwrap_or_default() {
                // Check if this is one of our monitored service UUIDs
                let service_str = service_uuid.to_string();
                if service_str.contains("2a37") || // Heart rate
                   service_str.contains("2a6d") || // Pressure  
                   service_str.contains("2a6e") || // Temperature
                   service_str.contains("180f") || // Battery
                   service_str.contains("2a46") {  // Alert
                    
                    // Generate mock data for testing purposes
                    // In a real implementation, this would come from actual advertisement packets
                    let mock_data = self.generate_mock_service_data(&service_str);
                    service_data.insert(service_uuid, mock_data);
                    
                    debug!("Found monitored service {} on device {}", service_str, device_address);
                }
            }
            
            if !service_data.is_empty() {
                let iot_data = self.parse_advertisement_data(device_address, &service_data).await;
                
                // Store any collected IoT data
                for data in iot_data {
                    info!("Storing advertisement data: {} from {}", data.name(), device_address);
                    if let Err(e) = self.data_store.add_data_batch(vec![data]).await {
                        warn!("Failed to store advertisement data: {}", e);
                    }
                }
            }
        }
        
        Ok(())
    }
    
    /// Generate mock service data for testing (replace with real advertisement parsing)
    fn generate_mock_service_data(&self, service_uuid: &str) -> Vec<u8> {
        if service_uuid.contains("2a37") {
            // Heart rate: simple 2-byte value (75 BPM)
            vec![0x00, 75]
        } else if service_uuid.contains("2a6d") {
            // Pressure: 4-byte value (1013 hPa)
            vec![0xF5, 0x03, 0x00, 0x00]
        } else if service_uuid.contains("2a6e") {
            // Temperature: 2-byte signed value (23°C)
            vec![23, 0]
        } else if service_uuid.contains("180f") {
            // Battery: 1-byte percentage (85%)
            vec![85]
        } else if service_uuid.contains("2a46") {
            // Alert: text message
            "test_alert".as_bytes().to_vec()
        } else {
            Vec::new()
        }
    }
    
    /// Check if we should process data from this device (only approved devices)
    async fn should_process_device_data(&self, device_address: &str) -> bool {
        if let Some(device_info) = self.device_memory.get_device(device_address).await {
            device_info.approved
        } else {
            false
        }
    }

    /// Check if a device name matches supported device patterns
    fn is_supported_device(&self, name: &str) -> bool {
        self.config.supported_devices.iter()
            .any(|pattern| name.contains(pattern))
    }

    /// Connect to a device and collect data
    pub async fn connect_and_collect_data(&self, address: &str) -> Result<Vec<IoTData>> {
        let addr = Address::from_str(address)
            .map_err(|e| Error::General(format!("Invalid address {}: {}", address, e)))?;
        
        let device = self.adapter.device(addr)
            .map_err(|e| Error::General(format!("Failed to get device {}: {}", address, e)))?;
        
        // Check if device is supported for data collection
        let device_name = device.name().await.unwrap_or_default().unwrap_or_default();
        if !device_name.is_empty() && !self.is_supported_device(&device_name) {
            warn!("Device {} ({}) is not supported for data collection", device_name, address);
            return Ok(Vec::new()); // Return empty data for unsupported devices
        }
        
        if device_name.is_empty() {
            warn!("Device {} has no name, skipping data collection", address);
            return Ok(Vec::new());
        }
        
        debug!("Attempting to connect to supported device: {} ({})", device_name, address);
        
        // Connect to the device with retry logic
        for attempt in 1..=3 {
            if device.is_connected().await.unwrap_or(false) {
                break;
            }
            
            match device.connect().await {
                Ok(()) => {
                    info!("Connected to device {} on attempt {}", address, attempt);
                    break;
                }
                Err(e) if attempt < 3 => {
                    warn!("Connection attempt {} failed for {}: {}", attempt, address, e);
                    sleep(Duration::from_millis(500)).await;
                }
                Err(e) => {
                    error!("Failed to connect to device {} after 3 attempts: {}", address, e);
                    return Err(Error::General(format!("Connection failed: {}", e)));
                }
            }
        }
        
        // Collect data based on device type
        let data = self.collect_device_data(&device, address, &device_name).await?;
        
        // Disconnect
        if let Err(e) = device.disconnect().await {
            warn!("Failed to disconnect from device {}: {}", address, e);
        }
        
        Ok(data)
    }

    /// Collect data from a connected device
    async fn collect_device_data(&self, device: &Device, address: &str, device_name: &str) -> Result<Vec<IoTData>> {
        let mut collected_data = Vec::new();
        let timestamp = Utc::now().timestamp();
        
        // For now, implement a simplified version that doesn't use GATT operations
        // This would need to be expanded with proper GATT service discovery
        // when bluer's GATT API becomes more stable
        
        // Create some mock data based on device name for testing
        if device_name.contains("A&D_UA-651BLE_") || device_name.contains("BLESmart_") {
            // Mock blood pressure data
            let mut data_map = HashMap::new();
            data_map.insert("sys".to_string(), serde_json::Value::Number(120.into()));
            data_map.insert("dias".to_string(), serde_json::Value::Number(80.into()));
            let bp_data = BloodPressureData::new(data_map, address.to_string(), timestamp);
            collected_data.push(IoTData::BloodPressure(bp_data));
        } else if device_name.contains("X4 Smart") {
            // Mock heart rate data
            let mut data_map = HashMap::new();
            data_map.insert("rate".to_string(), serde_json::Value::Number(75.into()));
            let hr_data = HeartRateData::new(data_map, address.to_string(), timestamp);
            collected_data.push(IoTData::HeartRate(hr_data));
        } else {
            // Mock generic data
            let mut data_map = HashMap::new();
            data_map.insert("raw_data".to_string(), serde_json::Value::String("mock_data".to_string()));
            data_map.insert("length".to_string(), serde_json::Value::Number(9.into()));
            let generic_data = DataType::new(data_map, address.to_string(), timestamp, "generic".to_string());
            collected_data.push(IoTData::Generic(generic_data));
        }
        
        info!("Collected {} mock data points from device {}", collected_data.len(), address);
        
        Ok(collected_data)
    }

    /// Parse characteristic data into IoTData types
    async fn parse_characteristic_data(
        &self,
        address: &str,
        device_name: &str,
        characteristic_uuid: &Uuid,
        data: &[u8],
        timestamp: i64,
    ) -> Option<IoTData> {
        // Blood pressure devices
        if device_name.contains("A&D_UA-651BLE_") || device_name.contains("BLESmart_") {
            return self.parse_blood_pressure_data(address, data, timestamp).await;
        }
        
        // Heart rate devices
        if device_name.contains("X4 Smart") {
            return self.parse_heart_rate_data(address, data, timestamp).await;
        }
        
        // Generic battery level (common characteristic UUID)
        let battery_uuid = Uuid::parse_str("00002a19-0000-1000-8000-00805f9b34fb").unwrap();
        if characteristic_uuid == &battery_uuid {
            return self.parse_battery_data(address, data, timestamp).await;
        }
        
        // Generic data parsing fallback
        self.parse_generic_data(address, data, timestamp).await
    }

    /// Parse blood pressure measurement data
    async fn parse_blood_pressure_data(&self, address: &str, data: &[u8], timestamp: i64) -> Option<IoTData> {
        if data.len() >= 4 {
            // Typical blood pressure data format: [flags, systolic_low, systolic_high, diastolic_low, diastolic_high, ...]
            let systolic = u16::from_le_bytes([data[1], data[2]]) as i32;
            let diastolic = u16::from_le_bytes([data[3], data[4]]) as i32;
            
            let mut data_map = HashMap::new();
            data_map.insert("sys".to_string(), serde_json::Value::Number(systolic.into()));
            data_map.insert("dias".to_string(), serde_json::Value::Number(diastolic.into()));
            
            let bp_data = BloodPressureData::new(data_map, address.to_string(), timestamp);
            Some(IoTData::BloodPressure(bp_data))
        } else {
            None
        }
    }

    /// Parse heart rate measurement data
    async fn parse_heart_rate_data(&self, address: &str, data: &[u8], timestamp: i64) -> Option<IoTData> {
        if !data.is_empty() {
            // Heart rate data format: [flags, heart_rate, ...]
            let heart_rate = if data[0] & 0x01 == 0 {
                // 8-bit heart rate
                data[1] as i32
            } else {
                // 16-bit heart rate
                u16::from_le_bytes([data[1], data[2]]) as i32
            };
            
            let mut data_map = HashMap::new();
            data_map.insert("rate".to_string(), serde_json::Value::Number(heart_rate.into()));
            
            let hr_data = HeartRateData::new(data_map, address.to_string(), timestamp);
            Some(IoTData::HeartRate(hr_data))
        } else {
            None
        }
    }

    /// Parse battery level data
    async fn parse_battery_data(&self, address: &str, data: &[u8], timestamp: i64) -> Option<IoTData> {
        if !data.is_empty() {
            let battery_level = data[0] as i32;
            
            let mut data_map = HashMap::new();
            data_map.insert("level".to_string(), serde_json::Value::Number(battery_level.into()));
            
            let battery_data = BatteryLevelData::new(data_map, address.to_string(), timestamp);
            Some(IoTData::BatteryLevel(battery_data))
        } else {
            None
        }
    }

    /// Parse generic device data
    async fn parse_generic_data(&self, address: &str, data: &[u8], timestamp: i64) -> Option<IoTData> {
        if !data.is_empty() {
            let mut data_map = HashMap::new();
            data_map.insert("raw_data".to_string(), serde_json::Value::String(hex::encode(data)));
            data_map.insert("length".to_string(), serde_json::Value::Number(data.len().into()));
            
            let generic_data = DataType::new(data_map, address.to_string(), timestamp, "generic".to_string());
            Some(IoTData::Generic(generic_data))
        } else {
            None
        }
    }

    /// Parse advertisement data from BLE advertisements (similar to Python's iot_advertisement_data_callback_wrapper)
    pub async fn parse_advertisement_data(&self, device_address: &str, service_data: &HashMap<uuid::Uuid, Vec<u8>>) -> Vec<IoTData> {
        let mut collected_data = Vec::new();
        let timestamp = chrono::Utc::now().timestamp();
        
        // Service UUID mapping (matching Python implementation)
        let type_key_dict = [
            ("HEART_RATE", "00002a37-0000-1000-8000-00805f9b34fb"),
            ("PRESSURE", "00002a6d-0000-1000-8000-00805f9b34fb"),
            ("TEMPERATURE", "00002a6e-0000-1000-8000-00805f9b34fb"),
            ("BATTERY_LEVEL", "0000180f-0000-1000-8000-00805f9b34fb"),
            ("ALERT", "00002a46-0000-1000-8000-00805f9b34fb"),
        ];
        
        for (data_type, uuid_str) in type_key_dict {
            if let Ok(target_uuid) = uuid::Uuid::parse_str(uuid_str) {
                // Check if any service UUID starts with this target UUID
                let mut matched_data: Option<&Vec<u8>> = None;
                for (service_uuid, data) in service_data {
                    if service_uuid.to_string().starts_with(&target_uuid.to_string()) {
                        matched_data = Some(data);
                        break;
                    }
                }
                
                if let Some(data) = matched_data {
                    let iot_data = match data_type {
                        "HEART_RATE" => {
                            let data_value = self.parse_signed_le_bytes(data);
                            debug!("BLE Found {}: Heart rate data: {}", uuid_str, data_value);
                            
                            let mut data_map = HashMap::new();
                            data_map.insert("rate".to_string(), serde_json::Value::Number(data_value.into()));
                            Some(IoTData::HeartRate(HeartRateData::new(data_map, device_address.to_string(), timestamp)))
                        }
                        "PRESSURE" => {
                            let data_value = self.parse_unsigned_le_bytes(data);
                            debug!("BLE Found {}: Pressure data: {}", uuid_str, data_value);
                            
                            let mut data_map = HashMap::new();
                            data_map.insert("level".to_string(), serde_json::json!(data_value as f64));
                            Some(IoTData::Pressure(PressureData::new(data_map, device_address.to_string(), timestamp)))
                        }
                        "TEMPERATURE" => {
                            let data_value = self.parse_signed_le_bytes(data);
                            debug!("BLE Found {}: Temperature data: {}", uuid_str, data_value);
                            
                            let mut data_map = HashMap::new();
                            data_map.insert("level".to_string(), serde_json::json!(data_value as f64));
                            Some(IoTData::Temperature(TemperatureData::new(data_map, device_address.to_string(), timestamp)))
                        }
                        "BATTERY_LEVEL" => {
                            let data_value = self.parse_signed_le_bytes(data);
                            debug!("BLE Found {}: Battery level data: {}", uuid_str, data_value);
                            
                            let mut data_map = HashMap::new();
                            data_map.insert("level".to_string(), serde_json::Value::Number(data_value.into()));
                            Some(IoTData::BatteryLevel(BatteryLevelData::new(data_map, device_address.to_string(), timestamp)))
                        }
                        "ALERT" => {
                            let data_value = self.parse_bytes_to_utf8(data);
                            debug!("BLE Found {}: Alert data: {:?}", uuid_str, data_value);
                            
                            if let Some(alert_text) = data_value {
                                let mut data_map = HashMap::new();
                                data_map.insert("id".to_string(), serde_json::Value::String(alert_text.clone()));
                                Some(IoTData::Alert(AlertData::new(data_map, device_address.to_string(), timestamp)))
                            } else {
                                None
                            }
                        }
                        _ => None,
                    };
                    
                    if let Some(data) = iot_data {
                        collected_data.push(data);
                    }
                }
            }
        }
        
        collected_data
    }
    
    /// Parse bytes as signed little-endian integer
    fn parse_signed_le_bytes(&self, data: &[u8]) -> i32 {
        match data.len() {
            1 => data[0] as i8 as i32,
            2 => i16::from_le_bytes([data[0], data[1]]) as i32,
            4 => i32::from_le_bytes([data[0], data[1], data[2], data[3]]),
            _ => {
                // For other lengths, just take the first byte as signed
                if data.is_empty() { 0 } else { data[0] as i8 as i32 }
            }
        }
    }
    
    /// Parse bytes as unsigned little-endian integer
    fn parse_unsigned_le_bytes(&self, data: &[u8]) -> u32 {
        match data.len() {
            1 => data[0] as u32,
            2 => u16::from_le_bytes([data[0], data[1]]) as u32,
            4 => u32::from_le_bytes([data[0], data[1], data[2], data[3]]),
            _ => {
                // For other lengths, just take the first byte as unsigned
                if data.is_empty() { 0 } else { data[0] as u32 }
            }
        }
    }
    
    /// Parse bytes as UTF-8 string
    fn parse_bytes_to_utf8(&self, data: &[u8]) -> Option<String> {
        match String::from_utf8(data.to_vec()) {
            Ok(text) => Some(text),
            Err(e) => {
                warn!("Failed to decode bytes to UTF-8: {}", e);
                None
            }
        }
    }

    /// Pair with a device using actual Bluetooth pairing
    pub async fn pair_device(&self, address: &str) -> Result<bool> {
        info!("Attempting to pair with device: {}", address);
        
        // Use BluetoothPairing for actual Bluetooth pairing
        let paired = self.bluetooth_pairing.pair_device(address).await?;
        
        if paired {
            // Also update our internal memory to reflect the pairing status
            self.device_memory.set_device_paired(address, true).await?;
            info!("Successfully paired with device: {}", address);
        } else {
            warn!("Failed to pair with device: {}", address);
        }
        
        Ok(paired)
    }

    /// Unpair a device using actual Bluetooth unpairing
    pub async fn unpair_device(&self, address: &str) -> Result<bool> {
        info!("Unpairing device: {}", address);
        
        // Use BluetoothPairing for actual Bluetooth unpairing
        let unpaired = self.bluetooth_pairing.unpair_device(address).await?;
        
        if unpaired {
            // Also update our internal memory to reflect the unpairing
            self.device_memory.set_device_paired(address, false).await?;
            info!("Successfully unpaired device: {}", address);
        } else {
            warn!("Failed to unpair device: {}", address);
        }
        
        Ok(unpaired)
    }

    /// Check if device is actually paired via Bluetooth
    pub async fn is_device_paired(&self, address: &str) -> Result<bool> {
        self.bluetooth_pairing.is_device_paired(address).await
    }

    /// Check if device is currently connected
    pub async fn is_device_connected(&self, address: &str) -> Result<bool> {
        let addr = Address::from_str(address)
            .map_err(|e| Error::General(format!("Invalid address {}: {}", address, e)))?;
        
        let device = self.adapter.device(addr)
            .map_err(|e| Error::General(format!("Failed to get device {}: {}", address, e)))?;
        
        device.is_connected().await
            .map_err(|e| Error::General(format!("Failed to check connection status for {}: {}", address, e)))
    }
    
    /// Start continuous advertisement monitoring loop (similar to Python's detection_callback)
    /// This should be run in a separate task to continuously monitor for advertisement data
    pub async fn start_advertisement_monitoring_loop(&self) -> Result<()> {
        info!("Starting continuous advertisement monitoring loop...");
        
        // Create a monitoring interval that runs more frequently than device discovery
        let mut monitoring_interval = interval(Duration::from_secs(2));
        
        loop {
            monitoring_interval.tick().await;
            
            // Get all known devices and check for advertisement data
            let all_devices = self.device_memory.get_all_devices().await;
            
            for device_info in all_devices {
                // Only process approved devices
                if device_info.approved {
                    if let Ok(addr) = Address::from_str(&device_info.address) {
                        let device = self.adapter.device(addr).unwrap_or_else(|_| self.adapter.device(addr).unwrap());
                        
                        // Process any available advertisement data
                        if let Err(e) = self.process_device_advertisements(&device, &device_info.address).await {
                            debug!("Failed to process advertisement data for {}: {}", device_info.address, e);
                        }
                    }
                }
            }
        }
    }
}

// Add hex crate to Cargo.toml for raw data encoding
// This is a common practice for debugging BLE data