#[cfg(test)]
mod tests;
use embedded_io::ErrorType;
use crate::transport::common::{NoUsb, Transport, TransportError};
use crate::transport::runtime::Runtime;
use crate::transport::uri::{self, Uri, UsbSelector};
use crate::transport::UsbBackend;
pub type AnyTransport<R, U = NoUsb> = Transport<<R as Runtime>::Tcp, U>;
pub type AnyTransportError<R, U = NoUsb> =
TransportError<<<R as Runtime>::Tcp as ErrorType>::Error, <U as ErrorType>::Error>;
#[derive(Debug)]
#[non_exhaustive]
pub enum ConnectError<E> {
Uri(uri::UriError),
Tcp(std::io::Error),
Usb(E),
UsbBlockingTaskFailed,
}
impl<E: core::fmt::Display> core::fmt::Display for ConnectError<E> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Uri(e) => write!(f, "uri: {e}"),
Self::Tcp(e) => write!(f, "tcp: {e}"),
Self::Usb(e) => write!(f, "usb: {e}"),
Self::UsbBlockingTaskFailed => f.write_str("usb: blocking task failed"),
}
}
}
impl<E> std::error::Error for ConnectError<E>
where
E: std::error::Error + 'static,
{
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Uri(e) => Some(e),
Self::Tcp(e) => Some(e),
Self::Usb(e) => Some(e),
Self::UsbBlockingTaskFailed => None,
}
}
}
pub async fn connect<R, B>(
uri_str: &str,
) -> Result<AnyTransport<R, B::Transport>, ConnectError<B::Error>>
where
R: Runtime,
B: UsbBackend<R>,
B::Transport: Send + 'static,
B::Error: Send + 'static,
{
let uri = uri::parse(uri_str).map_err(ConnectError::Uri)?;
match uri {
Uri::Tcp { host, port } => R::connect_tcp(host, port)
.await
.map(Transport::Tcp)
.map_err(ConnectError::Tcp),
Uri::Usb(selector) => {
let owned = OwnedUsbSelector::from_borrowed(selector);
R::run_blocking(move || B::connect_by_selector(owned.as_borrowed()))
.await
.map_err(|_| ConnectError::UsbBlockingTaskFailed)?
.map(Transport::Usb)
.map_err(ConnectError::Usb)
}
}
}
enum OwnedUsbSelector {
Any,
VidPid { vid: u16, pid: u16 },
Serial(alloc::string::String),
}
impl OwnedUsbSelector {
fn from_borrowed(s: UsbSelector<'_>) -> Self {
match s {
UsbSelector::Any => Self::Any,
UsbSelector::VidPid { vid, pid } => Self::VidPid { vid, pid },
UsbSelector::Serial(s) => Self::Serial(s.into()),
}
}
fn as_borrowed(&self) -> UsbSelector<'_> {
match self {
Self::Any => UsbSelector::Any,
Self::VidPid { vid, pid } => UsbSelector::VidPid {
vid: *vid,
pid: *pid,
},
Self::Serial(s) => UsbSelector::Serial(s),
}
}
}