socketcan_rs/
lib.rs

1mod constants;
2pub use constants::*;
3mod driver;
4pub use driver::*;
5mod frame;
6pub use frame::*;
7mod socket;
8pub use socket::*;
9
10use rs_can::{CanDevice, CanError, CanFilter, CanFrame, CanResult, DeviceBuilder};
11use std::{sync::Arc, time::Duration};
12
13unsafe impl Send for SocketCan {}
14unsafe impl Sync for SocketCan {}
15
16#[async_trait::async_trait]
17impl CanDevice for SocketCan {
18    type Channel = String;
19    type Frame = CanMessage;
20
21    #[inline(always)]
22    fn opened_channels(&self) -> Vec<Self::Channel> {
23        self.sockets.iter()
24            .map(|(c, _)| c.clone())
25            .collect()
26    }
27
28    #[inline(always)]
29    async fn transmit(&self, msg: Self::Frame, timeout: Option<u32>) -> CanResult<(), CanError> {
30        match timeout {
31            Some(timeout) => self.write_timeout(msg, Duration::from_millis(timeout as u64)),
32            None => self.write(msg),
33        }
34    }
35
36    #[inline(always)]
37    async fn receive(&self, channel: Self::Channel, timeout: Option<u32>) -> 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.channel_configs()
60            .iter()
61            .try_for_each(|(chl, cfg)| {
62                let canfd = cfg.get_other::<bool>(CANFD)?
63                    .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}