extern crate std;
use std::{fmt, io};
use socketcan::{CanAnyFrame, CanFdSocket, CanFrame, Socket};
use crate::{
AttemptError, BeginSendError, Driver, IngestResult, OperationId,
protocol::{FrameRef, compat::socketcan::FromSocketcanError},
};
#[derive(Debug)]
pub struct SocketCan {
socket: CanFdSocket,
}
impl SocketCan {
pub fn open(interface: &str) -> io::Result<Self> {
Self::from_socket(CanFdSocket::open(interface)?)
}
pub fn from_socket(socket: CanFdSocket) -> io::Result<Self> {
socket.set_nonblocking(true)?;
Ok(Self { socket })
}
pub fn socket(&self) -> &CanFdSocket {
&self.socket
}
pub fn send<F>(
&self,
driver: &mut Driver,
id: OperationId,
mut now_ms: F,
) -> Result<(), SocketCanSendError>
where
F: FnMut() -> u64,
{
let attempt = driver
.begin_send(id, now_ms())
.map_err(SocketCanSendError::Begin)?;
let frame: CanFrame = attempt.frame().into();
match self.socket.write_frame(&frame) {
Ok(()) => attempt
.submitted(now_ms())
.map_err(SocketCanSendError::Attempt),
Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
attempt
.would_block(now_ms())
.map_err(SocketCanSendError::Attempt)?;
Err(SocketCanSendError::Io(error))
}
Err(error) => Err(SocketCanSendError::Io(error)),
}
}
pub fn receive(
&self,
driver: &mut Driver,
timestamp_ms: impl FnOnce() -> u64,
) -> io::Result<SocketCanReceive> {
let frame = self.socket.read_frame()?;
Ok(receive_frame(driver, frame, timestamp_ms()))
}
}
#[derive(Debug)]
pub enum SocketCanSendError {
Begin(BeginSendError),
Attempt(AttemptError),
Io(io::Error),
}
impl fmt::Display for SocketCanSendError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Begin(error) => write!(formatter, "cannot begin SocketCAN send: {error:?}"),
Self::Attempt(error) => write!(formatter, "cannot record SocketCAN send: {error:?}"),
Self::Io(error) => write!(formatter, "SocketCAN write failed: {error}"),
}
}
}
impl std::error::Error for SocketCanSendError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io(error) => Some(error),
Self::Begin(_) | Self::Attempt(_) => None,
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct SocketCanReceive {
pub frame: CanAnyFrame,
pub classification: Result<IngestResult, FromSocketcanError>,
}
pub fn receive_frame(
driver: &mut Driver,
frame: CanAnyFrame,
received_at_ms: u64,
) -> SocketCanReceive {
let classification = FrameRef::try_from(&frame)
.map(|protocol_frame| driver.ingest(protocol_frame, received_at_ms));
SocketCanReceive {
frame,
classification,
}
}