1use std::io;
2use std::pin::pin;
3use std::time::Duration;
4
5use bt_hci_transport::{PacketKind, PacketToController, PacketToHost, ReadHciError};
6use futures::future::Either;
7use nusb::io::{EndpointRead, EndpointWrite};
8use nusb::transfer::{Bulk, BulkOrInterrupt, ControlOut, ControlType, Interrupt, Recipient};
9use nusb::{Device, DeviceInfo, Interface};
10use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt};
11use tokio::sync::Mutex;
12
13const USB_CLASS_WIRELESS: u8 = 0xE0;
14const USB_SUBCLASS_BLUETOOTH: u8 = 0x01;
15const USB_PROTOCOL_BLUETOOTH_HCI: u8 = 0x01;
16
17const ENDPOINT_EVENT_IN: u8 = 0x81;
18const ENDPOINT_ACL_IN: u8 = 0x82;
19const ENDPOINT_ACL_OUT: u8 = 0x02;
20
21#[derive(Debug)]
22pub enum Error {
23 ReadHci(ReadHciError<core::convert::Infallible>),
24 UsbTransfer(nusb::transfer::TransferError),
25 Io(io::Error),
26}
27
28impl core::fmt::Display for Error {
29 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30 match self {
31 Self::ReadHci(_) => write!(f, "failed to parse HCI bytes"),
32 Self::UsbTransfer(e) => write!(f, "USB transfer: {e}"),
33 Self::Io(e) => write!(f, "I/O: {e}"),
34 }
35 }
36}
37
38impl core::error::Error for Error {}
39
40impl embedded_io::Error for Error {
41 fn kind(&self) -> embedded_io::ErrorKind {
42 embedded_io::ErrorKind::Other
43 }
44}
45
46impl From<ReadHciError<core::convert::Infallible>> for Error {
47 fn from(e: ReadHciError<core::convert::Infallible>) -> Self {
48 Self::ReadHci(e)
49 }
50}
51
52pub struct Transport {
53 interface: Interface,
54 in_endpoints: Mutex<InEndpoints>,
55 acl_writer: Mutex<EndpointWrite<Bulk>>,
56}
57
58struct InEndpoints {
59 event_reader: EndpointRead<Interrupt>,
60 acl_reader: EndpointRead<Bulk>,
61}
62
63async fn read_packet<R>(reader: &mut EndpointRead<R>, rx: &mut [u8]) -> Result<(), Error>
64where
65 R: BulkOrInterrupt,
66{
67 let mut reader = reader.until_short_packet();
68 match reader.read_exact(rx).await {
69 Ok(_) => {}
70 Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => {
71 }
73 Err(_) => {
74 return Err(Error::Io(io::Error::new(
75 io::ErrorKind::InvalidInput,
76 "buffer too small",
77 )));
78 }
79 }
80 reader.consume_end().unwrap();
81 Ok(())
82}
83
84impl Transport {
85 pub async fn new(dev: Device) -> Result<Self, nusb::Error> {
86 let _ = dev.set_configuration(1).await;
90 let interface = dev.detach_and_claim_interface(0).await?;
91 let event_in = interface.endpoint(ENDPOINT_EVENT_IN)?;
92 let acl_in = interface.endpoint(ENDPOINT_ACL_IN)?;
93 let acl_out = interface.endpoint(ENDPOINT_ACL_OUT)?;
94
95 let event_reader = event_in.reader(16);
97 let acl_reader = acl_in.reader(512);
98 let acl_writer = acl_out.writer(512);
99
100 Ok(Self {
101 interface,
102 in_endpoints: Mutex::new(InEndpoints {
103 event_reader,
104 acl_reader,
105 }),
106 acl_writer: Mutex::new(acl_writer),
107 })
108 }
109}
110
111impl bt_hci_transport::Transport for Transport {
112 async fn read<'a, P: PacketToHost<'a>>(&self, rx: &'a mut [u8]) -> Result<P, Self::Error> {
113 let mut in_endpoints = self.in_endpoints.lock().await;
114 let InEndpoints {
115 event_reader,
116 acl_reader,
117 } = &mut *in_endpoints;
118
119 let event_ready = pin!(event_reader.fill_buf());
120 let acl_ready = pin!(acl_reader.fill_buf());
121
122 let mut tmp = vec![0u8; rx.len()];
123 let kind = match futures::future::select(event_ready, acl_ready).await {
124 Either::Left(_) => {
125 read_packet(event_reader, &mut tmp).await?;
126 PacketKind::Event
127 }
128 Either::Right(_) => {
129 read_packet(acl_reader, &mut tmp).await?;
130 PacketKind::AclData
131 }
132 };
133
134 let mut data = &tmp[..];
135 P::read_hci(kind, &mut data, rx).map_err(Error::ReadHci)
136 }
137
138 async fn write<T: PacketToController>(&self, val: &T) -> Result<(), Self::Error> {
139 let mut buf = Vec::<u8>::new();
140 val.write_hci(&mut buf).unwrap();
141 match T::KIND {
142 PacketKind::Cmd => {
143 let data = ControlOut {
144 control_type: ControlType::Class,
145 recipient: Recipient::Device,
146 request: 0x00,
147 value: 0x00,
148 index: 0x00,
149 data: &buf,
150 };
151 self.interface
152 .control_out(data, Duration::from_secs(5))
153 .await
154 .map_err(Error::UsbTransfer)?;
155 }
156 PacketKind::AclData => {
157 let mut acl_writer = self.acl_writer.lock().await;
158 acl_writer.write_all(&buf).await.map_err(Error::Io)?;
159 acl_writer.submit_end();
160 }
161 _ => {
162 todo!();
163 }
164 }
165
166 Ok(())
167 }
168}
169
170impl embedded_io::ErrorType for Transport {
171 type Error = Error;
172}
173
174pub async fn list_devices() -> Result<impl Iterator<Item = DeviceInfo>, nusb::Error> {
175 Ok(nusb::list_devices().await?.filter(|d| {
176 d.class() == USB_CLASS_WIRELESS
177 && d.subclass() == USB_SUBCLASS_BLUETOOTH
178 && d.protocol() == USB_PROTOCOL_BLUETOOTH_HCI
179 }))
180}