Skip to main content

socketcan_rs/
lib.rs

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