bcms 0.1.12

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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
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> {
        info!("Initializing BLE Manager...");

        // Enhanced debugging for ARM platform
        let arch = std::env::consts::ARCH;
        let os = std::env::consts::OS;
        info!("Platform: {} on {}", arch, os);

        let session = Session::new().await
            .map_err(|e| {
                error!("Failed to create Bluetooth session on {}: {}", arch, e);
                error!("This might indicate: 1) Bluetooth not available, 2) Permission issues, 3) Bluetooth daemon not running");
                Error::General(format!("Failed to create Bluetooth session: {}", e))
            })?;

        let adapter = session.default_adapter().await
            .map_err(|e| {
                error!("No Bluetooth adapter found on {}: {}", arch, e);
                error!("Check: 1) Bluetooth hardware present, 2) Driver loaded, 3) Adapter powered on");
                Error::General(format!("No Bluetooth adapter found: {}", e))
            })?;

        // Log adapter information for debugging
        info!("Using Bluetooth adapter");
        if let Ok(address) = adapter.address().await {
            info!("Adapter address: {}", address);
        }
        if let Ok(powered) = adapter.is_powered().await {
            info!("Adapter powered: {}", powered);
            if !powered {
                warn!("Bluetooth adapter is not powered on - BLE operations may fail");
            }
        }

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

        info!("BLE Manager initialized successfully on {}", arch);
        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...");

        // Enhanced ARM debugging
        debug!("BLE scan parameters: timeout=5s, max_events=20");
        debug!("Bluetooth scan interval: {:?}", self.config.bluetooth_scan_duration());

        let mut discovered_devices = Vec::new();

        // Check adapter state before scanning
        if let Ok(powered) = self.adapter.is_powered().await {
            if !powered {
                error!("Cannot scan: Bluetooth adapter is not powered");
                return Err(Error::General("Bluetooth adapter not powered".to_string()));
            }
        }

        // Start discovery and create event stream
        debug!("Starting device discovery...");
        let discover = self.adapter.discover_devices().await
            .map_err(|e| {
                error!("Failed to start device discovery: {}", e);
                error!("This may indicate: 1) Adapter not ready, 2) Permission issues, 3) Resource busy");
                Error::General(format!("Discovery failed: {}", e))
            })?;
        let mut events = discover.take(20); // Limit to 20 events to avoid infinite scanning

        // Use timeout to limit scanning duration
        debug!("Waiting for BLE advertisement events...");
        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
                        debug!("Processing discovered device: {}", addr);
                        if let Ok(name) = device.name().await {
                            if let Some(name) = name {
                                let address = addr.to_string();
                                let now = Utc::now().timestamp();

                                debug!("Found named device: {} at {}", name, address);

                                // Fetch device class (Class of Device) - optional
                                let device_class = match device.class().await {
                                    Ok(Some(class)) => {
                                        debug!("Device {} class: 0x{:06X}", address, class);
                                        class
                                    }
                                    Ok(None) => {
                                        debug!("Device {} has no class information", address);
                                        0
                                    }
                                    Err(e) => {
                                        debug!("Failed to get class for device {}: {}", address, e);
                                        0
                                    }
                                };

                                // Fetch appearance value - optional
                                let appearance = match device.appearance().await {
                                    Ok(Some(app)) => {
                                        debug!("Device {} appearance: 0x{:04X}", address, app);
                                        app
                                    }
                                    Ok(None) => {
                                        debug!("Device {} has no appearance information", address);
                                        0
                                    }
                                    Err(e) => {
                                        debug!("Failed to get appearance for device {}: {}", address, e);
                                        0
                                    }
                                };

                                // Use discovery-specific update to preserve approval status
                                if let Err(e) = self.device_memory.update_device_from_discovery(
                                    address.clone(),
                                    name.clone(),
                                    now,
                                    device_class,
                                    appearance,
                                ).await {
                                    warn!("Failed to update device from discovery: {}", e);
                                } else {
                                    let mut device_info = DeviceInfo::new(address.clone(), name.clone());
                                    device_info.device_class = device_class;
                                    device_info.appearance = appearance;
                                    discovered_devices.push(device_info);
                                    info!("Discovered device: {} ({}) class=0x{:06X} appearance=0x{:04X}",
                                          name, address, device_class, appearance);
                                }

                                // Check for advertisement data and process it
                                debug!("Processing advertisement data for device: {}", address);
                                if let Err(e) = self.process_device_advertisements(&device, &address).await {
                                    debug!("Failed to process advertisement data for {}: {}", address, e);
                                } else {
                                    debug!("Successfully processed advertisement data for {}", address);
                                }
                            } else {
                                debug!("Device {} has no name, skipping", addr);
                            }
                        } else {
                            debug!("Failed to get name for device {}", addr);
                        }
                    }
                    _ => {} // Ignore other events
                }
            }
            Ok::<Vec<DeviceInfo>, Error>(discovered_devices.clone())
        }).await;

        match scan_result {
            Ok(result) => {
                let device_count = result?.len();
                info!("BLE scan completed successfully. Found {} devices", device_count);
                if device_count == 0 {
                    warn!("No BLE devices discovered. This may indicate:");
                    warn!("1. No BLE devices in range");
                    warn!("2. Bluetooth adapter issues");
                    warn!("3. Permission/privilege problems");
                    warn!("4. Platform-specific BLE driver issues");
                }
                Ok(discovered_devices)
            }
            Err(_) => {
                warn!("BLE scan timed out after 5 seconds. Found {} devices", discovered_devices.len());
                debug!("Timeout is normal - continuing with discovered devices");
                Ok(discovered_devices)
            }
        }
    }

    /// Process advertisement data from a discovered device (matching Python iot_advertisement_data_callback_wrapper)
    async fn process_device_advertisements(&self, device: &Device, device_address: &str) -> Result<()> {
        // Check if device is approved before processing its data (matching Python logic)
        if !self.should_process_device_data(device_address).await {
            debug!("Device {} not approved for data processing", device_address);
            return Ok(());
        }

        // Get real advertisement data from device properties
        let mut service_data = HashMap::new();

        // Try to get service data from device properties
        if let Ok(Some(service_data_prop)) = device.service_data().await {
            debug!("Found {} service data entries for device {}", service_data_prop.len(), device_address);

            for (service_uuid, data) in service_data_prop {
                let service_str = service_uuid.to_string();

                // Use startswith matching like Python implementation
                if self.is_monitored_service_startswith(&service_str) {
                    let data_len = data.len();
                    service_data.insert(service_uuid, data);
                    info!("Found monitored service data: {} on device {} ({} bytes)", service_str, device_address, data_len);
                } else {
                    debug!("Ignoring non-monitored service: {} on device {}", service_str, device_address);
                }
            }
        }

        // Also check manufacturer data for debugging
        if let Ok(Some(manufacturer_data)) = device.manufacturer_data().await {
            for (manufacturer_id, data) in manufacturer_data {
                debug!("Found manufacturer data {} on device {}: {} bytes", manufacturer_id, device_address, data.len());
            }
        }

        // Process and store service data if found
        if !service_data.is_empty() {
            debug!("Processing {} service data entries for device {}", service_data.len(), device_address);
            let iot_data = self.parse_advertisement_data(device_address, &service_data).await;

            if !iot_data.is_empty() {
                info!("Storing {} IoT data points from advertisement for device {}", iot_data.len(), device_address);
                if let Err(e) = self.data_store.add_data_batch(iot_data).await {
                    warn!("Failed to store advertisement data for {}: {}", device_address, e);
                }
            } else {
                debug!("No IoT data extracted from service data for device {}", device_address);
            }
        } else {
            debug!("No monitored service data found for device {}", device_address);
        }

        Ok(())
    }

    /// Check if a service UUID is one we monitor (using startswith like Python)
    fn is_monitored_service_startswith(&self, service_uuid: &str) -> bool {
        // Python uses key.startswith(uuid) for flexible matching
        let monitored_uuids = [
            "00002a37-0000-1000-8000-00805f9b34fb", // Heart rate
            "00002a6d-0000-1000-8000-00805f9b34fb", // Pressure
            "00002a6e-0000-1000-8000-00805f9b34fb", // Temperature
            "0000180f-0000-1000-8000-00805f9b34fb", // Battery service
            "00002a46-0000-1000-8000-00805f9b34fb", // Alert
        ];

        for monitored_uuid in &monitored_uuids {
            if service_uuid.starts_with(monitored_uuid) || monitored_uuid.starts_with(service_uuid) {
                return true;
            }
        }
        false
    }

    /// Process manufacturer-specific data from advertisements
    async fn process_manufacturer_data(&self, device_address: &str, manufacturer_id: u16, data: &[u8]) {
        // Process manufacturer-specific advertisement data
        // This is where device-specific parsing would go
        debug!("Processing manufacturer data from {}: ID={}, {} bytes", device_address, manufacturer_id, data.len());

        // For supported devices, we might parse manufacturer data differently
        // For now, just log the data for debugging
        if !data.is_empty() {
            debug!("Manufacturer data: {}", hex::encode(data));
        }
    }

    /// 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 using GATT operations (matching Python ble_utils.py collect_data_from_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();

        info!("Starting GATT data collection from device: {} ({})", device_name, address);

        // Standard characteristic UUIDs (matching Python implementation exactly)
        let battery_level_uuid = "00002a19-0000-1000-8000-00805f9b34fb";  // Battery Level
        let serial_number_uuid = "00002a25-0000-1000-8000-00805f9b34fb";  // Serial Number String
        let date_time_uuid = "00002a08-0000-1000-8000-00805f9b34fb";     // Date Time
        let bp_measurement_uuid = "00002a35-0000-1000-8000-00805f9b34fb"; // Blood Pressure Measurement

        debug!("Enumerating all GATT services and characteristics for device: {}", address);

        // Python implementation: enumerate all services and characteristics
        // This is a simplified version since bluer's GATT API is still evolving
        // For now, we'll attempt to read standard characteristics if device supports them

        // 1. Read Battery Level (if available)
        debug!("Attempting to read battery level characteristic");
        if let Ok(battery_level) = self.try_read_characteristic(device, battery_level_uuid).await {
            if let Some(battery_data) = self.parse_battery_data(address, &battery_level, timestamp).await {
                collected_data.push(battery_data);
                info!("Read battery level from GATT: {} bytes", battery_level.len());
            }
        }

        // 2. Read Serial Number (if available)
        debug!("Attempting to read serial number characteristic");
        if let Ok(serial_data) = self.try_read_characteristic(device, serial_number_uuid).await {
            if let Ok(serial) = String::from_utf8(serial_data) {
                info!("Device serial number: {}", serial);
                // Store in device memory if needed
            }
        }

        // 3. Read and potentially update Date Time (matching Python time sync logic)
        debug!("Attempting to read/sync device time");
        if let Ok(time_data) = self.try_read_characteristic(device, date_time_uuid).await {
            if let Some(device_time) = self.parse_device_time(&time_data) {
                let system_time = Utc::now().timestamp();
                let time_diff = (system_time - device_time).abs();

                info!("Device time vs system time difference: {} seconds", time_diff);

                // Update device time if drift > 60 seconds (matching Python)
                if time_diff > 60 {
                    warn!("Device time drift detected: {} seconds, update needed", time_diff);
                    // Note: time update would require GATT write capability
                    // For now, just log the need for update
                }
            }
        }

        // 4. Handle blood pressure devices specifically (matching Python logic)
        if device_name.contains("A&D_UA-651BLE_") || device_name.contains("BLESmart_") {
            info!("Detected blood pressure device: {}", device_name);

            // Subscribe to Blood Pressure Measurement notifications
            debug!("Attempting to subscribe to blood pressure notifications");
            if let Ok(bp_data) = self.subscribe_to_blood_pressure_notifications(device, address, timestamp).await {
                let bp_count = bp_data.len();
                collected_data.extend(bp_data);
                info!("Collected {} blood pressure measurements via notifications", bp_count);
            } else {
                debug!("Blood pressure notification subscription not available");
            }
        }

        // If no GATT data was collected, fall back to advertisement data
        if collected_data.is_empty() {
            debug!("No GATT data collected, falling back to advertisement data");
            // This matches Python behavior of falling back to advertisements
            if let Err(e) = self.process_device_advertisements(device, address).await {
                debug!("Advertisement data fallback failed: {}", e);
            }
        }

        info!("GATT data collection completed: {} 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 (matching Python's iot_advertisement_data_callback_wrapper exactly)
    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();

        debug!("Parsing advertisement data for device {} with {} service entries", device_address, service_data.len());

        // Service UUID mapping (exactly matching Python TYPE_KEY_DICT)
        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 {
            debug!("Checking for {} data type with UUID {}", data_type, uuid_str);

            // Find matching service data using startswith like Python
            let mut matched_data: Option<&Vec<u8>> = None;
            for (service_uuid, data) in service_data {
                let service_str = service_uuid.to_string();
                if service_str.starts_with(uuid_str) {
                    matched_data = Some(data);
                    debug!("Found matching service UUID {} for {}", service_str, data_type);
                    break;
                }
            }

            if let Some(data) = matched_data {
                if data.is_empty() {
                    debug!("Empty data for {} - skipping", data_type);
                    continue;
                }

                debug!("Processing {} bytes of {} data: {:?}", data.len(), data_type, data);

                let iot_data = match data_type {
                    "HEART_RATE" => {
                        // Signed little-endian integer (matching Python)
                        let data_value = self.parse_signed_le_bytes(data);
                        info!("Advertisement: Heart rate = {} BPM from device {}", data_value, device_address);

                        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" => {
                        // Unsigned little-endian integer with 4.16x conversion factor
                        let raw_value = self.parse_unsigned_le_bytes(data);
                        let data_value = (raw_value as f64 * 4.16).round() as u32; // Convert to actual pressure (hPa)
                        info!("Advertisement: Pressure = {} hPa (raw: {}) from device {}", data_value, raw_value, device_address);

                        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" => {
                        // Signed little-endian integer (matching Python)
                        let data_value = self.parse_signed_le_bytes(data);
                        info!("Advertisement: Temperature = {}C from device {}", data_value, device_address);

                        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" => {
                        // Signed little-endian integer (matching Python)
                        let data_value = self.parse_signed_le_bytes(data);
                        info!("Advertisement: Battery level = {}% from device {}", data_value, device_address);

                        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" => {
                        // UTF-8 decoded string (matching Python)
                        let data_value = self.parse_bytes_to_utf8(data);
                        info!("Advertisement: Alert = {:?} from device {}", data_value, device_address);

                        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));
                            Some(IoTData::Alert(AlertData::new(data_map, device_address.to_string(), timestamp)))
                        } else {
                            warn!("Failed to decode alert data as UTF-8 for device {}", device_address);
                            None
                        }
                    }
                    _ => None,
                };

                if let Some(data) = iot_data {
                    collected_data.push(data);
                } else {
                    debug!("Failed to parse {} data for device {}", data_type, device_address);
                }
            } else {
                debug!("No {} data found in advertisements for device {}", data_type, device_address);
            }
        }

        if collected_data.is_empty() {
            debug!("No IoT data extracted from advertisements for device {}", device_address);
        }

        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
            }
        }
    }

    /// Decode IEEE 11073-20601 SFLOAT (16-bit float with 4-bit exponent, 12-bit mantissa)
    /// This is critical for blood pressure measurements
    fn decode_sfloat(&self, data: u16) -> f64 {
        // Extract 4-bit exponent (upper 4 bits) and 12-bit mantissa (lower 12 bits)
        let exponent = ((data >> 12) & 0x0F) as i8;
        let mantissa = (data & 0x0FFF) as i16;

        // Handle signed mantissa (12-bit signed value)
        let signed_mantissa = if mantissa & 0x0800 != 0 {
            // Negative: extend sign bit for 16-bit signed
            mantissa | (0xF000u16 as i16)
        } else {
            mantissa
        } as f64;

        // Handle special values
        if data == 0x07FF {
            return f64::NAN; // +INFINITY
        } else if data == 0x0800 {
            return f64::NAN; // NaN
        } else if data == 0x0801 {
            return f64::NAN; // NRes (Not at this Resolution)
        } else if data == 0x0802 {
            return f64::NAN; // Reserved
        }

        // Calculate: mantissa * 10^exponent
        signed_mantissa * 10.0_f64.powi(exponent as i32)
    }

    /// Parse blood pressure measurement data according to BLE Blood Pressure Service specification
    fn parse_blood_pressure_measurement(&self, data: &[u8]) -> Option<(f64, f64, Option<f64>, Option<i64>)> {
        if data.len() < 3 {
            return None;
        }

        let flags = data[0];
        let mut offset = 1;

        // Parse systolic pressure (always present)
        if offset + 2 > data.len() {
            return None;
        }
        let systolic_raw = u16::from_le_bytes([data[offset], data[offset + 1]]);
        let systolic = self.decode_sfloat(systolic_raw);
        offset += 2;

        // Parse diastolic pressure (always present)
        if offset + 2 > data.len() {
            return None;
        }
        let diastolic_raw = u16::from_le_bytes([data[offset], data[offset + 1]]);
        let diastolic = self.decode_sfloat(diastolic_raw);
        offset += 2;

        // Parse mean arterial pressure (always present)
        if offset + 2 > data.len() {
            return None;
        }
        let _mean_raw = u16::from_le_bytes([data[offset], data[offset + 1]]);
        offset += 2;

        // Parse timestamp if present (flag bit 1)
        let mut timestamp = None;
        if flags & 0x02 != 0 {
            if offset + 7 <= data.len() {
                // Parse date-time structure (7 bytes)
                let year = u16::from_le_bytes([data[offset], data[offset + 1]]);
                let month = data[offset + 2];
                let day = data[offset + 3];
                let hour = data[offset + 4];
                let minute = data[offset + 5];
                let second = data[offset + 6];

                // Convert to Unix timestamp (simplified)
                if let Some(datetime) = chrono::NaiveDate::from_ymd_opt(year as i32, month as u32, day as u32)
                    .and_then(|date| date.and_hms_opt(hour as u32, minute as u32, second as u32)) {
                    timestamp = Some(datetime.and_utc().timestamp());
                }
                offset += 7;
            }
        }

        // Parse pulse rate if present (flag bit 2)
        let mut pulse_rate = None;
        if flags & 0x04 != 0 {
            if offset + 2 <= data.len() {
                let pulse_raw = u16::from_le_bytes([data[offset], data[offset + 1]]);
                pulse_rate = Some(self.decode_sfloat(pulse_raw));
            }
        }

        Some((systolic, diastolic, pulse_rate, timestamp))
    }

    /// Parse device time from Current Time characteristic
    fn parse_device_time(&self, data: &[u8]) -> Option<i64> {
        if data.len() >= 7 {
            // Current Time structure: year(2), month(1), day(1), hour(1), minute(1), second(1), ...
            let year = u16::from_le_bytes([data[0], data[1]]);
            let month = data[2];
            let day = data[3];
            let hour = data[4];
            let minute = data[5];
            let second = data[6];

            if let Some(datetime) = chrono::NaiveDate::from_ymd_opt(year as i32, month as u32, day as u32)
                .and_then(|date| date.and_hms_opt(hour as u32, minute as u32, second as u32)) {
                Some(datetime.and_utc().timestamp())
            } else {
                None
            }
        } else {
            None
        }
    }

    /// Try to read a specific characteristic (simplified approach)
    async fn try_read_characteristic(&self, device: &Device, characteristic_uuid: &str) -> Result<Vec<u8>> {
        // This is a placeholder for GATT characteristic reading
        // The actual implementation would depend on bluer's stable GATT API
        debug!("Attempting to read characteristic {} from device", characteristic_uuid);

        // For now, return an error to indicate GATT operations are not yet implemented
        Err(Error::General("GATT operations not yet implemented with current bluer API".to_string()))
    }

    /// Placeholder for blood pressure notification subscription
    /// This will be implemented when bluer's GATT API is more stable
    async fn subscribe_to_blood_pressure_notifications(
        &self,
        device: &Device,
        address: &str,
        base_timestamp: i64
    ) -> Result<Vec<IoTData>> {
        info!("Blood pressure notification subscription not yet implemented for device: {}", address);
        debug!("Will rely on advertisement data for blood pressure measurements");

        // For now, return empty data and rely on advertisement processing
        Ok(Vec::new())
    }

    /// 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)))
    }

    /// Connect to a device
    pub async fn connect_device(&self, address: &str) -> Result<bool> {
        info!("Attempting to connect to device: {}", address);

        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 already connected
        if device.is_connected().await.unwrap_or(false) {
            info!("Device {} is already connected", address);
            self.device_memory.set_device_connected(address, true).await?;
            return Ok(true);
        }

        // Try to connect with retry logic
        for attempt in 1..=3 {
            match device.connect().await {
                Ok(()) => {
                    info!("Successfully connected to device {} on attempt {}", address, attempt);
                    self.device_memory.set_device_connected(address, true).await?;
                    return Ok(true);
                }
                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)));
                }
            }
        }

        Ok(false)
    }

    /// Disconnect from a device
    pub async fn disconnect_device(&self, address: &str) -> Result<bool> {
        info!("Attempting to disconnect from device: {}", address);

        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 already disconnected
        if !device.is_connected().await.unwrap_or(true) {
            info!("Device {} is already disconnected", address);
            self.device_memory.set_device_connected(address, false).await?;
            return Ok(true);
        }

        // Disconnect
        match device.disconnect().await {
            Ok(()) => {
                info!("Successfully disconnected from device {}", address);
                self.device_memory.set_device_connected(address, false).await?;
                Ok(true)
            }
            Err(e) => {
                error!("Failed to disconnect from device {}: {}", address, e);
                Err(Error::General(format!("Disconnect failed: {}", e)))
            }
        }
    }

    /// Get device class for a device address
    pub async fn get_device_class(&self, address: &str) -> Result<u32> {
        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)))?;

        match device.class().await {
            Ok(Some(class)) => Ok(class),
            Ok(None) => Ok(0),
            Err(e) => {
                debug!("Failed to get class for device {}: {}", address, e);
                Ok(0)
            }
        }
    }

    /// Get appearance for a device address
    pub async fn get_device_appearance(&self, address: &str) -> Result<u16> {
        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)))?;

        match device.appearance().await {
            Ok(Some(appearance)) => Ok(appearance),
            Ok(None) => Ok(0),
            Err(e) => {
                debug!("Failed to get appearance for device {}: {}", address, e);
                Ok(0)
            }
        }
    }

    /// 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