host-can 0.1.5

Host library for CAN adapters
Documentation
//! CAN Adapter Interface
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,
}

/// Adapter baud rate
pub type AdapterBaud = u32;

/// Base adapter interface (blocking)
pub trait Adapter {
    /// Send a CAN frame
    fn send(&self, frame: &CanFrame) -> Result<(), Box<AdapterError>>;

    /// Receive a CAN frame
    fn recv(
        &self,
        timeout: Option<Duration>,
    ) -> Result<CanFrame, Box<AdapterError>>;
}

/// Return a CAN adapter with the given system name and baud-rate
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))
}