use std::error::Error;
use std::time::Duration;
use thiserror::Error;
use crate::frame::CanFrame;
#[cfg(feature = "pcan")]
pub mod pcan;
#[cfg(feature = "socketcan")]
pub mod socketcan;
#[derive(Error, Debug)]
pub enum AdapterError {
#[error("Could not open adapter interface")]
OpenFailed,
#[error("Unsupported baud rate")]
UnsupportedBaud,
#[error("Unknown adapter device")]
UnknownDevice,
#[error("Unable to send message")]
WriteFailed,
#[error("Unable to receive message")]
ReadFailed,
#[error("The read operation timed out")]
ReadTimeout,
}
pub type AdapterBaud = u32;
pub trait Adapter {
fn send(&self, frame: &CanFrame) -> Result<(), Box<AdapterError>>;
fn recv(
&self,
timeout: Option<Duration>,
) -> Result<CanFrame, Box<AdapterError>>;
}
pub fn get_adapter(
name: &str,
baud: AdapterBaud,
) -> Result<Box<dyn Adapter>, Box<dyn Error>> {
#[cfg(feature = "pcan")]
return Ok(Box::new(pcan::PcanAdapter::new(name, baud)?));
#[cfg(feature = "socketcan")]
return Ok(Box::new(socketcan::SocketCanAdapter::new(name, baud)?));
#[cfg(not(any(feature = "pcan", feature = "socketcan")))]
Err(Box::new(AdapterError::UnknownDevice))
}