Skip to main content

serialplugin_core/cmux/
io.rs

1//! Physical port write abstraction (unified `serialport::SerialPort` bearer).
2#[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
10/// Writes raw bytes to the physical CMUX bearer.
11pub trait CmuxPhysicalIo: Send + Sync {
12    fn write_all(&self, data: &[u8]) -> Result<(), String>;
13
14    /// How long a write of `len` bytes may take; also how long a channel write waits
15    /// out flow control (FCoff, MSC FC) before it fails. Default 1 s.
16    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    /// Writes with a timeout from the wire time ([`write_timeout`]), then puts the
26    /// port's own timeout back.
27    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
50/// Twice the wire time of `len` bytes at the port's baud rate and character format
51/// (start + data + parity + stop bits), plus 1 s: the margin plain-port writes get.
52fn 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(); // 9600 8N1: 10 bits per char
80                                              // 960 bytes = 1 s on the wire: twice that plus 1 s.
81        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        // The write runs with that timeout and puts the port's own one back.
101        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    }
111}