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        Ok(len)
115    }
116}
117
118impl SerialPort for MockSerialPort {
119    fn name(&self) -> Option<String> {
120        Some("COM1".to_string())
121    }
122
123    fn baud_rate(&self) -> Result<u32, serialport::Error> {
124        Ok(self.baud_rate)
125    }
126
127    fn data_bits(&self) -> Result<serialport::DataBits, serialport::Error> {
128        Ok(self.data_bits)
129    }
130
131    fn flow_control(&self) -> Result<serialport::FlowControl, serialport::Error> {
132        Ok(self.flow_control)
133    }
134
135    fn parity(&self) -> Result<serialport::Parity, serialport::Error> {
136        Ok(self.parity)
137    }
138
139    fn stop_bits(&self) -> Result<serialport::StopBits, serialport::Error> {
140        Ok(self.stop_bits)
141    }
142
143    fn timeout(&self) -> Duration {
144        self.timeout
145    }
146
147    fn set_baud_rate(&mut self, rate: u32) -> Result<(), serialport::Error> {
148        self.baud_rate = rate;
149        Ok(())
150    }
151
152    fn set_data_bits(&mut self, bits: serialport::DataBits) -> Result<(), serialport::Error> {
153        self.data_bits = bits;
154        Ok(())
155    }
156
157    fn set_flow_control(&mut self, flow: serialport::FlowControl) -> Result<(), serialport::Error> {
158        self.flow_control = flow;
159        Ok(())
160    }
161
162    fn set_parity(&mut self, parity: serialport::Parity) -> Result<(), serialport::Error> {
163        self.parity = parity;
164        Ok(())
165    }
166
167    fn set_stop_bits(&mut self, bits: serialport::StopBits) -> Result<(), serialport::Error> {
168        self.stop_bits = bits;
169        Ok(())
170    }
171
172    fn set_timeout(&mut self, timeout: Duration) -> Result<(), serialport::Error> {
173        self.timeout = timeout;
174        Ok(())
175    }
176
177    fn write_request_to_send(&mut self, _level: bool) -> Result<(), serialport::Error> {
178        Ok(())
179    }
180
181    fn write_data_terminal_ready(&mut self, _level: bool) -> Result<(), serialport::Error> {
182        Ok(())
183    }
184
185    fn read_clear_to_send(&mut self) -> Result<bool, serialport::Error> {
186        Ok(true)
187    }
188
189    fn read_data_set_ready(&mut self) -> Result<bool, serialport::Error> {
190        Ok(true)
191    }
192
193    fn read_ring_indicator(&mut self) -> Result<bool, serialport::Error> {
194        Ok(true)
195    }
196
197    fn read_carrier_detect(&mut self) -> Result<bool, serialport::Error> {
198        Ok(true)
199    }
200
201    fn bytes_to_read(&self) -> Result<u32, serialport::Error> {
202        Ok((self.rx_buffer.len() + self.rx_script.iter().map(|c| c.len()).sum::<usize>()) as u32)
203    }
204
205    fn bytes_to_write(&self) -> Result<u32, serialport::Error> {
206        Ok(0)
207    }
208
209    fn clear(&self, _buffer_to_clear: serialport::ClearBuffer) -> Result<(), serialport::Error> {
210        Ok(())
211    }
212
213    fn try_clone(&self) -> Result<Box<dyn SerialPort>, serialport::Error> {
214        Ok(Box::new(MockSerialPort {
215            rx_buffer: self.rx_buffer.clone(),
216            rx_script: self.rx_script.clone(),
217            captured_tx: self.captured_tx.clone(),
218            next_read_error: self.next_read_error,
219            sticky_read_error: self.sticky_read_error,
220            baud_rate: self.baud_rate,
221            data_bits: self.data_bits,
222            flow_control: self.flow_control,
223            parity: self.parity,
224            stop_bits: self.stop_bits,
225            timeout: self.timeout,
226        }))
227    }
228
229    fn set_break(&self) -> Result<(), serialport::Error> {
230        Ok(())
231    }
232
233    fn clear_break(&self) -> Result<(), serialport::Error> {
234        Ok(())
235    }
236}
237
238impl Read for MockSerialPort {
239    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
240        if let Some(kind) = self.next_read_error.take().or(self.sticky_read_error) {
241            return Err(io::Error::new(kind, "injected read error"));
242        }
243        self.pull_rx(buf)
244    }
245}
246
247impl Write for MockSerialPort {
248    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
249        self.captured_tx.lock().unwrap().extend_from_slice(buf);
250        Ok(buf.len())
251    }
252
253    fn flush(&mut self) -> std::io::Result<()> {
254        Ok(())
255    }
256}
257
258#[allow(dead_code)]
259pub fn create_mock_serialport_info() -> SerialportInfo {
260    SerialportInfo {
261        state: PortState::Connected(ConnectedPort::new(Box::new(MockSerialPort::new()))),
262    }
263}