extern crate std;
use std::{fmt, io};
use socketcan::{CanAnyFrame, CanFdSocket, CanFrame, CanTimestamps, Socket};
use crate::{
AttemptError, Driver, IngestResult, Instant, TxAttempt as CoreTxAttempt, TxCompletion,
TxOutcome,
protocol::{FrameRef, compat::socketcan::FromSocketcanError},
};
#[derive(Debug)]
pub struct CanTx {
socket: CanFdSocket,
}
impl CanTx {
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 into_socket(self) -> CanFdSocket {
self.socket
}
pub const fn attempt<'tx, 's>(&'tx self, attempt: CoreTxAttempt<'s>) -> TxAttempt<'tx, 's> {
TxAttempt {
tx: self,
attempt: Some(attempt),
}
}
}
#[derive(Debug)]
pub struct CanRx {
socket: CanFdSocket,
}
impl CanRx {
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 into_socket(self) -> CanFdSocket {
self.socket
}
pub fn receive(
&self,
driver: &mut Driver<'_>,
received_at: impl FnOnce(&CanTimestamps) -> Instant,
) -> io::Result<CanRxFrame> {
let (frame, timestamps) = self.socket.read_frame_with_timestamps()?;
let received_at = received_at(×tamps);
Ok(receive_frame(driver, frame, timestamps, received_at))
}
}
#[must_use]
pub struct TxAttempt<'tx, 's> {
tx: &'tx CanTx,
attempt: Option<CoreTxAttempt<'s>>,
}
impl<'tx, 's> TxAttempt<'tx, 's> {
pub fn id(&self) -> crate::OperationId<'s> {
match &self.attempt {
Some(attempt) => attempt.id(),
None => panic!("SocketCAN TX attempt was already consumed"),
}
}
pub fn poll(
&mut self,
driver: &mut Driver<'s>,
mut now: impl FnMut() -> Instant,
) -> Result<TxCompletion<'s>, SocketCanTxError> {
let attempt = self.attempt.as_ref().ok_or(SocketCanTxError::Consumed)?;
let authorized_at = now();
let frame = driver
.authorize_tx(attempt, authorized_at)
.map_err(SocketCanTxError::Authorize)?;
let frame: CanFrame = (&frame).into();
let outcome = match self.tx.socket.write_frame(&frame) {
Ok(()) => TxOutcome::Submitted { occurred_at: now() },
Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
TxOutcome::WouldBlock { occurred_at: now() }
}
Err(error) => {
let attempt = self.attempt.take().expect("attempt checked above");
return match driver.abandon_attempt(attempt, now()) {
Ok(()) => Err(SocketCanTxError::Io(error)),
Err(core) => Err(SocketCanTxError::Abandon { io: error, core }),
};
}
};
let attempt = self.attempt.take().expect("attempt checked above");
driver
.finish_tx(attempt, outcome, now())
.map_err(SocketCanTxError::Finish)
}
pub fn cancel_unsubmitted(
mut self,
driver: &mut Driver<'s>,
occurred_at: Instant,
processed_at: Instant,
) -> Result<(), SocketCanTxError> {
let attempt = self.attempt.take().ok_or(SocketCanTxError::Consumed)?;
driver
.cancel_unsubmitted(attempt, occurred_at, processed_at)
.map_err(SocketCanTxError::Cancel)
}
pub fn into_core(mut self) -> Option<CoreTxAttempt<'s>> {
self.attempt.take()
}
pub fn abandon(
mut self,
driver: &mut Driver<'s>,
processed_at: Instant,
) -> Result<crate::OperationId<'s>, SocketCanTxError> {
let attempt = self.attempt.take().ok_or(SocketCanTxError::Consumed)?;
let id = attempt.id();
driver
.abandon_attempt(attempt, processed_at)
.map_err(SocketCanTxError::AbandonCore)?;
Ok(id)
}
}
#[derive(Debug)]
pub enum SocketCanTxError {
Consumed,
Authorize(AttemptError),
Finish(AttemptError),
Io(io::Error),
Abandon {
io: io::Error,
core: AttemptError,
},
Cancel(AttemptError),
AbandonCore(AttemptError),
}
impl fmt::Display for SocketCanTxError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Consumed => formatter.write_str("SocketCAN TX attempt was already consumed"),
Self::Authorize(error) => {
write!(formatter, "SocketCAN TX was not authorized: {error:?}")
}
Self::Finish(error) => {
write!(formatter, "cannot record SocketCAN TX result: {error:?}")
}
Self::Io(error) => write!(formatter, "SocketCAN write has unknown result: {error}"),
Self::Abandon { io, core } => write!(
formatter,
"SocketCAN write has unknown result ({io}); core recovery failed: {core:?}"
),
Self::Cancel(error) => {
write!(formatter, "cannot record SocketCAN cancellation: {error:?}")
}
Self::AbandonCore(error) => {
write!(formatter, "cannot record unknown SocketCAN TX: {error:?}")
}
}
}
}
impl std::error::Error for SocketCanTxError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Io(error) | Self::Abandon { io: error, .. } => Some(error),
Self::Consumed
| Self::Authorize(_)
| Self::Finish(_)
| Self::Cancel(_)
| Self::AbandonCore(_) => None,
}
}
}
#[derive(Debug)]
pub struct CanRxFrame {
pub frame: CanAnyFrame,
pub timestamps: CanTimestamps,
pub received_at: Instant,
pub classification: Result<IngestResult, FromSocketcanError>,
}
pub fn receive_frame(
driver: &mut Driver<'_>,
frame: CanAnyFrame,
timestamps: CanTimestamps,
received_at: Instant,
) -> CanRxFrame {
let classification =
FrameRef::try_from(&frame).map(|protocol_frame| driver.ingest(protocol_frame, received_at));
CanRxFrame {
frame,
timestamps,
received_at,
classification,
}
}