host_can/adapter/
mod.rs

1//! CAN Adapter Interface
2use 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
31/// Adapter baud rate
32pub type AdapterBaud = u32;
33
34/// Base adapter interface (blocking)
35pub trait Adapter {
36    /// Send a CAN frame
37    fn send(&self, frame: &CanFrame) -> Result<(), Box<AdapterError>>;
38
39    /// Receive a CAN frame
40    fn recv(
41        &self,
42        timeout: Option<Duration>,
43    ) -> Result<CanFrame, Box<AdapterError>>;
44}
45
46/// Return a CAN adapter with the given system name and baud-rate
47pub 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}