Skip to main content

industrial_protocols_bridge_can/
lib.rs

1// Copyright (c) 2026 erik <erik@erik.xyz> — https://erik.xyz
2//! # CAN 总线传输
3//!
4//! Linux SocketCAN (CAN_RAW) 实现。通过 `libc` 直接操作 CAN 套接字,
5//! 支持 CAN 2.0A(11-bit ID)和 CAN 2.0B(29-bit ID)帧格式。
6//! 非 Linux 平台使用存根实现。
7
8//! CAN bus transport via Linux SocketCAN.
9//!
10//! Uses raw CAN_RAW sockets to send/receive CAN frames.
11//! Requires the `socketcan` feature (Linux only).
12
13use industrial_protocols_kernel::bridge::Transport;
14use std::io;
15
16/// A single CAN frame.
17#[derive(Debug, Clone)]
18pub struct CanFrame {
19    pub id: u32,
20    pub extended: bool,
21    pub data: Vec<u8>,
22}
23
24/// CAN transport using Linux SocketCAN.
25#[cfg(target_os = "linux")]
26pub struct CanTransport {
27    socket: std::os::fd::RawFd,
28}
29
30#[cfg(target_os = "linux")]
31impl CanTransport {
32    /// Open a CAN socket on the given interface.
33    /// Requires CAP_NET_RAW or root.
34    pub fn open(interface: &str) -> io::Result<Self> {
35        // Create CAN_RAW socket
36        let fd = unsafe {
37            libc::socket(
38                libc::PF_CAN,
39                libc::SOCK_RAW | libc::SOCK_CLOEXEC,
40                libc::CAN_RAW,
41            )
42        };
43        if fd < 0 {
44            return Err(io::Error::last_os_error());
45        }
46
47        // Get interface index
48        let ifname = std::ffi::CString::new(interface).map_err(|_| {
49            io::Error::new(
50                io::ErrorKind::InvalidInput,
51                "interface name contains a NUL byte",
52            )
53        })?;
54        let ifindex = unsafe { libc::if_nametoindex(ifname.as_ptr()) };
55        if ifindex == 0 {
56            unsafe { libc::close(fd) };
57            return Err(io::Error::new(
58                io::ErrorKind::NotFound,
59                format!("interface '{}' not found", interface),
60            ));
61        }
62
63        // Bind to interface
64        let mut addr: libc::sockaddr_can = unsafe { std::mem::zeroed() };
65        addr.can_family = libc::AF_CAN as u16;
66        addr.can_ifindex = ifindex as i32;
67
68        let ret = unsafe {
69            libc::bind(
70                fd,
71                &addr as *const _ as *const libc::sockaddr,
72                std::mem::size_of::<libc::sockaddr_can>() as u32,
73            )
74        };
75        if ret < 0 {
76            unsafe { libc::close(fd) };
77            return Err(io::Error::last_os_error());
78        }
79
80        Ok(CanTransport { socket: fd })
81    }
82
83    /// Send a raw CAN frame.
84    pub fn send_frame(&self, id: u32, data: &[u8], extended: bool) -> io::Result<()> {
85        let mut frame: libc::can_frame = unsafe { std::mem::zeroed() };
86        frame.can_id = id;
87        if extended {
88            frame.can_id |= libc::CAN_EFF_FLAG;
89        }
90        frame.can_dlc = data.len().min(8) as u8;
91        unsafe {
92            std::ptr::copy_nonoverlapping(
93                data.as_ptr(),
94                frame.data.as_mut_ptr(),
95                frame.can_dlc as usize,
96            );
97        }
98        let ret = unsafe {
99            libc::write(
100                self.socket,
101                &frame as *const _ as *const libc::c_void,
102                std::mem::size_of::<libc::can_frame>(),
103            )
104        };
105        if ret < 0 {
106            return Err(io::Error::last_os_error());
107        }
108        Ok(())
109    }
110
111    /// Receive a CAN frame.
112    pub fn recv_frame(&self, timeout_ms: u64) -> io::Result<CanFrame> {
113        use std::time::{Duration, Instant};
114        let deadline = Instant::now() + Duration::from_millis(timeout_ms);
115        loop {
116            let remaining = deadline.saturating_duration_since(Instant::now());
117            let _tv = libc::timeval {
118                tv_sec: remaining.as_secs() as libc::time_t,
119                tv_usec: remaining.subsec_micros() as libc::suseconds_t,
120            };
121            let mut fds = libc::pollfd {
122                fd: self.socket,
123                events: libc::POLLIN,
124                revents: 0,
125            };
126            let ret = unsafe { libc::poll(&mut fds, 1, (remaining.as_millis() as i32).min(1000)) };
127            if ret < 0 {
128                return Err(io::Error::last_os_error());
129            }
130            if ret == 0 {
131                return Err(io::Error::new(io::ErrorKind::TimedOut, "CAN recv timeout"));
132            }
133            if fds.revents & libc::POLLIN != 0 {
134                let mut frame: libc::can_frame = unsafe { std::mem::zeroed() };
135                let ret = unsafe {
136                    libc::read(
137                        self.socket,
138                        &mut frame as *mut _ as *mut libc::c_void,
139                        std::mem::size_of::<libc::can_frame>(),
140                    )
141                };
142                if ret >= 0 {
143                    let id = frame.can_id & !libc::CAN_EFF_FLAG;
144                    let extended = frame.can_id & libc::CAN_EFF_FLAG != 0;
145                    let data = frame.data[..frame.can_dlc as usize].to_vec();
146                    return Ok(CanFrame { id, extended, data });
147                }
148            }
149        }
150    }
151}
152
153#[cfg(target_os = "linux")]
154impl Drop for CanTransport {
155    fn drop(&mut self) {
156        if self.socket >= 0 {
157            unsafe { libc::close(self.socket) };
158        }
159    }
160}
161
162#[cfg(target_os = "linux")]
163impl Transport for CanTransport {
164    fn send(&mut self, data: &[u8]) -> io::Result<Vec<u8>> {
165        if data.len() < 4 {
166            return Err(io::Error::new(
167                io::ErrorKind::InvalidInput,
168                "CAN frame too short",
169            ));
170        }
171        let id = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
172        let payload = &data[4..];
173        self.send_frame(id, payload, false)?;
174        match self.recv_frame(1000) {
175            Ok(frame) => Ok(frame.data),
176            Err(_) => Ok(vec![]),
177        }
178    }
179    fn is_open(&self) -> bool {
180        self.socket >= 0
181    }
182    fn close(&mut self) -> io::Result<()> {
183        if self.socket >= 0 {
184            unsafe { libc::close(self.socket) };
185            self.socket = -1;
186        }
187        Ok(())
188    }
189}
190
191/// Stub for non-Linux platforms.
192#[cfg(not(target_os = "linux"))]
193pub struct CanTransport;
194
195#[cfg(not(target_os = "linux"))]
196impl CanTransport {
197    pub fn open(_interface: &str) -> io::Result<Self> {
198        Err(io::Error::new(
199            io::ErrorKind::Unsupported,
200            "SocketCAN only available on Linux",
201        ))
202    }
203}
204
205#[cfg(not(target_os = "linux"))]
206impl Transport for CanTransport {
207    fn send(&mut self, _data: &[u8]) -> io::Result<Vec<u8>> {
208        Err(io::Error::new(
209            io::ErrorKind::Unsupported,
210            "SocketCAN only available on Linux",
211        ))
212    }
213    fn is_open(&self) -> bool {
214        false
215    }
216    fn close(&mut self) -> io::Result<()> {
217        Ok(())
218    }
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224
225    #[test]
226    fn test_can_frame_default() {
227        let frame = CanFrame {
228            id: 0x123,
229            extended: false,
230            data: vec![1, 2, 3],
231        };
232        assert_eq!(frame.id, 0x123);
233        assert!(!frame.extended);
234        assert_eq!(frame.data.len(), 3);
235    }
236
237    #[test]
238    fn test_can_frame_extended_29bit() {
239        let frame = CanFrame {
240            id: 0x1FFFFFFF,
241            extended: true,
242            data: vec![0u8; 8],
243        };
244        assert!(frame.extended);
245        assert_eq!(frame.id, 0x1FFFFFFF);
246        assert_eq!(frame.data.len(), 8);
247    }
248
249    #[test]
250    fn test_can_frame_clone_debug() {
251        let frame = CanFrame {
252            id: 0x55,
253            extended: false,
254            data: vec![1, 2],
255        };
256        let clone = frame.clone();
257        assert_eq!(clone.id, frame.id);
258        assert_eq!(clone.data, frame.data);
259        let _dbg = format!("{frame:?}");
260    }
261
262    #[test]
263    fn test_open_bogus_interface_fails() {
264        // Linux: socket creation or if_nametoindex fails; other platforms:
265        // the stub rejects outright. Either way open must error.
266        assert!(CanTransport::open("definitely_not_an_iface_12345").is_err());
267    }
268
269    #[test]
270    #[cfg(not(target_os = "linux"))]
271    fn test_stub_rejects() {
272        assert!(CanTransport::open("can0").is_err());
273    }
274}