Skip to main content

serialplugin_core/
mock_serial.rs

1//! Shared desktop serial port mock for unit tests (scripted RX, TX capture, error injection).
2#[cfg(target_os = "ios")]
3use crate::serialport;
4
5use crate::state::{ConnectedPort, PortState, SerialportInfo};
6use serialport::SerialPort;
7use std::io::{self, Read, Write};
8use std::sync::{Arc, Mutex};
9use std::time::Duration;
10
11#[allow(dead_code)]
12pub trait SerialPortTrait: Read + Write + Send {
13    fn name(&self) -> Option<String>;
14    fn baud_rate(&self) -> io::Result<u32>;
15    fn data_bits(&self) -> io::Result<serialport::DataBits>;
16    fn flow_control(&self) -> io::Result<serialport::FlowControl>;
17    fn parity(&self) -> io::Result<serialport::Parity>;
18    fn stop_bits(&self) -> io::Result<serialport::StopBits>;
19    fn timeout(&self) -> io::Result<std::time::Duration>;
20    fn set_baud_rate(&mut self, baud_rate: u32) -> io::Result<()>;
21    fn set_data_bits(&mut self, data_bits: serialport::DataBits) -> io::Result<()>;
22    fn set_flow_control(&mut self, flow_control: serialport::FlowControl) -> io::Result<()>;
23    fn set_parity(&mut self, parity: serialport::Parity) -> io::Result<()>;
24    fn set_stop_bits(&mut self, stop_bits: serialport::StopBits) -> io::Result<()>;
25    fn set_timeout(&mut self, timeout: std::time::Duration) -> io::Result<()>;
26    fn write_request_to_send(&mut self, level: bool) -> io::Result<()>;
27    fn write_data_terminal_ready(&mut self, level: bool) -> io::Result<()>;
28    fn read_clear_to_send(&mut self) -> io::Result<bool>;
29    fn read_data_set_ready(&mut self) -> io::Result<bool>;
30    fn read_ring_indicator(&mut self) -> io::Result<bool>;
31    fn read_carrier_detect(&mut self) -> io::Result<bool>;
32    fn bytes_to_read(&self) -> io::Result<u32>;
33    fn bytes_to_write(&self) -> io::Result<u32>;
34    fn clear(&self, buffer_to_clear: serialport::ClearBuffer) -> io::Result<()>;
35    fn try_clone(&self) -> io::Result<Box<dyn SerialPort>>;
36    fn set_break(&self) -> io::Result<()>;
37    fn clear_break(&self) -> io::Result<()>;
38}
39
40/// In-memory serial port with optional scripted RX chunks and read-error injection.
41#[allow(dead_code)]
42pub struct MockSerialPort {
43    pub rx_buffer: Vec<u8>,
44    pub rx_script: Vec<Vec<u8>>,
45    pub captured_tx: Arc<Mutex<Vec<u8>>>,
46    pub next_read_error: Option<io::ErrorKind>,
47    /// Returned by every read (simulates an unplugged adapter).
48    pub sticky_read_error: Option<io::ErrorKind>,
49    pub baud_rate: u32,
50    pub data_bits: serialport::DataBits,
51    pub flow_control: serialport::FlowControl,
52    pub parity: serialport::Parity,
53    pub stop_bits: serialport::StopBits,
54    pub timeout: Duration,
55}
56
57#[allow(dead_code)]
58impl MockSerialPort {
59    pub fn new() -> Self {
60        Self::default()
61    }
62}
63
64impl Default for MockSerialPort {
65    fn default() -> Self {
66        Self {
67            rx_buffer: Vec::new(),
68            rx_script: Vec::new(),
69            captured_tx: Arc::new(Mutex::new(Vec::new())),
70            next_read_error: None,
71            sticky_read_error: None,
72            baud_rate: 9600,
73            data_bits: serialport::DataBits::Eight,
74            flow_control: serialport::FlowControl::None,
75            parity: serialport::Parity::None,
76            stop_bits: serialport::StopBits::One,
77            timeout: Duration::from_millis(1000),
78        }
79    }
80}
81
82#[allow(dead_code)]
83impl MockSerialPort {
84    pub fn with_rx_script(chunks: impl IntoIterator<Item = impl AsRef<[u8]>>) -> Self {
85        let mut mock = Self::new();
86        mock.rx_script = chunks.into_iter().map(|c| c.as_ref().to_vec()).collect();
87        mock
88    }
89
90    pub fn push_rx(&mut self, chunk: impl AsRef<[u8]>) {
91        self.rx_buffer.extend_from_slice(chunk.as_ref());
92    }
93
94    pub fn inject_read_error(&mut self, kind: io::ErrorKind) {
95        self.next_read_error = Some(kind);
96    }
97
98    pub fn captured_tx(&self) -> Vec<u8> {
99        self.captured_tx.lock().unwrap().clone()
100    }
101
102    fn pull_rx(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
103        if self.rx_buffer.is_empty() {
104            if let Some(chunk) = self.rx_script.first().cloned() {
105                self.rx_script.remove(0);
106                self.rx_buffer = chunk;
107            }
108        }
109        let len = std::cmp::min(buf.len(), self.rx_buffer.len());
110        if len > 0 {
111            buf[..len].copy_from_slice(&self.rx_buffer[..len]);
112            self.rx_buffer.drain(..len);
113        }
114        if len == 0 && !buf.is_empty() {
115            // As serialport: nothing within the timeout is `TimedOut` (`Ok(0)` is EOF).
116            return Err(io::Error::new(io::ErrorKind::TimedOut, "mock read timeout"));
117        }
118        Ok(len)
119    }
120}
121
122impl SerialPort for MockSerialPort {
123    fn name(&self) -> Option<String> {
124        Some("COM1".to_string())
125    }
126
127    fn baud_rate(&self) -> Result<u32, serialport::Error> {
128        Ok(self.baud_rate)
129    }
130
131    fn data_bits(&self) -> Result<serialport::DataBits, serialport::Error> {
132        Ok(self.data_bits)
133    }
134
135    fn flow_control(&self) -> Result<serialport::FlowControl, serialport::Error> {
136        Ok(self.flow_control)
137    }
138
139    fn parity(&self) -> Result<serialport::Parity, serialport::Error> {
140        Ok(self.parity)
141    }
142
143    fn stop_bits(&self) -> Result<serialport::StopBits, serialport::Error> {
144        Ok(self.stop_bits)
145    }
146
147    fn timeout(&self) -> Duration {
148        self.timeout
149    }
150
151    fn set_baud_rate(&mut self, rate: u32) -> Result<(), serialport::Error> {
152        self.baud_rate = rate;
153        Ok(())
154    }
155
156    fn set_data_bits(&mut self, bits: serialport::DataBits) -> Result<(), serialport::Error> {
157        self.data_bits = bits;
158        Ok(())
159    }
160
161    fn set_flow_control(&mut self, flow: serialport::FlowControl) -> Result<(), serialport::Error> {
162        self.flow_control = flow;
163        Ok(())
164    }
165
166    fn set_parity(&mut self, parity: serialport::Parity) -> Result<(), serialport::Error> {
167        self.parity = parity;
168        Ok(())
169    }
170
171    fn set_stop_bits(&mut self, bits: serialport::StopBits) -> Result<(), serialport::Error> {
172        self.stop_bits = bits;
173        Ok(())
174    }
175
176    fn set_timeout(&mut self, timeout: Duration) -> Result<(), serialport::Error> {
177        self.timeout = timeout;
178        Ok(())
179    }
180
181    fn write_request_to_send(&mut self, _level: bool) -> Result<(), serialport::Error> {
182        Ok(())
183    }
184
185    fn write_data_terminal_ready(&mut self, _level: bool) -> Result<(), serialport::Error> {
186        Ok(())
187    }
188
189    fn read_clear_to_send(&mut self) -> Result<bool, serialport::Error> {
190        Ok(true)
191    }
192
193    fn read_data_set_ready(&mut self) -> Result<bool, serialport::Error> {
194        Ok(true)
195    }
196
197    fn read_ring_indicator(&mut self) -> Result<bool, serialport::Error> {
198        Ok(true)
199    }
200
201    fn read_carrier_detect(&mut self) -> Result<bool, serialport::Error> {
202        Ok(true)
203    }
204
205    fn bytes_to_read(&self) -> Result<u32, serialport::Error> {
206        Ok((self.rx_buffer.len() + self.rx_script.iter().map(|c| c.len()).sum::<usize>()) as u32)
207    }
208
209    fn bytes_to_write(&self) -> Result<u32, serialport::Error> {
210        Ok(0)
211    }
212
213    fn clear(&self, _buffer_to_clear: serialport::ClearBuffer) -> Result<(), serialport::Error> {
214        Ok(())
215    }
216
217    fn try_clone(&self) -> Result<Box<dyn SerialPort>, serialport::Error> {
218        Ok(Box::new(MockSerialPort {
219            rx_buffer: self.rx_buffer.clone(),
220            rx_script: self.rx_script.clone(),
221            captured_tx: self.captured_tx.clone(),
222            next_read_error: self.next_read_error,
223            sticky_read_error: self.sticky_read_error,
224            baud_rate: self.baud_rate,
225            data_bits: self.data_bits,
226            flow_control: self.flow_control,
227            parity: self.parity,
228            stop_bits: self.stop_bits,
229            timeout: self.timeout,
230        }))
231    }
232
233    fn set_break(&self) -> Result<(), serialport::Error> {
234        Ok(())
235    }
236
237    fn clear_break(&self) -> Result<(), serialport::Error> {
238        Ok(())
239    }
240}
241
242impl Read for MockSerialPort {
243    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
244        if let Some(kind) = self.next_read_error.take().or(self.sticky_read_error) {
245            return Err(io::Error::new(kind, "injected read error"));
246        }
247        self.pull_rx(buf)
248    }
249}
250
251impl Write for MockSerialPort {
252    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
253        self.captured_tx.lock().unwrap().extend_from_slice(buf);
254        Ok(buf.len())
255    }
256
257    fn flush(&mut self) -> std::io::Result<()> {
258        Ok(())
259    }
260}
261
262#[allow(dead_code)]
263pub fn create_mock_serialport_info() -> SerialportInfo {
264    SerialportInfo {
265        state: PortState::Connected(ConnectedPort::new(Box::new(MockSerialPort::new()))),
266    }
267}