1use std::error::Error;
3use std::time::Duration;
4
5use thiserror::Error;
6
7use crate::frame::CanFrame;
8
9#[cfg(feature = "pcan")]
10pub mod pcan;
11
12#[cfg(feature = "socketcan")]
13pub mod socketcan;
14
15#[derive(Error, Debug)]
16pub enum AdapterError {
17 #[error("Could not open adapter interface")]
18 OpenFailed,
19 #[error("Unsupported baud rate")]
20 UnsupportedBaud,
21 #[error("Unknown adapter device")]
22 UnknownDevice,
23 #[error("Unable to send message")]
24 WriteFailed,
25 #[error("Unable to receive message")]
26 ReadFailed,
27 #[error("The read operation timed out")]
28 ReadTimeout,
29}
30
31pub type AdapterBaud = u32;
33
34pub trait Adapter {
36 fn send(&self, frame: &CanFrame) -> Result<(), Box<AdapterError>>;
38
39 fn recv(
41 &self,
42 timeout: Option<Duration>,
43 ) -> Result<CanFrame, Box<AdapterError>>;
44}
45
46pub fn get_adapter(
48 name: &str,
49 baud: AdapterBaud,
50) -> Result<Box<dyn Adapter>, Box<dyn Error>> {
51 #[cfg(feature = "pcan")]
52 return Ok(Box::new(pcan::PcanAdapter::new(name, baud)?));
53
54 #[cfg(feature = "socketcan")]
55 return Ok(Box::new(socketcan::SocketCanAdapter::new(name, baud)?));
56
57 #[cfg(not(any(feature = "pcan", feature = "socketcan")))]
58 Err(Box::new(AdapterError::UnknownDevice))
59}