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}