1use std::io;
6use std::os::unix::io::{AsRawFd, FromRawFd, RawFd};
7
8#[derive(Debug, Clone, Copy, PartialEq)]
10pub enum Parity {
11 None,
12 Even,
13 Odd,
14}
15
16#[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
38pub struct SerialPort {
40 fd: RawFd,
41}
42
43impl SerialPort {
44 pub fn from_raw_fd(fd: RawFd) -> Self {
47 SerialPort { fd }
48 }
49
50 pub fn open(config: &SerialConfig) -> io::Result<Self> {
52 let c_path = std::ffi::CString::new(config.path.as_str())
53 .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "invalid path"))?;
54
55 let fd = unsafe {
56 libc::open(
57 c_path.as_ptr(),
58 libc::O_RDWR | libc::O_NOCTTY | libc::O_NONBLOCK,
59 )
60 };
61 if fd < 0 {
62 return Err(io::Error::last_os_error());
63 }
64
65 let mut termios: libc::termios = unsafe { std::mem::zeroed() };
67 if unsafe { libc::tcgetattr(fd, &mut termios) } != 0 {
68 unsafe { libc::close(fd) };
69 return Err(io::Error::last_os_error());
70 }
71
72 termios.c_iflag &= !(libc::IGNBRK
74 | libc::BRKINT
75 | libc::PARMRK
76 | libc::ISTRIP
77 | libc::INLCR
78 | libc::IGNCR
79 | libc::ICRNL
80 | libc::IXON);
81 termios.c_oflag &= !libc::OPOST;
82 termios.c_lflag &= !(libc::ECHO | libc::ECHONL | libc::ICANON | libc::ISIG | libc::IEXTEN);
83 termios.c_cflag &= !(libc::CSIZE | libc::PARENB);
84 termios.c_cflag |= libc::CS8;
85
86 termios.c_cflag &= !libc::CSIZE;
88 termios.c_cflag |= match config.data_bits {
89 5 => libc::CS5,
90 6 => libc::CS6,
91 7 => libc::CS7,
92 _ => libc::CS8,
93 };
94
95 match config.parity {
97 Parity::None => {
98 termios.c_cflag &= !libc::PARENB;
99 }
100 Parity::Even => {
101 termios.c_cflag |= libc::PARENB;
102 termios.c_cflag &= !libc::PARODD;
103 }
104 Parity::Odd => {
105 termios.c_cflag |= libc::PARENB;
106 termios.c_cflag |= libc::PARODD;
107 }
108 }
109
110 if config.stop_bits == 2 {
112 termios.c_cflag |= libc::CSTOPB;
113 } else {
114 termios.c_cflag &= !libc::CSTOPB;
115 }
116
117 termios.c_cflag |= libc::CLOCAL | libc::CREAD;
120 termios.c_cflag &= !(libc::CRTSCTS | libc::HUPCL);
121 termios.c_iflag &= !(libc::IXON | libc::IXOFF | libc::IXANY);
122
123 let speed = baud_to_speed(config.baud)?;
125 unsafe {
126 libc::cfsetispeed(&mut termios, speed);
127 libc::cfsetospeed(&mut termios, speed);
128 }
129
130 termios.c_cc[libc::VMIN] = 1;
132 termios.c_cc[libc::VTIME] = 0;
133
134 if unsafe { libc::tcsetattr(fd, libc::TCSANOW, &termios) } != 0 {
135 unsafe { libc::close(fd) };
136 return Err(io::Error::last_os_error());
137 }
138
139 let flags = unsafe { libc::fcntl(fd, libc::F_GETFL) };
141 if flags < 0 {
142 unsafe { libc::close(fd) };
143 return Err(io::Error::last_os_error());
144 }
145 if unsafe { libc::fcntl(fd, libc::F_SETFL, flags & !libc::O_NONBLOCK) } < 0 {
146 unsafe { libc::close(fd) };
147 return Err(io::Error::last_os_error());
148 }
149
150 Ok(SerialPort { fd })
151 }
152
153 pub fn as_raw_fd(&self) -> RawFd {
155 self.fd
156 }
157
158 pub fn reader(&self) -> io::Result<std::fs::File> {
160 let new_fd = unsafe { libc::dup(self.fd) };
161 if new_fd < 0 {
162 return Err(io::Error::last_os_error());
163 }
164 Ok(unsafe { std::fs::File::from_raw_fd(new_fd) })
165 }
166
167 pub fn writer(&self) -> io::Result<std::fs::File> {
169 let new_fd = unsafe { libc::dup(self.fd) };
170 if new_fd < 0 {
171 return Err(io::Error::last_os_error());
172 }
173 Ok(unsafe { std::fs::File::from_raw_fd(new_fd) })
174 }
175}
176
177impl AsRawFd for SerialPort {
178 fn as_raw_fd(&self) -> RawFd {
179 self.fd
180 }
181}
182
183impl Drop for SerialPort {
184 fn drop(&mut self) {
185 unsafe {
186 libc::close(self.fd);
187 }
188 }
189}
190
191fn baud_to_speed(baud: u32) -> io::Result<libc::speed_t> {
193 match baud {
194 0 => Ok(libc::B0),
195 50 => Ok(libc::B50),
196 75 => Ok(libc::B75),
197 110 => Ok(libc::B110),
198 134 => Ok(libc::B134),
199 150 => Ok(libc::B150),
200 200 => Ok(libc::B200),
201 300 => Ok(libc::B300),
202 600 => Ok(libc::B600),
203 1200 => Ok(libc::B1200),
204 1800 => Ok(libc::B1800),
205 2400 => Ok(libc::B2400),
206 4800 => Ok(libc::B4800),
207 9600 => Ok(libc::B9600),
208 19200 => Ok(libc::B19200),
209 38400 => Ok(libc::B38400),
210 57600 => Ok(libc::B57600),
211 115200 => Ok(libc::B115200),
212 230400 => Ok(libc::B230400),
213 460800 => Ok(libc::B460800),
214 500000 => Ok(libc::B500000),
215 576000 => Ok(libc::B576000),
216 921600 => Ok(libc::B921600),
217 1000000 => Ok(libc::B1000000),
218 1152000 => Ok(libc::B1152000),
219 1500000 => Ok(libc::B1500000),
220 2000000 => Ok(libc::B2000000),
221 2500000 => Ok(libc::B2500000),
222 3000000 => Ok(libc::B3000000),
223 3500000 => Ok(libc::B3500000),
224 4000000 => Ok(libc::B4000000),
225 _ => Err(io::Error::new(
226 io::ErrorKind::InvalidInput,
227 format!("unsupported baud rate: {}", baud),
228 )),
229 }
230}
231
232#[cfg(test)]
236pub fn open_pty_pair() -> io::Result<(RawFd, RawFd)> {
237 let mut master: RawFd = -1;
238 let mut slave: RawFd = -1;
239 let ret = unsafe {
240 libc::openpty(
241 &mut master,
242 &mut slave,
243 std::ptr::null_mut(),
244 std::ptr::null_mut(),
245 std::ptr::null_mut(),
246 )
247 };
248 if ret != 0 {
249 return Err(io::Error::last_os_error());
250 }
251
252 for fd in [master, slave] {
254 let mut termios: libc::termios = unsafe { std::mem::zeroed() };
255 unsafe { libc::tcgetattr(fd, &mut termios) };
256 termios.c_iflag &= !(libc::IGNBRK
258 | libc::BRKINT
259 | libc::PARMRK
260 | libc::ISTRIP
261 | libc::INLCR
262 | libc::IGNCR
263 | libc::ICRNL
264 | libc::IXON);
265 termios.c_oflag &= !libc::OPOST;
266 termios.c_lflag &= !(libc::ECHO | libc::ECHONL | libc::ICANON | libc::ISIG | libc::IEXTEN);
267 termios.c_cflag &= !(libc::CSIZE | libc::PARENB);
268 termios.c_cflag |= libc::CS8;
269 termios.c_cc[libc::VMIN] = 1;
270 termios.c_cc[libc::VTIME] = 0;
271 unsafe { libc::tcsetattr(fd, libc::TCSANOW, &termios) };
272 }
273
274 Ok((master, slave))
275}
276
277#[cfg(test)]
278mod tests {
279 use super::*;
280 use std::io::{Read, Write};
281
282 #[test]
283 fn open_pty_pair_works() {
284 let (master, slave) = open_pty_pair().unwrap();
285 assert!(master >= 0);
286 assert!(slave >= 0);
287 unsafe {
288 libc::close(master);
289 libc::close(slave);
290 }
291 }
292
293 #[test]
294 fn write_read_roundtrip() {
295 let (master, slave) = open_pty_pair().unwrap();
296
297 let mut master_file = unsafe { std::fs::File::from_raw_fd(master) };
298 let mut slave_file = unsafe { std::fs::File::from_raw_fd(slave) };
299
300 let data = b"hello serial";
301 master_file.write_all(data).unwrap();
302 master_file.flush().unwrap();
303
304 let mut pfd = libc::pollfd {
306 fd: slave,
307 events: libc::POLLIN,
308 revents: 0,
309 };
310 let ret = unsafe { libc::poll(&mut pfd, 1, 2000) };
311 assert!(ret > 0, "should have data available on slave");
312
313 let mut buf = [0u8; 64];
314 let n = slave_file.read(&mut buf).unwrap();
315 assert_eq!(&buf[..n], data);
316 }
317
318 #[test]
319 fn config_baud_rates() {
320 for &baud in &[9600, 19200, 38400, 57600, 115200, 230400, 460800, 921600] {
322 let speed = baud_to_speed(baud);
323 assert!(speed.is_ok(), "baud {} should be supported", baud);
324 }
325 }
326
327 #[test]
328 fn from_raw_fd_works() {
329 let (master, slave) = open_pty_pair().unwrap();
330
331 let port = SerialPort::from_raw_fd(slave);
332 let mut writer = port.writer().unwrap();
333 let mut reader_file = unsafe { std::fs::File::from_raw_fd(master) };
334
335 let data = b"from_raw_fd test";
336 writer.write_all(data).unwrap();
337 writer.flush().unwrap();
338
339 let mut pfd = libc::pollfd {
340 fd: master,
341 events: libc::POLLIN,
342 revents: 0,
343 };
344 let ret = unsafe { libc::poll(&mut pfd, 1, 2000) };
345 assert!(ret > 0, "should have data available");
346
347 let mut buf = [0u8; 64];
348 let n = reader_file.read(&mut buf).unwrap();
349 assert_eq!(&buf[..n], data);
350 }
351
352 #[test]
353 fn invalid_path_fails() {
354 let config = SerialConfig {
355 path: "/dev/nonexistent_serial_port_xyz".into(),
356 ..Default::default()
357 };
358 let result = SerialPort::open(&config);
359 assert!(result.is_err());
360 }
361}