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
//! Bluetooth RFCOMM transport.

use async_trait::async_trait;
use bluer::rfcomm::{Listener, Socket, SocketAddr};
use futures::future;
use std::{
    any::Any,
    cmp::Ordering,
    collections::HashSet,
    fmt,
    hash::{Hash, Hasher},
    io::Result,
};
use tokio::sync::{mpsc, watch};

use super::{AcceptedIoBox, AcceptingTransport, ConnectingTransport, IoBox, LinkTag, LinkTagBox};
use aggligator::control::Direction;

static NAME: &str = "rfcomm";

/// Link tag for Bluetooth RFCOMM link.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RfcommLinkTag {
    /// Local RFCOMM address.
    pub local: SocketAddr,
    /// Remote RFCOMM address.
    pub remote: SocketAddr,
    /// Link direction.
    pub direction: Direction,
}

impl fmt::Display for RfcommLinkTag {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let dir = match self.direction {
            Direction::Incoming => "<-",
            Direction::Outgoing => "->",
        };
        write!(f, "{} {dir} {}", self.local, self.remote)
    }
}

impl RfcommLinkTag {
    /// Creates a new link tag for a Bluetooth RFCOMM link.
    pub fn new(local: SocketAddr, remote: SocketAddr, direction: Direction) -> Self {
        Self { local, remote, direction }
    }
}

impl LinkTag for RfcommLinkTag {
    fn transport_name(&self) -> &str {
        NAME
    }

    fn direction(&self) -> Direction {
        self.direction
    }

    fn user_data(&self) -> Vec<u8> {
        Vec::new()
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn box_clone(&self) -> LinkTagBox {
        Box::new(self.clone())
    }

    fn dyn_cmp(&self, other: &dyn LinkTag) -> Ordering {
        let other = other.as_any().downcast_ref::<Self>().unwrap();
        Ord::cmp(self, other)
    }

    fn dyn_hash(&self, mut state: &mut dyn Hasher) {
        Hash::hash(self, &mut state)
    }
}

/// Bluetooth RFCOMM transport for outgoing connections.
#[derive(Debug, Clone)]
pub struct RfcommConnector {
    local: SocketAddr,
    remote: SocketAddr,
}

impl RfcommConnector {
    /// Creates a new Bluetooth RFCOMM transport for RFCOMM connections.
    ///
    /// The transport establishes one connection to the specified RFCOMM socket address.
    pub fn new(remote: SocketAddr) -> Self {
        Self { local: SocketAddr::any(), remote }
    }

    /// Binds the outgoing socket to the given local Bluetooth address.
    pub fn bind(&mut self, local: SocketAddr) {
        self.local = local;
    }
}

#[async_trait]
impl ConnectingTransport for RfcommConnector {
    fn name(&self) -> &str {
        NAME
    }

    async fn link_tags(&self, tx: watch::Sender<HashSet<LinkTagBox>>) -> Result<()> {
        let tag = RfcommLinkTag::new(self.local, self.remote, Direction::Outgoing);
        tx.send_replace([Box::new(tag) as Box<dyn LinkTag>].into_iter().collect());
        future::pending().await
    }

    async fn connect(&self, tag: &dyn LinkTag) -> Result<IoBox> {
        let tag: &RfcommLinkTag = tag.as_any().downcast_ref().unwrap();

        let socket = Socket::new()?;
        socket.bind(tag.local)?;
        let stream = socket.connect(tag.remote).await?;

        let (rh, wh) = stream.into_split();
        Ok(IoBox::new(rh, wh))
    }
}

/// Bluetooth RFCOMM transport for incoming connection.
#[derive(Debug)]
pub struct RfcommAcceptor {
    listener: Listener,
}

impl RfcommAcceptor {
    /// Creates a new Bluetooth RFCOMM transport for incoming connections.
    ///
    /// It listens on the specified RFCOMM socket address.
    pub async fn new(addr: SocketAddr) -> Result<Self> {
        let listener = Listener::bind(addr).await?;
        Ok(Self { listener })
    }

    /// The local RFCOMM socket address used for listening.
    pub fn address(&self) -> Result<SocketAddr> {
        self.listener.as_ref().local_addr()
    }
}

#[async_trait]
impl AcceptingTransport for RfcommAcceptor {
    fn name(&self) -> &str {
        NAME
    }

    async fn listen(&self, tx: mpsc::Sender<AcceptedIoBox>) -> Result<()> {
        loop {
            let (socket, remote) = self.listener.accept().await?;
            let local = socket.as_ref().local_addr()?;

            tracing::debug!("Accepted RFCOMM connection from {remote} on {local}");
            let tag = RfcommLinkTag::new(local, remote, Direction::Incoming);

            let (rh, wh) = socket.into_split();
            let _ = tx.send(AcceptedIoBox::new(rh, wh, tag)).await;
        }
    }
}