Skip to main content

rns_net/
serial.rs

1//! Serial port abstraction using libc termios.
2//!
3//! Provides raw serial I/O without external crate dependencies.
4
5use std::io;
6use std::os::unix::io::{AsRawFd, FromRawFd, RawFd};
7
8/// Serial port parity setting.
9#[derive(Debug, Clone, Copy, PartialEq)]
10pub enum Parity {
11    None,
12    Even,
13    Odd,
14}
15
16/// Configuration for a serial port.
17#[derive(Debug, Clone)]
18pub struct SerialConfig {
19    pub path: String,
20    pub baud: u32,
21    pub data_bits: u8,
22    pub parity: Parity,
23    pub stop_bits: u8,
24}
25
26impl Default for SerialConfig {
27    fn default() -> Self {
28        SerialConfig {
29            path: String::new(),
30            baud: 9600,
31            data_bits: 8,
32            parity: Parity::None,
33            stop_bits: 1,
34        }
35    }
36}
37
38/// A serial port backed by a file descriptor.
39pub struct SerialPort {
40    fd: RawFd,
41}
42
43impl SerialPort {
44    /// Open and configure a serial port.
45    pub fn open(config: &SerialConfig) -> io::Result<Self> {
46        let c_path = std::ffi::CString::new(config.path.as_str())
47            .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "invalid path"))?;
48
49        let fd = unsafe {
50            libc::open(
51                c_path.as_ptr(),
52                libc::O_RDWR | libc::O_NOCTTY | libc::O_NONBLOCK,
53            )
54        };
55        if fd < 0 {
56            return Err(io::Error::last_os_error());
57        }
58
59        // Configure termios
60        let mut termios: libc::termios = unsafe { std::mem::zeroed() };
61        if unsafe { libc::tcgetattr(fd, &mut termios) } != 0 {
62            unsafe { libc::close(fd) };
63            return Err(io::Error::last_os_error());
64        }
65
66        // cfmakeraw equivalent
67        termios.c_iflag &= !(libc::IGNBRK
68            | libc::BRKINT
69            | libc::PARMRK
70            | libc::ISTRIP
71            | libc::INLCR
72            | libc::IGNCR
73            | libc::ICRNL
74            | libc::IXON);
75        termios.c_oflag &= !libc::OPOST;
76        termios.c_lflag &= !(libc::ECHO | libc::ECHONL | libc::ICANON | libc::ISIG | libc::IEXTEN);
77        termios.c_cflag &= !(libc::CSIZE | libc::PARENB);
78        termios.c_cflag |= libc::CS8;
79
80        // Data bits
81        termios.c_cflag &= !libc::CSIZE;
82        termios.c_cflag |= match config.data_bits {
83            5 => libc::CS5,
84            6 => libc::CS6,
85            7 => libc::CS7,
86            _ => libc::CS8,
87        };
88
89        // Parity
90        match config.parity {
91            Parity::None => {
92                termios.c_cflag &= !libc::PARENB;
93            }
94            Parity::Even => {
95                termios.c_cflag |= libc::PARENB;
96                termios.c_cflag &= !libc::PARODD;
97            }
98            Parity::Odd => {
99                termios.c_cflag |= libc::PARENB;
100                termios.c_cflag |= libc::PARODD;
101            }
102        }
103
104        // Stop bits
105        if config.stop_bits == 2 {
106            termios.c_cflag |= libc::CSTOPB;
107        } else {
108            termios.c_cflag &= !libc::CSTOPB;
109        }
110
111        // Disable flow control
112        termios.c_cflag |= libc::CLOCAL | libc::CREAD;
113        termios.c_iflag &= !(libc::IXON | libc::IXOFF | libc::IXANY);
114        termios.c_cflag &= !libc::CRTSCTS;
115
116        // Baud rate
117        let speed = baud_to_speed(config.baud)?;
118        unsafe {
119            libc::cfsetispeed(&mut termios, speed);
120            libc::cfsetospeed(&mut termios, speed);
121        }
122
123        // Blocking read with VMIN=1, VTIME=0
124        termios.c_cc[libc::VMIN] = 1;
125        termios.c_cc[libc::VTIME] = 0;
126
127        if unsafe { libc::tcsetattr(fd, libc::TCSANOW, &termios) } != 0 {
128            unsafe { libc::close(fd) };
129            return Err(io::Error::last_os_error());
130        }
131
132        // Clear O_NONBLOCK for blocking reads
133        let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
134        if flags < 0 {
135            unsafe { libc::close(fd) };
136            return Err(io::Error::last_os_error());
137        }
138        if unsafe { libc::fcntl(fd, libc::F_SETFL, flags & !libc::O_NONBLOCK) } < 0 {
139            unsafe { libc::close(fd) };
140            return Err(io::Error::last_os_error());
141        }
142
143        Ok(SerialPort { fd })
144    }
145
146    /// Get the raw fd.
147    pub fn as_raw_fd(&self) -> RawFd {
148        self.fd
149    }
150
151    /// Get a Read handle (File wrapping a dup'd fd).
152    pub fn reader(&self) -> io::Result<std::fs::File> {
153        let new_fd = unsafe { libc::dup(self.fd) };
154        if new_fd < 0 {
155            return Err(io::Error::last_os_error());
156        }
157        Ok(unsafe { std::fs::File::from_raw_fd(new_fd) })
158    }
159
160    /// Get a Write handle (File wrapping a dup'd fd).
161    pub fn writer(&self) -> io::Result<std::fs::File> {
162        let new_fd = unsafe { libc::dup(self.fd) };
163        if new_fd < 0 {
164            return Err(io::Error::last_os_error());
165        }
166        Ok(unsafe { std::fs::File::from_raw_fd(new_fd) })
167    }
168}
169
170impl AsRawFd for SerialPort {
171    fn as_raw_fd(&self) -> RawFd {
172        self.fd
173    }
174}
175
176impl Drop for SerialPort {
177    fn drop(&mut self) {
178        unsafe {
179            libc::close(self.fd);
180        }
181    }
182}
183
184/// Map baud rate u32 to libc speed_t constant.
185fn baud_to_speed(baud: u32) -> io::Result<libc::speed_t> {
186    match baud {
187        0 => Ok(libc::B0),
188        50 => Ok(libc::B50),
189        75 => Ok(libc::B75),
190        110 => Ok(libc::B110),
191        134 => Ok(libc::B134),
192        150 => Ok(libc::B150),
193        200 => Ok(libc::B200),
194        300 => Ok(libc::B300),
195        600 => Ok(libc::B600),
196        1200 => Ok(libc::B1200),
197        1800 => Ok(libc::B1800),
198        2400 => Ok(libc::B2400),
199        4800 => Ok(libc::B4800),
200        9600 => Ok(libc::B9600),
201        19200 => Ok(libc::B19200),
202        38400 => Ok(libc::B38400),
203        57600 => Ok(libc::B57600),
204        115200 => Ok(libc::B115200),
205        230400 => Ok(libc::B230400),
206        460800 => Ok(libc::B460800),
207        500000 => Ok(libc::B500000),
208        576000 => Ok(libc::B576000),
209        921600 => Ok(libc::B921600),
210        1000000 => Ok(libc::B1000000),
211        1152000 => Ok(libc::B1152000),
212        1500000 => Ok(libc::B1500000),
213        2000000 => Ok(libc::B2000000),
214        2500000 => Ok(libc::B2500000),
215        3000000 => Ok(libc::B3000000),
216        3500000 => Ok(libc::B3500000),
217        4000000 => Ok(libc::B4000000),
218        _ => Err(io::Error::new(
219            io::ErrorKind::InvalidInput,
220            format!("unsupported baud rate: {}", baud),
221        )),
222    }
223}
224
225/// Create a pseudo-terminal pair for testing. Returns (master_fd, slave_fd).
226///
227/// The master and slave are configured for raw mode to avoid terminal processing.
228#[cfg(test)]
229pub fn open_pty_pair() -> io::Result<(RawFd, RawFd)> {
230    let mut master: RawFd = -1;
231    let mut slave: RawFd = -1;
232    let ret = unsafe {
233        libc::openpty(
234            &mut master,
235            &mut slave,
236            std::ptr::null_mut(),
237            std::ptr::null_mut(),
238            std::ptr::null_mut(),
239        )
240    };
241    if ret != 0 {
242        return Err(io::Error::last_os_error());
243    }
244
245    // Set both sides to raw mode to avoid terminal character processing
246    for fd in [master, slave] {
247        let mut termios: libc::termios = unsafe { std::mem::zeroed() };
248        unsafe { libc::tcgetattr(fd, &mut termios) };
249        // cfmakeraw equivalent
250        termios.c_iflag &= !(libc::IGNBRK
251            | libc::BRKINT
252            | libc::PARMRK
253            | libc::ISTRIP
254            | libc::INLCR
255            | libc::IGNCR
256            | libc::ICRNL
257            | libc::IXON);
258        termios.c_oflag &= !libc::OPOST;
259        termios.c_lflag &= !(libc::ECHO | libc::ECHONL | libc::ICANON | libc::ISIG | libc::IEXTEN);
260        termios.c_cflag &= !(libc::CSIZE | libc::PARENB);
261        termios.c_cflag |= libc::CS8;
262        termios.c_cc[libc::VMIN] = 1;
263        termios.c_cc[libc::VTIME] = 0;
264        unsafe { libc::tcsetattr(fd, libc::TCSANOW, &termios) };
265    }
266
267    Ok((master, slave))
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273    use std::io::{Read, Write};
274
275    #[test]
276    fn open_pty_pair_works() {
277        let (master, slave) = open_pty_pair().unwrap();
278        assert!(master >= 0);
279        assert!(slave >= 0);
280        unsafe {
281            libc::close(master);
282            libc::close(slave);
283        }
284    }
285
286    #[test]
287    fn write_read_roundtrip() {
288        let (master, slave) = open_pty_pair().unwrap();
289
290        let mut master_file = unsafe { std::fs::File::from_raw_fd(master) };
291        let mut slave_file = unsafe { std::fs::File::from_raw_fd(slave) };
292
293        let data = b"hello serial";
294        master_file.write_all(data).unwrap();
295        master_file.flush().unwrap();
296
297        // Poll with timeout to avoid blocking forever
298        let mut pfd = libc::pollfd {
299            fd: slave,
300            events: libc::POLLIN,
301            revents: 0,
302        };
303        let ret = unsafe { libc::poll(&mut pfd, 1, 2000) };
304        assert!(ret > 0, "should have data available on slave");
305
306        let mut buf = [0u8; 64];
307        let n = slave_file.read(&mut buf).unwrap();
308        assert_eq!(&buf[..n], data);
309    }
310
311    #[test]
312    fn config_baud_rates() {
313        // Verify common baud rates map successfully
314        for &baud in &[9600, 19200, 38400, 57600, 115200, 230400, 460800, 921600] {
315            let speed = baud_to_speed(baud);
316            assert!(speed.is_ok(), "baud {} should be supported", baud);
317        }
318    }
319
320    #[test]
321    fn invalid_path_fails() {
322        let config = SerialConfig {
323            path: "/dev/nonexistent_serial_port_xyz".into(),
324            ..Default::default()
325        };
326        let result = SerialPort::open(&config);
327        assert!(result.is_err());
328    }
329}