hippox-drivers 0.3.5

🦛All indivisible atomic driver units in Hippox.
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
//! Shared utilities for Bluetooth control across platforms
//!
//! This module provides cross-platform utilities for Bluetooth management,
//! including device discovery, pairing, connection control, and adapter status.
//! It abstracts platform-specific implementations behind a unified API.
use crate::DriverError;
use crate::result::DriverResult;
use serde::{Deserialize, Serialize};
use std::process::Command;
use tracing::{debug, info, warn};
/// Bluetooth device information
///
/// Contains comprehensive information about a Bluetooth device including
/// its name, MAC address, connection status, and signal strength.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BluetoothDevice {
    /// Human-readable device name
    pub name: String,
    /// MAC address in format XX:XX:XX:XX:XX:XX
    pub mac_address: String,
    /// Device type (e.g., Audio, HID, Phone)
    pub device_type: String,
    /// Whether the device is paired with this system
    pub paired: bool,
    /// Whether the device is currently connected
    pub connected: bool,
    /// Signal strength in dBm (RSSI), if available
    pub rssi: Option<i32>,
    /// Battery level as percentage (0-100), if available
    pub battery_level: Option<u8>,
}
/// Bluetooth adapter status
///
/// Contains the current state of the Bluetooth adapter including
/// power state, discoverability, and configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BluetoothAdapterStatus {
    /// Whether the Bluetooth adapter is powered on
    pub powered_on: bool,
    /// Whether the adapter is in discoverable mode
    pub discoverable: bool,
    /// Whether the adapter is pairable
    pub pairable: bool,
    /// The adapter's display name
    pub name: String,
    /// The adapter's MAC address
    pub mac_address: String,
    /// How long the adapter stays discoverable (seconds), 0 = unlimited
    pub discoverable_timeout: u32,
}
/// Bluetooth service/characteristic info for BLE GATT
///
/// Represents a BLE service with its UUID, name, and associated characteristics.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BluetoothService {
    /// Service UUID
    pub uuid: String,
    /// Human-readable service name
    pub name: String,
    /// Whether this is a primary service
    pub primary: bool,
    /// List of characteristics belonging to this service
    pub characteristics: Vec<BluetoothCharacteristic>,
}
/// Bluetooth characteristic info for BLE GATT
///
/// Represents a BLE characteristic with its UUID, properties, and value.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BluetoothCharacteristic {
    /// Characteristic UUID
    pub uuid: String,
    /// Human-readable characteristic name
    pub name: String,
    /// List of properties (read, write, notify, etc.)
    pub properties: Vec<String>,
    /// Current value of the characteristic, if available
    pub value: Option<Vec<u8>>,
}
/// Get Bluetooth adapter status (Windows)
///
/// Retrieves the current status of the Bluetooth adapter on Windows
/// using PowerShell commands.
#[cfg(target_os = "windows")]
pub fn get_adapter_status() -> DriverResult<BluetoothAdapterStatus> {
    debug!("Getting adapter status on Windows");
    let output = crate::common::hidden_cmd("powershell")
        .args(["-Command", "Get-PnpDevice -Class Bluetooth | Select-Object Status, FriendlyName"])
        .output()
        .map_err(|e| {
            let err_msg = format!("Failed to execute PowerShell: {}", e);
            warn!("{}", err_msg);
            return DriverError::execution(err_msg);
        })?;
    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut powered_on = false;
    let mut name = "Unknown".to_string();
    for line in stdout.lines() {
        if line.contains("OK") || line.contains("正在运行") {
            powered_on = true;
            debug!("Bluetooth adapter is powered on");
        }
        if line.contains("Bluetooth") && !line.contains("Status") {
            name = line.trim().to_string();
            debug!("Adapter name: {}", name);
        }
    }
    let mac_address = get_mac_address()?;
    debug!("Adapter MAC address: {}", mac_address);
    return Ok(BluetoothAdapterStatus { powered_on, discoverable: false, pairable: true, name, mac_address, discoverable_timeout: 120 });
}
/// Get Bluetooth adapter status (Linux)
///
/// Retrieves the current status of the Bluetooth adapter on Linux
/// using bluetoothctl commands.
#[cfg(target_os = "linux")]
pub fn get_adapter_status() -> DriverResult<BluetoothAdapterStatus> {
    debug!("Getting adapter status on Linux");
    let output = crate::common::hidden_cmd("bluetoothctl").args(["show"]).output().map_err(|e| {
        let err_msg = format!("Failed to execute bluetoothctl: {}", e);
        warn!("{}", err_msg);
        return DriverError::execution(err_msg);
    })?;
    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut powered_on = false;
    let mut discoverable = false;
    let mut pairable = true;
    let mut name = "Unknown".to_string();
    let mut mac_address = "Unknown".to_string();
    let mut discoverable_timeout = 0;
    for line in stdout.lines() {
        if line.contains("Powered:") && line.contains("yes") {
            powered_on = true;
            debug!("Adapter is powered on");
        }
        if line.contains("Discoverable:") && line.contains("yes") {
            discoverable = true;
            debug!("Adapter is discoverable");
        }
        if line.contains("Name:") {
            if let Some(n) = line.split(':').nth(1) {
                name = n.trim().to_string();
                debug!("Adapter name: {}", name);
            }
        }
        if line.contains("Address:") {
            if let Some(addr) = line.split(':').nth(1) {
                mac_address = addr.trim().to_string();
                debug!("Adapter MAC address: {}", mac_address);
            }
        }
        if line.contains("DiscoverableTimeout:") {
            if let Some(t) = line.split(':').nth(1) {
                discoverable_timeout = t.trim().parse().unwrap_or(0);
                debug!("Discoverable timeout: {}s", discoverable_timeout);
            }
        }
    }
    return Ok(BluetoothAdapterStatus { powered_on, discoverable, pairable, name, mac_address, discoverable_timeout });
}
/// Get Bluetooth adapter status (macOS)
///
/// Retrieves the current status of the Bluetooth adapter on macOS
/// using system_profiler.
#[cfg(target_os = "macos")]
pub fn get_adapter_status() -> DriverResult<BluetoothAdapterStatus> {
    debug!("Getting adapter status on macOS");
    let output = crate::common::hidden_cmd("system_profiler").args(["SPBluetoothDataType"]).output().map_err(|e| {
        let err_msg = format!("Failed to execute system_profiler: {}", e);
        warn!("{}", err_msg);
        return DriverError::execution(err_msg);
    })?;
    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut powered_on = false;
    let mut name = "Unknown".to_string();
    let mut mac_address = "Unknown".to_string();
    for line in stdout.lines() {
        if line.contains("Bluetooth Power: On") {
            powered_on = true;
            debug!("Adapter is powered on");
        }
        if line.contains("Name:") {
            if let Some(n) = line.split(':').nth(1) {
                name = n.trim().to_string();
                debug!("Adapter name: {}", name);
            }
        }
        if line.contains("Address:") {
            if let Some(addr) = line.split(':').nth(1) {
                mac_address = addr.trim().to_string();
                debug!("Adapter MAC address: {}", mac_address);
            }
        }
    }
    return Ok(BluetoothAdapterStatus { powered_on, discoverable: true, pairable: true, name, mac_address, discoverable_timeout: 120 });
}
/// Get Bluetooth MAC address
///
/// Retrieves the MAC address of the local Bluetooth adapter.
/// This function works across all supported platforms.
pub fn get_mac_address() -> DriverResult<String> {
    debug!("Getting Bluetooth MAC address");
    #[cfg(target_os = "linux")]
    {
        let output = crate::common::hidden_cmd("bluetoothctl").args(["show"]).output().map_err(|e| {
            let err_msg = format!("Failed to execute bluetoothctl: {}", e);
            warn!("{}", err_msg);
            return DriverError::execution(err_msg);
        })?;
        let stdout = String::from_utf8_lossy(&output.stdout);
        for line in stdout.lines() {
            if line.contains("Address:") {
                if let Some(addr) = line.split(':').nth(1) {
                    let mac = addr.trim().to_string();
                    debug!("MAC address found: {}", mac);
                    return Ok(mac);
                }
            }
        }
    }
    #[cfg(target_os = "windows")]
    {
        let output = crate::common::hidden_cmd("getmac").output().map_err(|e| {
            let err_msg = format!("Failed to execute getmac: {}", e);
            warn!("{}", err_msg);
            return DriverError::execution(err_msg);
        })?;
        let stdout = String::from_utf8_lossy(&output.stdout);
        for line in stdout.lines() {
            if line.contains("Bluetooth") {
                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.len() >= 1 {
                    let mac = parts[0].to_string();
                    debug!("MAC address found: {}", mac);
                    return Ok(mac);
                }
            }
        }
    }
    #[cfg(target_os = "macos")]
    {
        let output = crate::common::hidden_cmd("system_profiler").args(["SPBluetoothDataType"]).output().map_err(|e| {
            let err_msg = format!("Failed to execute system_profiler: {}", e);
            warn!("{}", err_msg);
            return DriverError::execution(err_msg);
        })?;
        let stdout = String::from_utf8_lossy(&output.stdout);
        for line in stdout.lines() {
            if line.contains("Address:") {
                if let Some(addr) = line.split(':').nth(1) {
                    let mac = addr.trim().to_string();
                    debug!("MAC address found: {}", mac);
                    return Ok(mac);
                }
            }
        }
    }
    warn!("MAC address not found, returning 'Unknown'");
    return Ok("Unknown".to_string());
}
/// Turn Bluetooth on
///
/// Enables the Bluetooth adapter. On macOS, this requires the `blueutil` tool.
#[cfg(target_os = "linux")]
pub fn bluetooth_on() -> DriverResult<()> {
    debug!("Turning Bluetooth on (Linux)");
    crate::common::hidden_cmd("bluetoothctl").args(["power", "on"]).output().map_err(|e| {
        let err_msg = format!("Failed to execute bluetoothctl: {}", e);
        warn!("{}", err_msg);
        return DriverError::execution(err_msg);
    })?;
    info!("Bluetooth turned on");
    return Ok(());
}
#[cfg(target_os = "windows")]
pub fn bluetooth_on() -> DriverResult<()> {
    debug!("Turning Bluetooth on (Windows)");
    crate::common::hidden_cmd("powershell").args(["-Command", "Enable-PnpDevice -Class Bluetooth -ErrorAction SilentlyContinue"]).output().map_err(|e| {
        let err_msg = format!("Failed to execute PowerShell: {}", e);
        warn!("{}", err_msg);
        return DriverError::execution(err_msg);
    })?;
    info!("Bluetooth turned on");
    return Ok(());
}
#[cfg(target_os = "macos")]
pub fn bluetooth_on() -> DriverResult<()> {
    debug!("Turning Bluetooth on (macOS)");
    let output = crate::common::hidden_cmd("blueutil").args(["--power", "1"]).output();
    if output.is_err() {
        let err_msg = "blueutil not installed. Run: brew install blueutil".to_string();
        warn!("{}", err_msg);
        return Err(DriverError::execution(err_msg));
    }
    info!("Bluetooth turned on");
    return Ok(());
}
/// Turn Bluetooth off
///
/// Disables the Bluetooth adapter. On macOS, this requires the `blueutil` tool.
#[cfg(target_os = "linux")]
pub fn bluetooth_off() -> DriverResult<()> {
    debug!("Turning Bluetooth off (Linux)");
    crate::common::hidden_cmd("bluetoothctl").args(["power", "off"]).output().map_err(|e| {
        let err_msg = format!("Failed to execute bluetoothctl: {}", e);
        warn!("{}", err_msg);
        return DriverError::execution(err_msg);
    })?;
    info!("Bluetooth turned off");
    return Ok(());
}
#[cfg(target_os = "windows")]
pub fn bluetooth_off() -> DriverResult<()> {
    debug!("Turning Bluetooth off (Windows)");
    crate::common::hidden_cmd("powershell").args(["-Command", "Disable-PnpDevice -Class Bluetooth -ErrorAction SilentlyContinue"]).output().map_err(|e| {
        let err_msg = format!("Failed to execute PowerShell: {}", e);
        warn!("{}", err_msg);
        return DriverError::execution(err_msg);
    })?;
    info!("Bluetooth turned off");
    return Ok(());
}
#[cfg(target_os = "macos")]
pub fn bluetooth_off() -> DriverResult<()> {
    debug!("Turning Bluetooth off (macOS)");
    let output = crate::common::hidden_cmd("blueutil").args(["--power", "0"]).output();
    if output.is_err() {
        let err_msg = "blueutil not installed. Run: brew install blueutil".to_string();
        warn!("{}", err_msg);
        return Err(DriverError::execution(err_msg));
    }
    info!("Bluetooth turned off");
    return Ok(());
}
/// Scan for Bluetooth devices
///
/// Performs a scan for nearby Bluetooth devices and returns a list
/// of discovered devices with their information.
#[cfg(target_os = "linux")]
pub fn scan_devices() -> DriverResult<Vec<BluetoothDevice>> {
    debug!("Starting Bluetooth scan (Linux)");
    // Start scan
    debug!("Starting discovery scan");
    let _ = crate::common::hidden_cmd("bluetoothctl").args(["scan", "on"]).output();
    // Wait for scan results
    debug!("Waiting 5 seconds for scan results");
    std::thread::sleep(std::time::Duration::from_secs(5));
    let output = crate::common::hidden_cmd("bluetoothctl").args(["devices"]).output().map_err(|e| {
        let err_msg = format!("Failed to execute bluetoothctl: {}", e);
        warn!("{}", err_msg);
        return DriverError::execution(err_msg);
    })?;
    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut devices = Vec::new();
    for line in stdout.lines() {
        if line.starts_with("Device") {
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() >= 3 {
                let device = BluetoothDevice {
                    mac_address: parts[1].to_string(),
                    name: parts[2..].join(" "),
                    device_type: "Unknown".to_string(),
                    paired: false,
                    connected: false,
                    rssi: None,
                    battery_level: None,
                };
                debug!("Found device: {} ({})", device.name, device.mac_address);
                devices.push(device);
            }
        }
    }
    // Stop scan
    debug!("Stopping discovery scan");
    let _ = crate::common::hidden_cmd("bluetoothctl").args(["scan", "off"]).output();
    info!("Scan complete, found {} devices", devices.len());
    return Ok(devices);
}
#[cfg(target_os = "windows")]
pub fn scan_devices() -> DriverResult<Vec<BluetoothDevice>> {
    debug!("Starting Bluetooth scan (Windows)");
    let output = crate::common::hidden_cmd("powershell")
        .args(["-Command", "Get-PnpDevice -Class Bluetooth | Select-Object FriendlyName, InstanceId"])
        .output()
        .map_err(|e| {
            let err_msg = format!("Failed to execute PowerShell: {}", e);
            warn!("{}", err_msg);
            return DriverError::execution(err_msg);
        })?;
    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut devices = Vec::new();
    for line in stdout.lines().skip(1) {
        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.len() >= 1 && !line.contains("Bluetooth") {
            let device = BluetoothDevice {
                name: parts[0].to_string(),
                mac_address: "Unknown".to_string(),
                device_type: "Unknown".to_string(),
                paired: false,
                connected: false,
                rssi: None,
                battery_level: None,
            };
            debug!("Found device: {}", device.name);
            devices.push(device);
        }
    }
    info!("Scan complete, found {} devices", devices.len());
    return Ok(devices);
}
#[cfg(target_os = "macos")]
pub fn scan_devices() -> DriverResult<Vec<BluetoothDevice>> {
    debug!("Starting Bluetooth scan (macOS)");
    let output = crate::common::hidden_cmd("system_profiler").args(["SPBluetoothDataType"]).output().map_err(|e| {
        let err_msg = format!("Failed to execute system_profiler: {}", e);
        warn!("{}", err_msg);
        return DriverError::execution(err_msg);
    })?;
    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut devices = Vec::new();
    let mut current_device: Option<BluetoothDevice> = None;
    for line in stdout.lines() {
        if line.contains("Fully Qualified") {
            if let Some(device) = current_device.take() {
                devices.push(device);
            }
            if let Some(name) = line.split(':').nth(1) {
                debug!("Found device: {}", name.trim());
                current_device = Some(BluetoothDevice {
                    name: name.trim().to_string(),
                    mac_address: "Unknown".to_string(),
                    device_type: "Unknown".to_string(),
                    paired: false,
                    connected: false,
                    rssi: None,
                    battery_level: None,
                });
            }
        }
        if let Some(ref mut device) = current_device {
            if line.contains("Address:") {
                if let Some(addr) = line.split(':').nth(1) {
                    device.mac_address = addr.trim().to_string();
                    debug!("Device MAC: {}", device.mac_address);
                }
            }
            if line.contains("Connected: Yes") {
                device.connected = true;
                debug!("Device is connected");
            }
            if line.contains("Paired: Yes") {
                device.paired = true;
                debug!("Device is paired");
            }
        }
    }
    if let Some(device) = current_device {
        devices.push(device);
    }
    info!("Scan complete, found {} devices", devices.len());
    return Ok(devices);
}
/// Pair with a device
///
/// Initiates pairing with a discovered Bluetooth device.
/// On non-Linux platforms, this may require GUI interaction.
#[cfg(target_os = "linux")]
pub fn pair_device(mac_address: &str) -> DriverResult<()> {
    debug!("Pairing with device: {}", mac_address);
    crate::common::hidden_cmd("bluetoothctl").args(["pair", mac_address]).output().map_err(|e| {
        let err_msg = format!("Failed to execute bluetoothctl: {}", e);
        warn!("{}", err_msg);
        return DriverError::execution(err_msg);
    })?;
    info!("Paired with device: {}", mac_address);
    return Ok(());
}
#[cfg(not(target_os = "linux"))]
pub fn pair_device(mac_address: &str) -> DriverResult<()> {
    debug!("Pairing not supported on this platform: {}", mac_address);
    let err_msg = "Pairing on this platform requires GUI interaction".to_string();
    warn!("{}", err_msg);
    return Err(DriverError::execution(err_msg));
}
/// Unpair a device
///
/// Removes a device from the paired devices list.
/// On non-Linux platforms, this may require GUI interaction.
#[cfg(target_os = "linux")]
pub fn unpair_device(mac_address: &str) -> DriverResult<()> {
    debug!("Unpairing device: {}", mac_address);
    crate::common::hidden_cmd("bluetoothctl").args(["remove", mac_address]).output().map_err(|e| {
        let err_msg = format!("Failed to execute bluetoothctl: {}", e);
        warn!("{}", err_msg);
        return DriverError::execution(err_msg);
    })?;
    info!("Unpaired device: {}", mac_address);
    return Ok(());
}
#[cfg(not(target_os = "linux"))]
pub fn unpair_device(mac_address: &str) -> DriverResult<()> {
    debug!("Unpairing not supported on this platform: {}", mac_address);
    let err_msg = "Unpairing on this platform requires GUI interaction".to_string();
    warn!("{}", err_msg);
    return Err(DriverError::execution(err_msg));
}
/// List paired devices
///
/// Retrieves the list of all devices that are paired with this system.
#[cfg(target_os = "linux")]
pub fn list_paired_devices() -> DriverResult<Vec<BluetoothDevice>> {
    debug!("Listing paired devices (Linux)");
    let output = crate::common::hidden_cmd("bluetoothctl").args(["paired-devices"]).output().map_err(|e| {
        let err_msg = format!("Failed to execute bluetoothctl: {}", e);
        warn!("{}", err_msg);
        return DriverError::execution(err_msg);
    })?;
    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut devices = Vec::new();
    for line in stdout.lines() {
        if line.starts_with("Device") {
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.len() >= 3 {
                let device = BluetoothDevice {
                    mac_address: parts[1].to_string(),
                    name: parts[2..].join(" "),
                    device_type: "Unknown".to_string(),
                    paired: true,
                    connected: false,
                    rssi: None,
                    battery_level: None,
                };
                debug!("Paired device: {} ({})", device.name, device.mac_address);
                devices.push(device);
            }
        }
    }
    info!("Found {} paired devices", devices.len());
    return Ok(devices);
}
#[cfg(target_os = "windows")]
pub fn list_paired_devices() -> DriverResult<Vec<BluetoothDevice>> {
    debug!("Listing paired devices (Windows)");
    let output = crate::common::hidden_cmd("powershell")
        .args(["-Command", "Get-PnpDevice -Class Bluetooth | Where-Object {$_.FriendlyName -notlike '*Radio*'} | Select-Object FriendlyName, Status"])
        .output()
        .map_err(|e| {
            let err_msg = format!("Failed to execute PowerShell: {}", e);
            warn!("{}", err_msg);
            return DriverError::execution(err_msg);
        })?;
    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut devices = Vec::new();
    for line in stdout.lines().skip(1) {
        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.len() >= 1 {
            let connected = parts.contains(&"OK");
            let device = BluetoothDevice {
                name: parts[0].to_string(),
                mac_address: "Unknown".to_string(),
                device_type: "Unknown".to_string(),
                paired: true,
                connected,
                rssi: None,
                battery_level: None,
            };
            debug!("Paired device: {} (connected: {})", device.name, connected);
            devices.push(device);
        }
    }
    info!("Found {} paired devices", devices.len());
    return Ok(devices);
}
#[cfg(target_os = "macos")]
pub fn list_paired_devices() -> DriverResult<Vec<BluetoothDevice>> {
    debug!("Listing paired devices (macOS) - using scan_devices");
    return scan_devices();
}
/// Connect to a device
///
/// Establishes a connection to a paired Bluetooth device.
/// On non-Linux platforms, this may require GUI interaction.
#[cfg(target_os = "linux")]
pub fn connect_device(mac_address: &str) -> DriverResult<()> {
    debug!("Connecting to device: {}", mac_address);
    crate::common::hidden_cmd("bluetoothctl").args(["connect", mac_address]).output().map_err(|e| {
        let err_msg = format!("Failed to execute bluetoothctl: {}", e);
        warn!("{}", err_msg);
        return DriverError::execution(err_msg);
    })?;
    info!("Connected to device: {}", mac_address);
    return Ok(());
}
#[cfg(not(target_os = "linux"))]
pub fn connect_device(mac_address: &str) -> DriverResult<()> {
    debug!("Connecting not supported on this platform: {}", mac_address);
    let err_msg = "Connecting on this platform requires GUI interaction".to_string();
    warn!("{}", err_msg);
    return Err(DriverError::execution(err_msg));
}
/// Disconnect a device
///
/// Disconnects a connected Bluetooth device while keeping it paired.
/// On non-Linux platforms, this may require GUI interaction.
#[cfg(target_os = "linux")]
pub fn disconnect_device(mac_address: &str) -> DriverResult<()> {
    debug!("Disconnecting device: {}", mac_address);
    crate::common::hidden_cmd("bluetoothctl").args(["disconnect", mac_address]).output().map_err(|e| {
        let err_msg = format!("Failed to execute bluetoothctl: {}", e);
        warn!("{}", err_msg);
        return DriverError::execution(err_msg);
    })?;
    info!("Disconnected from device: {}", mac_address);
    return Ok(());
}
#[cfg(not(target_os = "linux"))]
pub fn disconnect_device(mac_address: &str) -> DriverResult<()> {
    debug!("Disconnecting not supported on this platform: {}", mac_address);
    let err_msg = "Disconnecting on this platform requires GUI interaction".to_string();
    warn!("{}", err_msg);
    return Err(DriverError::execution(err_msg));
}
/// Set discoverable mode
///
/// Enables or disables discoverable mode for the Bluetooth adapter.
/// On non-Linux platforms, this may require GUI interaction.
#[cfg(target_os = "linux")]
pub fn set_discoverable(discoverable: bool, timeout: Option<u32>) -> DriverResult<()> {
    debug!("Setting discoverable mode: enabled={}, timeout={:?}", discoverable, timeout);
    if discoverable {
        if let Some(t) = timeout {
            debug!("Setting discoverable timeout to {}s", t);
            crate::common::hidden_cmd("bluetoothctl").args(["discoverable-timeout", &t.to_string()]).output().map_err(|e| {
                let err_msg = format!("Failed to set discoverable timeout: {}", e);
                warn!("{}", err_msg);
                return DriverError::execution(err_msg);
            })?;
        }
        debug!("Turning discoverable on");
        crate::common::hidden_cmd("bluetoothctl").args(["discoverable", "on"]).output().map_err(|e| {
            let err_msg = format!("Failed to enable discoverable: {}", e);
            warn!("{}", err_msg);
            return DriverError::execution(err_msg);
        })?;
    } else {
        debug!("Turning discoverable off");
        crate::common::hidden_cmd("bluetoothctl").args(["discoverable", "off"]).output().map_err(|e| {
            let err_msg = format!("Failed to disable discoverable: {}", e);
            warn!("{}", err_msg);
            return DriverError::execution(err_msg);
        })?;
    }
    info!("Discoverable mode set: enabled={}", discoverable);
    return Ok(());
}
#[cfg(not(target_os = "linux"))]
pub fn set_discoverable(discoverable: bool, timeout: Option<u32>) -> DriverResult<()> {
    let _ = (discoverable, timeout);
    debug!("Setting discoverable not supported on this platform");
    let err_msg = "Discoverable mode on this platform requires GUI interaction".to_string();
    warn!("{}", err_msg);
    return Err(DriverError::execution(err_msg));
}
/// Set device name
///
/// Changes the display name of the Bluetooth adapter.
/// On non-Linux platforms, this may require system preferences.
#[cfg(target_os = "linux")]
pub fn set_device_name(name: &str) -> DriverResult<()> {
    debug!("Setting device name to: {}", name);
    crate::common::hidden_cmd("bluetoothctl").args(["name", name]).output().map_err(|e| {
        let err_msg = format!("Failed to execute bluetoothctl: {}", e);
        warn!("{}", err_msg);
        return DriverError::execution(err_msg);
    })?;
    info!("Device name set to: {}", name);
    return Ok(());
}
#[cfg(not(target_os = "linux"))]
pub fn set_device_name(name: &str) -> DriverResult<()> {
    let _ = name;
    debug!("Setting device name not supported on this platform");
    let err_msg = "Setting device name on this platform requires system preferences".to_string();
    warn!("{}", err_msg);
    return Err(DriverError::execution(err_msg));
}
/// Get list of connected devices
///
/// Retrieves the list of currently connected Bluetooth devices.
pub fn get_connected_devices() -> DriverResult<Vec<BluetoothDevice>> {
    debug!("Getting connected devices");
    let all_devices = list_paired_devices()?;
    let connected: Vec<BluetoothDevice> = all_devices.into_iter().filter(|d| d.connected).collect();
    info!("Found {} connected devices", connected.len());
    return Ok(connected);
}
/// Send file via Bluetooth (OBEX)
///
/// Sends a file to a Bluetooth device using OBEX Object Push.
/// On Linux, this requires the `obexftp` tool to be installed.
#[cfg(target_os = "linux")]
pub fn send_file(mac_address: &str, file_path: &str) -> DriverResult<()> {
    debug!("Sending file {} to {}", file_path, mac_address);
    let output = crate::common::hidden_cmd("obexftp").args(["-b", mac_address, "-p", file_path]).output();
    if output.is_err() {
        let err_msg = "obexftp not installed. Please install obexftp package".to_string();
        warn!("{}", err_msg);
        return Err(DriverError::execution(err_msg));
    }
    info!("File sent successfully to {}", mac_address);
    return Ok(());
}
#[cfg(not(target_os = "linux"))]
pub fn send_file(mac_address: &str, file_path: &str) -> DriverResult<()> {
    let _ = (mac_address, file_path);
    debug!("File transfer not supported on this platform");
    let err_msg = "File transfer on this platform requires GUI interaction".to_string();
    warn!("{}", err_msg);
    return Err(DriverError::execution(err_msg));
}
// Platform-agnostic fallbacks
//
// These functions provide fallback implementations for platforms
// that don't have native Bluetooth support.
#[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
pub fn bluetooth_on() -> DriverResult<()> {
    debug!("Bluetooth not implemented on this platform");
    let err_msg = "Bluetooth not implemented on this platform".to_string();
    warn!("{}", err_msg);
    return Err(DriverError::execution(err_msg));
}
#[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
pub fn bluetooth_off() -> DriverResult<()> {
    debug!("Bluetooth not implemented on this platform");
    let err_msg = "Bluetooth not implemented on this platform".to_string();
    warn!("{}", err_msg);
    return Err(DriverError::execution(err_msg));
}