socketcan_rs/
lib.rs

1mod constants;
2mod driver;
3mod frame;
4mod socket;
5
6pub use self::{constants::*, driver::*, frame::*, socket::*};
7
8use rs_can::{CanDevice, CanError, CanFilter, CanFrame, CanResult, DeviceBuilder};
9use std::{sync::Arc, time::Duration};
10
11unsafe impl Send for SocketCan {}
12unsafe impl Sync for SocketCan {}
13
14#[async_trait::async_trait]
15impl CanDevice for SocketCan {
16    type Channel = String;
17    type Frame = CanMessage;
18
19    #[inline(always)]
20    fn opened_channels(&self) -> Vec<Self::Channel> {
21        self.sockets.iter().map(|(c, _)| c.clone()).collect()
22    }
23
24    #[inline(always)]
25    async fn transmit(&self, msg: Self::Frame, timeout: Option<u32>) -> CanResult<(), CanError> {
26        match timeout {
27            Some(timeout) => self.write_timeout(msg, Duration::from_millis(timeout as u64)),
28            None => self.write(msg),
29        }
30    }
31
32    #[inline(always)]
33    async fn receive(
34        &self,
35        channel: Self::Channel,
36        timeout: Option<u32>,
37    ) -> CanResult<Vec<Self::Frame>, CanError> {
38        let timeout = timeout.unwrap_or(0);
39        let mut msg = self.read_timeout(&channel, Duration::from_millis(timeout as u64))?;
40        msg.set_channel(channel);
41        // .set_direct(CanDirect::Receive);
42        Ok(vec![msg])
43    }
44
45    #[inline(always)]
46    fn shutdown(&mut self) {
47        match Arc::get_mut(&mut self.sockets) {
48            Some(s) => s.clear(),
49            None => (),
50        }
51    }
52}
53
54impl TryFrom<DeviceBuilder<String>> for SocketCan {
55    type Error = CanError;
56
57    fn try_from(builder: DeviceBuilder<String>) -> Result<Self, Self::Error> {
58        let mut device = SocketCan::new();
59        builder
60            .channel_configs()
61            .iter()
62            .try_for_each(|(chl, cfg)| {
63                let canfd = cfg.get_other::<bool>(CANFD)?.unwrap_or_default();
64                device.init_channel(chl, canfd)?;
65
66                if let Some(filters) = cfg.get_other::<Vec<CanFilter>>(FILTERS)? {
67                    device.set_filters(chl, &filters)?;
68                }
69
70                if let Some(loopback) = cfg.get_other::<bool>(LOOPBACK)? {
71                    device.set_loopback(chl, loopback)?;
72                }
73
74                if let Some(recv_own_msg) = cfg.get_other::<bool>(RECV_OWN_MSG)? {
75                    device.set_recv_own_msgs(chl, recv_own_msg)?;
76                }
77
78                Ok(())
79            })?;
80
81        Ok(device)
82    }
83}