Skip to main content

industrial_protocols_bridge_serial/
lib.rs

1// Copyright (c) 2026 erik <erik@erik.xyz> — https://erik.xyz
2//! # 串口传输
3//!
4//! 通过 `serialport` crate 实现真实串口通信。
5//! 启用 `serial` feature 后可用(需要系统安装 libudev)。
6//! 未启用时使用存根实现,返回明确的错误提示。
7
8use industrial_protocols_kernel::bridge::Transport;
9use std::io;
10
11#[derive(Debug, Clone)]
12pub struct SerialConfig {
13    pub port: String,
14    pub baud_rate: u32,
15    pub data_bits: u8,
16    pub parity: Parity,
17    pub stop_bits: u8,
18    pub timeout_ms: u64,
19}
20
21#[derive(Debug, Clone, Copy)]
22pub enum Parity {
23    None,
24    Even,
25    Odd,
26}
27
28/// Returns a list of available serial port names on the system.
29/// Requires the `serial` feature.
30#[cfg(feature = "serial")]
31pub fn available_ports() -> Vec<String> {
32    serialport::available_ports()
33        .unwrap_or_default()
34        .into_iter()
35        .map(|p| p.port_name)
36        .collect()
37}
38
39/// Always returns empty list when `serial` feature is not enabled.
40#[cfg(not(feature = "serial"))]
41pub fn available_ports() -> Vec<String> {
42    Vec::new()
43}
44
45/// Real serial transport — requires the `serial` feature.
46#[cfg(feature = "serial")]
47pub struct SerialTransport {
48    port: Box<dyn serialport::SerialPort>,
49}
50
51#[cfg(feature = "serial")]
52impl SerialTransport {
53    pub fn open(config: SerialConfig) -> io::Result<Self> {
54        use serialport::{DataBits, Parity as SpParity, StopBits};
55        use std::time::Duration;
56
57        let parity = match config.parity {
58            Parity::None => SpParity::None,
59            Parity::Even => SpParity::Even,
60            Parity::Odd => SpParity::Odd,
61        };
62        let data_bits = match config.data_bits {
63            5 => DataBits::Five,
64            6 => DataBits::Six,
65            7 => DataBits::Seven,
66            _ => DataBits::Eight,
67        };
68        let stop_bits = match config.stop_bits {
69            1 => StopBits::One,
70            2 => StopBits::Two,
71            _ => StopBits::One,
72        };
73
74        let port = serialport::new(&config.port, config.baud_rate)
75            .parity(parity)
76            .data_bits(data_bits)
77            .stop_bits(stop_bits)
78            .timeout(Duration::from_millis(config.timeout_ms))
79            .open()
80            .map_err(io::Error::other)?;
81
82        Ok(SerialTransport { port })
83    }
84}
85
86#[cfg(feature = "serial")]
87impl Transport for SerialTransport {
88    fn send(&mut self, data: &[u8]) -> io::Result<Vec<u8>> {
89        use std::io::{Read, Write};
90        self.port.write_all(data)?;
91        self.port.flush()?;
92        let mut buf = vec![0u8; 4096];
93        match self.port.read(&mut buf) {
94            Ok(n) => {
95                buf.truncate(n);
96                Ok(buf)
97            }
98            Err(ref e) if e.kind() == io::ErrorKind::TimedOut => Ok(vec![]),
99            Err(e) => Err(e),
100        }
101    }
102    fn is_open(&self) -> bool {
103        true
104    }
105    fn close(&mut self) -> io::Result<()> {
106        Ok(())
107    }
108}
109
110/// Stub transport when `serial` feature is not enabled.
111#[cfg(not(feature = "serial"))]
112pub struct SerialTransport {
113    config: SerialConfig,
114}
115
116#[cfg(not(feature = "serial"))]
117impl SerialTransport {
118    pub fn open(config: SerialConfig) -> io::Result<Self> {
119        Ok(SerialTransport { config })
120    }
121}
122
123#[cfg(not(feature = "serial"))]
124impl Transport for SerialTransport {
125    fn send(&mut self, _data: &[u8]) -> io::Result<Vec<u8>> {
126        Err(io::Error::new(
127            io::ErrorKind::Unsupported,
128            format!(
129                "Serial transport not available (enable 'serial' feature). Port: {}",
130                self.config.port
131            ),
132        ))
133    }
134    fn is_open(&self) -> bool {
135        false
136    }
137    fn close(&mut self) -> io::Result<()> {
138        Ok(())
139    }
140}
141
142#[cfg(test)]
143mod tests {
144    use super::*;
145
146    fn config(port: &str) -> SerialConfig {
147        SerialConfig {
148            port: port.into(),
149            baud_rate: 9600,
150            data_bits: 8,
151            parity: Parity::None,
152            stop_bits: 1,
153            timeout_ms: 100,
154        }
155    }
156
157    #[test]
158    fn test_available_ports_does_not_panic() {
159        let _ports = available_ports();
160    }
161
162    #[test]
163    fn test_parity_types() {
164        assert!(matches!(Parity::None, Parity::None));
165        assert!(matches!(Parity::Even, Parity::Even));
166        assert!(matches!(Parity::Odd, Parity::Odd));
167    }
168
169    #[test]
170    fn test_parity_is_copy() {
171        let a = Parity::Even;
172        let b = a;
173        assert!(matches!(b, Parity::Even));
174    }
175
176    #[test]
177    fn test_config_fields() {
178        let config = config("/dev/ttyS0");
179        assert_eq!(config.port, "/dev/ttyS0");
180        assert_eq!(config.baud_rate, 9600);
181        assert_eq!(config.data_bits, 8);
182        assert_eq!(config.stop_bits, 1);
183        assert_eq!(config.timeout_ms, 100);
184    }
185
186    #[cfg(not(feature = "serial"))]
187    #[test]
188    fn test_stub_open_succeeds_but_reports_closed() {
189        let t = SerialTransport::open(config("/dev/ttyTEST")).unwrap();
190        assert!(!t.is_open());
191    }
192
193    #[cfg(not(feature = "serial"))]
194    #[test]
195    fn test_stub_send_unsupported() {
196        let mut t = SerialTransport::open(config("/dev/ttyTEST")).unwrap();
197        let err = t.send(b"data").unwrap_err();
198        assert_eq!(err.kind(), std::io::ErrorKind::Unsupported);
199        assert!(err.to_string().contains("/dev/ttyTEST"));
200        assert!(err.to_string().contains("serial"));
201    }
202
203    #[cfg(not(feature = "serial"))]
204    #[test]
205    fn test_stub_close_idempotent() {
206        let mut t = SerialTransport::open(config("/dev/ttyTEST")).unwrap();
207        assert!(t.close().is_ok());
208        assert!(t.close().is_ok());
209    }
210
211    #[cfg(not(feature = "serial"))]
212    #[test]
213    fn test_available_ports_empty_without_feature() {
214        assert!(available_ports().is_empty());
215    }
216
217    #[cfg(feature = "serial")]
218    #[test]
219    fn test_real_open_nonexistent_port_fails() {
220        assert!(SerialTransport::open(config("/dev/ttyNONEXISTENT_XYZ")).is_err());
221    }
222}