serialplugin_core/cmux/
io.rs1#[cfg(target_os = "ios")]
3use crate::serialport;
4
5use serialport::SerialPort;
6use std::io::Write;
7use std::sync::{Arc, Mutex};
8use std::time::Duration;
9
10pub trait CmuxPhysicalIo: Send + Sync {
12 fn write_all(&self, data: &[u8]) -> Result<(), String>;
13
14 fn write_timeout(&self, len: usize) -> Duration {
17 let _ = len;
18 Duration::from_secs(1)
19 }
20}
21
22pub struct SerialPortIo(pub Arc<Mutex<Box<dyn SerialPort>>>);
23
24impl CmuxPhysicalIo for SerialPortIo {
25 fn write_all(&self, data: &[u8]) -> Result<(), String> {
28 let mut port = self
29 .0
30 .lock()
31 .map_err(|e| format!("port lock failed: {e}"))?;
32 let restore = port.timeout();
33 let timeout = write_timeout(&**port, data.len());
34 let _ = port.set_timeout(timeout);
35 let result = port
36 .write_all(data)
37 .map_err(|e| format!("cmux write failed: {e}"));
38 let _ = port.set_timeout(restore);
39 result
40 }
41
42 fn write_timeout(&self, len: usize) -> Duration {
43 match self.0.lock() {
44 Ok(port) => write_timeout(&**port, len),
45 Err(_) => Duration::from_secs(1),
46 }
47 }
48}
49
50fn write_timeout(port: &dyn SerialPort, len: usize) -> Duration {
53 use serialport::{DataBits, Parity, StopBits};
54 let data = match port.data_bits() {
55 Ok(DataBits::Five) => 5,
56 Ok(DataBits::Six) => 6,
57 Ok(DataBits::Seven) => 7,
58 _ => 8,
59 };
60 let parity = u64::from(matches!(port.parity(), Ok(Parity::Odd | Parity::Even)));
61 let stop = if matches!(port.stop_bits(), Ok(StopBits::Two)) {
62 2
63 } else {
64 1
65 };
66 let bits = 1 + data + parity + stop;
67 let baud = u64::from(port.baud_rate().unwrap_or(9600).max(1));
68 let wire_ms = (len as u64).saturating_mul(bits * 1000) / baud;
69 Duration::from_millis(wire_ms.saturating_mul(2) + 1000)
70}
71
72#[cfg(all(test, not(target_os = "android")))]
73mod tests {
74 use super::*;
75 use crate::mock_serial::MockSerialPort;
76
77 #[test]
78 fn cmux_write_timeout_scales_with_baud() {
79 let mut port = MockSerialPort::new(); assert_eq!(write_timeout(&port, 960), Duration::from_millis(3000));
82 port.baud_rate = 115_200;
83 assert_eq!(
84 write_timeout(&port, 960),
85 Duration::from_millis(2 * 83 + 1000)
86 );
87 port.baud_rate = 9600;
88 port.parity = serialport::Parity::Even;
89 port.stop_bits = serialport::StopBits::Two;
90 assert_eq!(
91 write_timeout(&port, 960),
92 Duration::from_millis(2 * 1200 + 1000)
93 );
94 port.baud_rate = 1200;
95 assert_eq!(
96 write_timeout(&port, 9600),
97 Duration::from_millis(2 * 96_000 + 1000)
98 );
99
100 let mock = MockSerialPort::new();
102 let tx = mock.captured_tx.clone();
103 let shared: Arc<Mutex<Box<dyn SerialPort>>> = Arc::new(Mutex::new(Box::new(mock)));
104 SerialPortIo(shared.clone()).write_all(b"frame").unwrap();
105 assert_eq!(
106 shared.lock().unwrap().timeout(),
107 Duration::from_millis(1000)
108 );
109 assert_eq!(tx.lock().unwrap().as_slice(), b"frame");
110 assert_eq!(
112 SerialPortIo(shared).write_timeout(960),
113 Duration::from_millis(3000)
114 );
115 }
116
117 #[test]
118 fn cmux_write_timeout_counts_the_data_bits() {
119 let mut port = MockSerialPort::new(); for (bits, per_char) in [
121 (serialport::DataBits::Five, 7u64),
122 (serialport::DataBits::Six, 8),
123 (serialport::DataBits::Seven, 9),
124 (serialport::DataBits::Eight, 10),
125 ] {
126 port.data_bits = bits;
127 assert_eq!(
129 write_timeout(&port, 9600),
130 Duration::from_millis(2 * per_char * 1000 + 1000),
131 "{bits:?}"
132 );
133 }
134 }
135
136 #[test]
137 fn default_write_timeout_is_one_second() {
138 struct Plain;
139 impl CmuxPhysicalIo for Plain {
140 fn write_all(&self, _data: &[u8]) -> Result<(), String> {
141 Ok(())
142 }
143 }
144 assert_eq!(Plain.write_timeout(10_000), Duration::from_secs(1));
145 }
146}