bluetooth-rust 0.3.8

A bluetooth communication library
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
#![deny(missing_docs)]
#![deny(clippy::missing_docs_in_private_items)]
#![warn(unused_extern_crates)]

//! This library is intended to eventually be a cross-platform bluetooth handling platform
//! Android portions adapted from <https://github.com/wuwbobo2021/android-bluetooth-serial-rs>

#[cfg(target_os = "android")]
use std::sync::Arc;
#[cfg(target_os = "android")]
use std::sync::Mutex;
#[cfg(target_os = "android")]
mod android;
#[cfg(target_os = "android")]
pub use android::Bluetooth;
#[cfg(target_os = "android")]
pub use android::Java;
#[cfg(target_os = "android")]
use winit::platform::android::activity::AndroidApp;

#[cfg(target_os = "linux")]
mod linux;

#[cfg(target_os = "windows")]
mod windows;

mod bluetooth_uuid;
pub use bluetooth_uuid::BluetoothUuid;

mod sdp;

/// Commands issued to the library
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub enum BluetoothCommand {
    /// Detect all bluetooth adapters present on the system
    DetectAdapters,
    /// Find out how many bluetooth adapters are detected
    QueryNumAdapters,
}

/// Messages that can be sent specifically to the app user hosting the bluetooth controls
pub enum MessageToBluetoothHost {
    /// The passkey used for pairing devices
    DisplayPasskey(u32, tokio::sync::mpsc::Sender<ResponseToPasskey>),
    /// The passkey to confirm for pairing
    ConfirmPasskey(u32, tokio::sync::mpsc::Sender<ResponseToPasskey>),
    /// Cancal the passkey display
    CancelDisplayPasskey,
}

#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
/// Messages that are send directly from the bluetooth host
pub enum MessageFromBluetoothHost {
    /// A response about the active pairing passkey
    PasskeyMessage(ResponseToPasskey),
}

#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
/// The user response to a bluetooth passkey
pub enum ResponseToPasskey {
    /// The passkey is accepted
    Yes,
    /// The passkey is not accepted
    No,
    /// The process is canceled by the user
    Cancel,
    /// Waiting on the user to decide
    Waiting,
}

/// Responses issued by the library
pub enum BluetoothResponse {
    /// The number of bluetooth adapters detected
    Adapters(usize),
}

/// Settings for an rfcomm profile
#[derive(Clone, Debug)]
pub struct BluetoothRfcommProfileSettings {
    /// The uuid for the profile
    pub uuid: String,
    /// User readable name for the profile
    pub name: Option<String>,
    /// The service uuid for the profile (can be the same as service)
    pub service_uuid: Option<String>,
    /// The channel to use
    pub channel: Option<u16>,
    /// PSM number used for UUIDS and SDP (if applicable)
    pub psm: Option<u16>,
    /// Is authentication required for a connection
    pub authenticate: Option<bool>,
    /// Is authorization required for a connection
    pub authorize: Option<bool>,
    /// For client profiles, This will force connection of the channel when a remote device is connected
    pub auto_connect: Option<bool>,
    /// manual SDP record
    pub sdp_record: Option<String>,
    /// SDP version
    pub sdp_version: Option<u16>,
    /// SDP profile features
    pub sdp_features: Option<u16>,
}

/// Settings for an rfcomm profile
#[derive(Clone)]
pub struct BluetoothL2capProfileSettings {
    /// The uuid for the profile
    pub uuid: String,
    /// User readable name for the profile
    pub name: Option<String>,
    /// The service uuid for the profile (can be the same as service)
    pub service_uuid: Option<String>,
    /// The channel to use
    pub channel: Option<u16>,
    /// PSM number used for UUIDS and SDP (if applicable)
    pub psm: Option<u16>,
    /// Is authentication required for a connection
    pub authenticate: Option<bool>,
    /// Is authorization required for a connection
    pub authorize: Option<bool>,
    /// For client profiles, This will force connection of the channel when a remote device is connected
    pub auto_connect: Option<bool>,
    /// manual SDP record
    pub sdp_record: Option<String>,
    /// SDP version
    pub sdp_version: Option<u16>,
    /// SDP profile features
    pub sdp_features: Option<u16>,
}

/// The trait that implements managing when bluetooth discovery is enabled
#[enum_dispatch::enum_dispatch]
pub trait BluetoothDiscoveryTrait {}

/// The trait for the object that manages bluetooth discovery
#[enum_dispatch::enum_dispatch(BluetoothDiscoveryTrait)]
pub enum BluetoothDiscovery {
    /// The android version
    #[cfg(target_os = "android")]
    Android(android::BluetoothDiscovery),
    /// Linux bluez library implementation
    #[cfg(target_os = "linux")]
    Bluez(linux::BluetoothDiscovery),
    /// Windows implementation
    #[cfg(target_os = "windows")]
    Windows(windows::BluetoothDiscovery),
}

/// The address of a bluetooth adapter
pub enum BluetoothAdapterAddress {
    /// The address in string form
    String(String),
    /// The address in byte form
    Byte([u8; 6]),
}

/// Common async functionality for the bluetooth adapter
#[enum_dispatch::enum_dispatch]
#[async_trait::async_trait]
pub trait AsyncBluetoothAdapterTrait {
    /// Attempt to register a new rfcomm profile
    async fn register_rfcomm_profile(
        &self,
        settings: BluetoothRfcommProfileSettings,
    ) -> Result<BluetoothRfcommProfileAsync, String>;
    /// Attempt to register a new l2cap profile
    async fn register_l2cap_profile(
        &self,
        settings: BluetoothL2capProfileSettings,
    ) -> Result<BluetoothL2capProfileAsync, String>;
    ///Get a list of paired bluetooth devices
    fn get_paired_devices(&self) -> Option<Vec<BluetoothDevice>>;
    /// Start discovery of bluetooth devices. Run this and drop the result to cancel discovery
    fn start_discovery(&self) -> BluetoothDiscovery;
    /// Get the mac addresses of all bluetooth adapters for the system
    async fn addresses(&self) -> Vec<BluetoothAdapterAddress>;
    /// Set the discoverable property
    async fn set_discoverable(&self, d: bool) -> Result<(), ()>;
}

/// Common sync functionality for the bluetooth adapter
#[enum_dispatch::enum_dispatch]
pub trait SyncBluetoothAdapterTrait {
    /// Attempt to register a new rfcomm profile
    fn register_rfcomm_profile(
        &self,
        settings: BluetoothRfcommProfileSettings,
    ) -> Result<BluetoothRfcommProfileSync, String>;
    /// Attempt to register a new lc2ap profile
    fn register_l2cap_profile(
        &self,
        settings: BluetoothL2capProfileSettings,
    ) -> Result<BluetoothL2capProfileAsync, String>;
    ///Get a list of paired bluetooth devices
    fn get_paired_devices(&self) -> Option<Vec<BluetoothDevice>>;
    /// Start discovery of bluetooth devices. Run this and drop the result to cancel discovery
    fn start_discovery(&self) -> BluetoothDiscovery;
    /// Get the mac addresses of all bluetooth adapters for the system
    fn addresses(&self) -> Vec<BluetoothAdapterAddress>;
    /// Set the discoverable property
    fn set_discoverable(&self, d: bool) -> Result<(), ()>;
}

/// Common functionality for the bluetooth adapter
#[enum_dispatch::enum_dispatch]
pub trait BluetoothAdapterTrait {
    /// Returns Some when the async interface is supported
    fn supports_async(&self) -> Option<&dyn AsyncBluetoothAdapterTrait>;
    /// Returns Some when the sync interface is supported
    fn supports_sync(&self) -> Option<&dyn SyncBluetoothAdapterTrait>;
}

/// The pairing status of a bluetooth device
pub enum PairingStatus {
    /// The device is not paired
    NotPaired,
    /// The device is in the pairing process
    Pairing,
    /// The device is paired
    Paired,
    /// The status is unknown or invalid
    Unknown,
}

fn uuid16(uuid: u16) -> Vec<u8> {
    let mut v = Vec::new();
    v.push(0x19); // UUID-16 type
    v.extend_from_slice(&uuid.to_be_bytes());
    v
}

fn build_sdp_request(uuid: u16, transaction_id: u16) -> Vec<u8> {
    let mut pdu = Vec::new();

    // PDU ID
    pdu.push(0x06);

    // placeholder length
    let mut params = Vec::new();

    // Transaction ID
    params.extend_from_slice(&transaction_id.to_be_bytes());

    // Parameter length placeholder (filled later)

    // ServiceSearchPattern: UUID 0x1101 (SPP)
    let uuid = uuid16(uuid);
    let mut search = Vec::new();
    search.push(0x35); // sequence
    search.push(uuid.len() as u8);
    search.extend_from_slice(&uuid);
    params.extend_from_slice(&search);

    // Attribute ID list (0x0000 - 0xFFFF for everything)
    let mut attrs = Vec::new();
    attrs.push(0x35);
    attrs.push(7);
    attrs.extend_from_slice(&[
        0x09, 0x00, 0x00, // uint16 0x0000
        0x09, 0xFF, 0xFF, // uint16 0xFFFF
    ]);
    params.extend_from_slice(&attrs);

    // Max attribute bytes
    params.extend_from_slice(&0xFFFFu16.to_be_bytes());

    // Continuation state
    params.push(0x00);

    // Now patch length
    let len = params.len() as u16;
    let mut out = Vec::new();
    out.push(0x06);
    out.extend_from_slice(&transaction_id.to_be_bytes());
    out.extend_from_slice(&len.to_be_bytes());
    out.extend_from_slice(&params);

    out
}

/// The trait that all bluetooth devices must implement
#[enum_dispatch::enum_dispatch]
pub trait BluetoothDeviceTrait {
    /// Get all known uuids for this device
    fn get_uuids(&mut self) -> Result<Vec<BluetoothUuid>, std::io::Error>;

    /// Retrieve the device name
    fn get_name(&self) -> Result<String, std::io::Error>;

    /// Retrieve the device address
    fn get_address(&mut self) -> Result<String, std::io::Error>;

    /// Retrieve the device pairing status
    fn get_pair_state(&self) -> Result<PairingStatus, std::io::Error>;

    /// Attempt to get an rfcomm socket for the given uuid and security setting
    fn get_rfcomm_socket(
        &mut self,
        channel: u8,
        is_secure: bool,
    ) -> Result<BluetoothSocket, String>;

    /// Attempt to get an l2cap socket for the given uuid and security setting
    fn get_l2cap_socket(&mut self, psm: u16, is_secure: bool) -> Result<BluetoothSocket, String>;

    /// Run the service discovery protocol
    fn run_sdp(&mut self, uuid: BluetoothUuid) -> Result<sdp::ServiceRecord, String> {
        if let Ok(a) = self.get_address() {
            return sdp::run_sdp(&a, uuid.get_16_bit_id()).map_err(|e| e.to_string());
        }
        Err("Sdp failed".to_string())
    }
}

/// A bluetooth device
#[enum_dispatch::enum_dispatch(BluetoothDeviceTrait)]
pub enum BluetoothDevice {
    /// Bluetooth device on android
    #[cfg(target_os = "android")]
    Android(android::BluetoothDevice),
    /// Bluetooth device on linux using the bluez library
    #[cfg(target_os = "linux")]
    Bluez(linux::LinuxBluetoothDevice),
    /// Bluetooth device on Windows
    #[cfg(target_os = "windows")]
    Windows(windows::BluetoothDevice),
}

/// Represents a bluetooth adapter that communicates to bluetooth devices
#[enum_dispatch::enum_dispatch(BluetoothAdapterTrait)]
pub enum BluetoothAdapter {
    /// The bluetooth adapter for android systems
    #[cfg(target_os = "android")]
    Android(android::Bluetooth),
    /// On linux, bluetooth adapter using the bluez library
    #[cfg(target_os = "linux")]
    Bluez(linux::BluetoothHandler),
    /// On Windows, bluetooth adapter using the windows crate
    #[cfg(target_os = "windows")]
    Windows(windows::BluetoothHandler),
}

/// A builder for `BluetoothAdapter`
pub struct BluetoothAdapterBuilder {
    /// The androidapp object
    #[cfg(target_os = "android")]
    app: Option<AndroidApp>,
    /// The sender to send messages to the bluetooth host
    s: Option<tokio::sync::mpsc::Sender<MessageToBluetoothHost>>,
}

impl Default for BluetoothAdapterBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl BluetoothAdapterBuilder {
    /// Construct a new self
    pub fn new() -> Self {
        Self {
            #[cfg(target_os = "android")]
            app: None,
            s: None,
        }
    }

    /// Put the required `AndroidApp` object into the builder
    #[cfg(target_os = "android")]
    pub fn with_android_app(&mut self, app: AndroidApp) {
        self.app = Some(app);
    }

    /// Add the sender to the builder
    pub fn with_sender(&mut self, s: tokio::sync::mpsc::Sender<MessageToBluetoothHost>) {
        self.s = Some(s);
    }

    /// Do the build
    pub fn build(self) -> Result<BluetoothAdapter, String> {
        #[cfg(target_os = "android")]
        {
            return Ok(BluetoothAdapter::Android(android::Bluetooth::new(
                self.app.unwrap(),
            )));
        }
        Err("No synchronous builders available".to_string())
    }

    /// Do the build
    pub async fn async_build(self) -> Result<BluetoothAdapter, String> {
        #[cfg(target_os = "android")]
        {
            return self.build();
        }
        #[cfg(target_os = "linux")]
        {
            return Ok(BluetoothAdapter::Bluez(
                linux::BluetoothHandler::new(self.s.unwrap()).await?,
            ));
        }
        #[cfg(target_os = "windows")]
        {
            return Ok(BluetoothAdapter::Windows(
                windows::BluetoothHandler::new(self.s.unwrap()).await?,
            ));
        }
        Err("No async builders available".to_string())
    }
}

/// An active stream for bluetooth communications
pub enum BluetoothStream {
    /// On linux, a stream using the bluez library
    #[cfg(target_os = "linux")]
    Bluez(std::pin::Pin<Box<bluer::rfcomm::Stream>>),
    /// Android code for a bluetooth stream
    #[cfg(target_os = "android")]
    Android(android::RfcommStream),
    /// Windows RFCOMM stream
    #[cfg(target_os = "windows")]
    Windows(windows::WindowsRfcommStream),
}

macro_rules! pin_match {
    ($this:expr, $s:ident => $body:expr) => {
        match $this.get_mut() {
            #[cfg(target_os = "linux")]
            BluetoothStream::Bluez($s) => $body,

            #[cfg(target_os = "android")]
            BluetoothStream::Android($s) => $body,

            #[cfg(target_os = "windows")]
            BluetoothStream::Windows($s) => $body,
        }
    };
}

impl tokio::io::AsyncWrite for BluetoothStream {
    fn poll_write(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
        buf: &[u8],
    ) -> std::task::Poll<std::io::Result<usize>> {
        pin_match!(self, s => {
            // SAFETY: we delegate to inner stream directly
            tokio::io::AsyncWrite::poll_write(std::pin::Pin::new(s), cx, buf)
        })
    }

    fn poll_flush(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<std::io::Result<()>> {
        pin_match!(self, s => {
            tokio::io::AsyncWrite::poll_flush(std::pin::Pin::new(s), cx)
        })
    }

    fn poll_shutdown(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<std::io::Result<()>> {
        pin_match!(self, s => {
            tokio::io::AsyncWrite::poll_shutdown(std::pin::Pin::new(s), cx)
        })
    }
}

impl tokio::io::AsyncRead for BluetoothStream {
    fn poll_read(
        self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
        buf: &mut tokio::io::ReadBuf<'_>,
    ) -> std::task::Poll<std::io::Result<()>> {
        pin_match!(self, s => {
            tokio::io::AsyncRead::poll_read(std::pin::Pin::new(s), cx, buf)
        })
    }
}

impl BluetoothStream {
    /// Used to check to see if the object supports async read, and then use the functionality
    pub fn supports_async_read(&mut self) -> Option<&mut dyn tokio::io::AsyncRead> {
        match self {
            #[cfg(target_os = "linux")]
            BluetoothStream::Bluez(pin) => Some(pin),
            #[cfg(target_os = "android")]
            BluetoothStream::Android(_pin) => None,
            #[cfg(target_os = "windows")]
            BluetoothStream::Windows(_pin) => None,
        }
    }

    /// Used to check to see if the object supports async write, and then use the functionality
    pub fn supports_async_write(&mut self) -> Option<&mut dyn tokio::io::AsyncWrite> {
        match self {
            #[cfg(target_os = "linux")]
            BluetoothStream::Bluez(pin) => Some(pin),
            #[cfg(target_os = "android")]
            BluetoothStream::Android(_pin) => None,
            #[cfg(target_os = "windows")]
            BluetoothStream::Windows(_pin) => None,
        }
    }

    /// Used to try to use synchronous read functionality
    pub fn supports_sync_read(&mut self) -> Option<&mut dyn std::io::Read> {
        match self {
            #[cfg(target_os = "linux")]
            BluetoothStream::Bluez(_pin) => None,
            #[cfg(target_os = "android")]
            BluetoothStream::Android(pin) => Some(pin),
            #[cfg(target_os = "windows")]
            BluetoothStream::Windows(pin) => Some(pin),
        }
    }

    /// Used to try to use synchronous write functionality
    pub fn supports_sync_write(&mut self) -> Option<&mut dyn std::io::Write> {
        match self {
            #[cfg(target_os = "linux")]
            BluetoothStream::Bluez(_pin) => None,
            #[cfg(target_os = "android")]
            BluetoothStream::Android(pin) => Some(pin),
            #[cfg(target_os = "windows")]
            BluetoothStream::Windows(pin) => Some(pin),
        }
    }
}

/// The trait for bluetooth rfcomm objects that can be connected or accepted
#[async_trait::async_trait]
#[enum_dispatch::enum_dispatch]
pub trait BluetoothRfcommConnectableAsyncTrait {
    /// Accept a connection from a bluetooth peer, returns the stream, bluetooth address, and port
    async fn accept(self) -> Result<(BluetoothStream, [u8; 6], u8), String>;
}

/// A bluetooth profile for rfcomm channels
#[enum_dispatch::enum_dispatch(BluetoothRfcommConnectableAsyncTrait)]
pub enum BluetoothRfcommConnectableAsync {
    /// The android object for the profile
    #[cfg(target_os = "android")]
    Android(android::BluetoothRfcommConnectable),
    /// The bluez library in linux is responsible for the profile
    #[cfg(target_os = "linux")]
    Bluez(bluer::rfcomm::ConnectRequest),
    /// Windows RFCOMM connectable
    #[cfg(target_os = "windows")]
    Windows(windows::BluetoothRfcommConnectable),
}

/// The trait for bluetooth rfcomm objects that can be connected or accepted
#[enum_dispatch::enum_dispatch]
pub trait BluetoothRfcommConnectableSyncTrait {
    /// Accept a connection from a bluetooth peer
    fn accept(self, timeout: std::time::Duration)
    -> Result<(BluetoothStream, [u8; 6], u8), String>;
}

/// A bluetooth profile for rfcomm channels
#[enum_dispatch::enum_dispatch(BluetoothRfcommConnectableSyncTrait)]
pub enum BluetoothRfcommConnectableSync {
    /// The android object for the profile
    #[cfg(target_os = "android")]
    Android(android::BluetoothRfcommConnectable),
}

/// The trait for bluetooth rfcomm objects that can be connected or accepted
#[enum_dispatch::enum_dispatch]
pub trait BluetoothL2capConnectableAsyncTrait {
    /// Accept a connection from a bluetooth peer
    async fn accept(self) -> Result<BluetoothStream, String>;
}

/// A bluetooth profile for rfcomm channels
#[enum_dispatch::enum_dispatch(BluetoothL2capConnectableTrait)]
pub enum BluetoothL2capConnectableAsync {
    /// The android object for the profile
    #[cfg(target_os = "android")]
    Android(android::BluetoothRfcommConnectable),
    /// The bluez library in linux is responsible for the profile
    #[cfg(target_os = "linux")]
    Bluez(bluer::rfcomm::ConnectRequest),
}

/// The trait for bluetooth rfcomm objects that can be connected or accepted
#[enum_dispatch::enum_dispatch]
pub trait BluetoothL2capConnectableSyncTrait {
    /// Accept a connection from a bluetooth peer
    fn accept(self, timeout: std::time::Duration) -> Result<BluetoothStream, String>;
}

/// A bluetooth profile for rfcomm channels
#[enum_dispatch::enum_dispatch(BluetoothL2capConnectableSyncTrait)]
pub enum BluetoothL2capConnectableSync {
    /// The android object for the profile
    #[cfg(target_os = "android")]
    Android(android::BluetoothRfcommConnectable),
}

/// Allows building an object to connect to bluetooth devices
#[enum_dispatch::enum_dispatch]
pub trait BluetoothRfcommProfileAsyncTrait {
    /// Get an object in order to accept a connection from or connect to a bluetooth peer
    async fn connectable(&mut self) -> Result<BluetoothRfcommConnectableAsync, String>;
}

/// Allows building an object to connect to bluetooth devices
#[enum_dispatch::enum_dispatch]
pub trait BluetoothRfcommProfileSyncTrait {
    /// Get an object in order to accept a connection from or connect to a bluetooth peer
    fn connectable(&mut self) -> Result<BluetoothRfcommConnectableSync, String>;
}

/// A bluetooth profile for rfcomm channels
#[enum_dispatch::enum_dispatch(BluetoothRfcommProfileAsyncTrait)]
pub enum BluetoothRfcommProfileAsync {
    /// The bluez library in linux is responsible for the profile
    #[cfg(target_os = "linux")]
    Bluez(bluer::rfcomm::ProfileHandle),
    /// Windows RFCOMM profile
    #[cfg(target_os = "windows")]
    Windows(windows::BluetoothRfcommProfile),
    /// A dummy handler
    Dummy(Dummy),
}

/// A bluetooth profile for rfcomm channels
#[enum_dispatch::enum_dispatch(BluetoothRfcommProfileSyncTrait)]
pub enum BluetoothRfcommProfileSync {
    /// Android rfcomm profile
    #[cfg(target_os = "android")]
    Android(android::BluetoothRfcommProfile),
    /// A dummy handler
    Dummy(Dummy),
}

/// A bluetooth profile for rfcomm channels
#[enum_dispatch::enum_dispatch(BluetoothL2capProfileAsyncTrait)]
pub enum BluetoothL2capProfileAsync {
    /// The bluez library in linux is responsible for the profile
    #[cfg(target_os = "linux")]
    Bluez(bluer::rfcomm::ProfileHandle),
    /// A dummy handler
    Dummy(Dummy),
}

/// A bluetooth profile for rfcomm channels
#[enum_dispatch::enum_dispatch(BluetoothL2capProfileSyncTrait)]
pub enum BluetoothL2capProfileSync {
    /// Android rfcomm profile
    #[cfg(target_os = "android")]
    Android(android::BluetoothRfcommProfile),
    /// A dummy handler
    Dummy(Dummy),
}

/// A dummy struct for ensuring enums are not empty
pub struct Dummy {}

impl BluetoothRfcommProfileSyncTrait for Dummy {
    fn connectable(&mut self) -> Result<BluetoothRfcommConnectableSync, String> {
        unimplemented!()
    }
}

impl BluetoothRfcommProfileAsyncTrait for Dummy {
    async fn connectable(&mut self) -> Result<BluetoothRfcommConnectableAsync, String> {
        unimplemented!()
    }
}

/// The common functions for all bluetooth rfcomm sockets
#[enum_dispatch::enum_dispatch]
pub trait BluetoothSocketTrait {
    /// Is the socket connected
    fn is_connected(&self) -> Result<bool, std::io::Error>;
    /// connect the socket
    fn connect(&mut self) -> Result<(), std::io::Error>;
}

impl std::io::Read for BluetoothSocket {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        match self {
            #[cfg(target_os = "android")]
            BluetoothSocket::Android(a) => a.read(buf),
            #[cfg(target_os = "linux")]
            BluetoothSocket::Bluez(b) => b.read(buf),
            #[cfg(target_os = "windows")]
            BluetoothSocket::Windows(w) => w.read(buf),
        }
    }
}

impl std::io::Write for BluetoothSocket {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        match self {
            #[cfg(target_os = "android")]
            BluetoothSocket::Android(a) => a.write(buf),
            #[cfg(target_os = "linux")]
            BluetoothSocket::Bluez(b) => b.write(buf),
            #[cfg(target_os = "windows")]
            BluetoothSocket::Windows(w) => w.write(buf),
        }
    }

    fn flush(&mut self) -> std::io::Result<()> {
        match self {
            #[cfg(target_os = "android")]
            BluetoothSocket::Android(a) => a.flush(),
            #[cfg(target_os = "linux")]
            BluetoothSocket::Bluez(b) => b.flush(),
            #[cfg(target_os = "windows")]
            BluetoothSocket::Windows(w) => w.flush(),
        }
    }
}

/// A bluetooth rfcomm socket
#[enum_dispatch::enum_dispatch(BluetoothSocketTrait)]
pub enum BluetoothSocket {
    /// The android based rfcomm socket
    #[cfg(target_os = "android")]
    Android(android::BluetoothSocket),
    /// Linux using bluez library
    #[cfg(target_os = "linux")]
    Bluez(linux::BluetoothRfcommSocket),
    /// Windows bluetooth socket
    #[cfg(target_os = "windows")]
    Windows(windows::BluetoothRfcommSocket),
}