Skip to main content

serial_mcp/serial/
connection.rs

1//! The single open serial connection: the `SerialIo` backend trait and its
2//! production `SerialStream` implementation, the `SerialConnection` struct
3//! with all methods, stream construction and baud validation, serialport
4//! error conversion, and connection/I/O/close/disconnect-state tests.
5//! Config types come from the `config` sibling; `PortInfo` from `port_info`.
6
7use std::fmt;
8use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
9use std::sync::Arc;
10use std::sync::Mutex as StdMutex;
11use std::time::{Duration, Instant};
12
13use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
14use tokio::sync::Mutex;
15use tokio::time::timeout;
16use tokio_serial::{SerialPort, SerialPortBuilderExt, SerialStream};
17use tokio_util::sync::CancellationToken;
18use uuid::Uuid;
19
20use crate::error::{Result, SerialError};
21
22use super::config::{
23    data_bits_to_str, flow_control_to_str, parity_to_str, stop_bits_to_str, ActiveProfileBinding,
24    ConnectionConfig, ConnectionState, ConnectionStatus, ConnectionSummary, DataBits, FlowControl,
25    FlushTarget, Parity, ReconnectPolicy, StopBits, MAX_BAUD_RATE,
26};
27use super::port_info::PortInfo;
28
29// ---- I/O backend trait -------------------------------------------------------
30
31/// Abstraction over the underlying byte stream plus the modem-control lines
32/// of a serial port.
33///
34/// The production backend ([`SerialStream`]) talks to a real OS-level
35/// serial port. Tests substitute an in-memory implementation backed by
36/// [`tokio::io::duplex`] so that read/write/transact can be exercised
37/// without any hardware.
38///
39/// Control-line operations (`clear_os_buffers`, `set_dtr_rts`,
40/// `set_flow_control`, `set_break_state`) are required methods so the trait can stay
41/// object-safe even when the backend doesn't have a real port behind it;
42/// in-memory backends typically implement them as no-ops.
43pub trait SerialIo: AsyncRead + AsyncWrite + Send + Unpin {
44    fn clear_os_buffers(&self, target: FlushTarget) -> std::io::Result<()>;
45    fn set_dtr_rts(&mut self, dtr: bool, rts: bool) -> std::io::Result<()>;
46    fn set_flow_control(&mut self, flow_control: FlowControl) -> std::io::Result<()>;
47    fn set_break_state(&self, asserted: bool) -> std::io::Result<()>;
48
49    /// Reconfigure baud rate on an already-open port. Default is no-op
50    /// for backends that don't support hardware reconfiguration.
51    fn reconfigure_baud_rate(&mut self, _baud_rate: u32) -> std::io::Result<()> {
52        Ok(())
53    }
54
55    /// Reconfigure data bits on an already-open port.
56    fn reconfigure_data_bits(&mut self, _data_bits: serialport::DataBits) -> std::io::Result<()> {
57        Ok(())
58    }
59
60    /// Reconfigure stop bits on an already-open port.
61    fn reconfigure_stop_bits(&mut self, _stop_bits: serialport::StopBits) -> std::io::Result<()> {
62        Ok(())
63    }
64
65    /// Reconfigure parity on an already-open port.
66    fn reconfigure_parity(&mut self, _parity: serialport::Parity) -> std::io::Result<()> {
67        Ok(())
68    }
69}
70
71impl SerialIo for SerialStream {
72    fn clear_os_buffers(&self, target: FlushTarget) -> std::io::Result<()> {
73        self.clear(target.into()).map_err(io_error_from_serialport)
74    }
75
76    fn set_dtr_rts(&mut self, dtr: bool, rts: bool) -> std::io::Result<()> {
77        self.write_data_terminal_ready(dtr)
78            .map_err(io_error_from_serialport)?;
79        self.write_request_to_send(rts)
80            .map_err(io_error_from_serialport)
81    }
82
83    fn set_flow_control(&mut self, flow_control: FlowControl) -> std::io::Result<()> {
84        SerialPort::set_flow_control(self, flow_control.into()).map_err(io_error_from_serialport)
85    }
86
87    fn set_break_state(&self, asserted: bool) -> std::io::Result<()> {
88        if asserted {
89            self.set_break().map_err(io_error_from_serialport)
90        } else {
91            self.clear_break().map_err(io_error_from_serialport)
92        }
93    }
94
95    fn reconfigure_baud_rate(&mut self, baud_rate: u32) -> std::io::Result<()> {
96        SerialPort::set_baud_rate(self, baud_rate).map_err(io_error_from_serialport)
97    }
98
99    fn reconfigure_data_bits(&mut self, data_bits: serialport::DataBits) -> std::io::Result<()> {
100        SerialPort::set_data_bits(self, data_bits).map_err(io_error_from_serialport)
101    }
102
103    fn reconfigure_stop_bits(&mut self, stop_bits: serialport::StopBits) -> std::io::Result<()> {
104        SerialPort::set_stop_bits(self, stop_bits).map_err(io_error_from_serialport)
105    }
106
107    fn reconfigure_parity(&mut self, parity: serialport::Parity) -> std::io::Result<()> {
108        SerialPort::set_parity(self, parity).map_err(io_error_from_serialport)
109    }
110}
111
112fn io_error_from_serialport(err: serialport::Error) -> std::io::Error {
113    std::io::Error::other(err.to_string())
114}
115
116// ---- Single open connection --------------------------------------------------
117
118/// A single open serial port. Cheap to clone via [`Arc`] because all state lives
119/// behind a [`Mutex`].
120pub struct SerialConnection {
121    id: String,
122    port: String,
123    name: Option<String>,
124    baud_rate: StdMutex<u32>,
125    data_bits: StdMutex<DataBits>,
126    stop_bits: StdMutex<StopBits>,
127    parity: StdMutex<Parity>,
128    flow_control: StdMutex<FlowControl>,
129    io: Mutex<Option<Box<dyn SerialIo>>>,
130    close_token: CancellationToken,
131    closed: AtomicBool,
132    /// Total bytes written to the device via the `write` tool.
133    tx_bytes: AtomicU64,
134    /// Total bytes read from the device and delivered through any RX path.
135    rx_bytes: AtomicU64,
136    /// Wall-clock time of the last rx or tx byte operation.
137    last_activity: StdMutex<Option<std::time::SystemTime>>,
138    /// Number of successful read-pipeline operations (`read`, `transact` read
139    /// half, `capture_boot`).
140    read_ops: AtomicU64,
141    /// Number of successful `write` operations.
142    write_ops: AtomicU64,
143    /// Number of RX operations where data was truncated
144    /// (bytes_returned < bytes_observed).
145    truncation_count: AtomicU64,
146    /// OS-level port identity captured at open time.
147    port_info: Option<PortInfo>,
148    /// Per-connection event log buffer.
149    log: Arc<crate::log_buffer::LogBuffer>,
150    /// Current connection health state.
151    state: StdMutex<ConnectionState>,
152    /// Reconnect policy for this connection.
153    pub(crate) reconnect_policy: StdMutex<ReconnectPolicy>,
154    /// Count of reconnect attempts since the last disconnect.
155    reconnect_attempts: AtomicU64,
156    /// Last fatal I/O error message and timestamp.
157    last_error: StdMutex<Option<(std::time::SystemTime, String)>>,
158    /// Default TX framing from profile/open call.
159    tx_framing_default: StdMutex<Option<crate::framing::TxFramingConfig>>,
160    /// Default RX framing from profile/open call.
161    rx_framing_default: StdMutex<Option<crate::framing::RxFramingConfig>>,
162    /// Default RX parser from profile/open call.
163    rx_parser_default: StdMutex<Option<crate::framing::ParserConfig>>,
164    /// Default protocol preset from profile/open call.
165    protocol_default: StdMutex<Option<crate::framing::ProtocolPreset>>,
166    /// Default max buffered bytes for `read` (from profile/open, mutable live).
167    max_buffered_bytes_default: AtomicUsize,
168    /// Active profile-session binding. `None` for connections
169    /// inserted directly by low-level tests.
170    active_profile: StdMutex<Option<ActiveProfileBinding>>,
171    /// Serializes durable write-through-learning sequences on this
172    /// connection (live mutation → effective snapshot → CAS persistence →
173    /// binding update). Held across `reconfigure`/`set_flow_control`/
174    /// connection-mode `configure`/clean close so concurrent requests
175    /// cannot snapshot each other's half-applied state.
176    learning_lock: tokio::sync::Mutex<()>,
177    /// Serializes line-control operations: `set_dtr_rts` and the
178    /// `capture_boot` reset pulse both hold this so a concurrent line-control
179    /// request cannot interleave inside an assert/hold/release sequence.
180    control_lock: tokio::sync::Mutex<()>,
181    /// Effective RX ring buffer size from the open config, so profile
182    /// snapshots never depend on whichever handler-local `RxSessionManager`
183    /// receives a later request.
184    rx_buffer_size: usize,
185}
186
187impl fmt::Debug for SerialConnection {
188    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
189        f.debug_struct("SerialConnection")
190            .field("id", &self.id)
191            .field("port", &self.port)
192            .field("name", &self.name)
193            .finish()
194    }
195}
196
197impl SerialConnection {
198    /// Open a serial port using the supplied configuration.
199    pub async fn open(config: ConnectionConfig) -> Result<Self> {
200        ensure_valid_baud_rate(config.baud_rate)?;
201        let stream = build_stream(&config)?;
202        Ok(Self::from_io_with_config(config, Box::new(stream)))
203    }
204
205    /// Build a connection from an arbitrary [`SerialIo`] backend. Used by
206    /// tests to inject an in-memory duplex stream.
207    pub fn from_io(port: String, io: Box<dyn SerialIo>) -> Self {
208        Self::from_io_with_config(
209            ConnectionConfig {
210                port,
211                name: None,
212                baud_rate: 115200,
213                data_bits: DataBits::Eight,
214                stop_bits: StopBits::One,
215                parity: Parity::None,
216                flow_control: FlowControl::None,
217                port_info: None,
218                log_capacity: 1024,
219                log_enabled: true,
220                tx_framing: None,
221                rx_framing: None,
222                rx_parser: None,
223                protocol: None,
224                rx_buffer_size: crate::limits::DEFAULT_RX_BUFFER_SIZE,
225                max_buffered_bytes: 32768,
226            },
227            io,
228        )
229    }
230
231    pub fn from_io_with_config(config: ConnectionConfig, io: Box<dyn SerialIo>) -> Self {
232        let log = crate::log_buffer::LogBuffer::new_shared(config.log_capacity, config.log_enabled);
233        log.opened();
234        Self {
235            id: Uuid::new_v4().to_string(),
236            port: config.port,
237            name: config.name,
238            baud_rate: StdMutex::new(config.baud_rate),
239            data_bits: StdMutex::new(config.data_bits),
240            stop_bits: StdMutex::new(config.stop_bits),
241            parity: StdMutex::new(config.parity),
242            flow_control: StdMutex::new(config.flow_control),
243            io: Mutex::new(Some(io)),
244            close_token: CancellationToken::new(),
245            closed: AtomicBool::new(false),
246            tx_bytes: AtomicU64::new(0),
247            rx_bytes: AtomicU64::new(0),
248            last_activity: StdMutex::new(None),
249            read_ops: AtomicU64::new(0),
250            write_ops: AtomicU64::new(0),
251            truncation_count: AtomicU64::new(0),
252            port_info: config.port_info,
253            log,
254            state: StdMutex::new(ConnectionState::Open),
255            reconnect_policy: StdMutex::new(ReconnectPolicy::default()),
256            reconnect_attempts: AtomicU64::new(0),
257            last_error: StdMutex::new(None),
258            tx_framing_default: StdMutex::new(config.tx_framing),
259            rx_framing_default: StdMutex::new(config.rx_framing),
260            rx_parser_default: StdMutex::new(config.rx_parser),
261            protocol_default: StdMutex::new(config.protocol),
262            max_buffered_bytes_default: AtomicUsize::new(config.max_buffered_bytes),
263            active_profile: StdMutex::new(None),
264            learning_lock: tokio::sync::Mutex::new(()),
265            control_lock: tokio::sync::Mutex::new(()),
266            rx_buffer_size: config.rx_buffer_size,
267        }
268    }
269
270    pub fn id(&self) -> &str {
271        &self.id
272    }
273
274    pub fn port(&self) -> &str {
275        &self.port
276    }
277
278    pub fn name(&self) -> Option<&str> {
279        self.name.as_deref()
280    }
281
282    pub fn baud_rate(&self) -> u32 {
283        *self.baud_rate.lock().expect("baud_rate mutex poisoned")
284    }
285
286    pub fn flow_control(&self) -> FlowControl {
287        *self
288            .flow_control
289            .lock()
290            .expect("flow_control mutex poisoned")
291    }
292
293    pub fn data_bits(&self) -> DataBits {
294        *self.data_bits.lock().expect("data_bits mutex poisoned")
295    }
296
297    pub fn stop_bits(&self) -> StopBits {
298        *self.stop_bits.lock().expect("stop_bits mutex poisoned")
299    }
300
301    pub fn parity(&self) -> Parity {
302        *self.parity.lock().expect("parity mutex poisoned")
303    }
304
305    /// Return the OS-level port identity captured at open time.
306    pub fn port_info(&self) -> Option<&PortInfo> {
307        self.port_info.as_ref()
308    }
309
310    /// Return the per-connection event log buffer.
311    pub fn log(&self) -> &Arc<crate::log_buffer::LogBuffer> {
312        &self.log
313    }
314
315    /// Default TX framing stored on the connection (from profile or `open`).
316    /// Returns by value (cloned from interior mutex for live mutation).
317    pub fn tx_framing_default(&self) -> Option<crate::framing::TxFramingConfig> {
318        self.tx_framing_default.lock().expect("poisoned").clone()
319    }
320
321    /// Default RX framing stored on the connection.
322    pub fn rx_framing_default(&self) -> Option<crate::framing::RxFramingConfig> {
323        self.rx_framing_default.lock().expect("poisoned").clone()
324    }
325
326    /// Default RX parser stored on the connection.
327    pub fn rx_parser_default(&self) -> Option<crate::framing::ParserConfig> {
328        self.rx_parser_default.lock().expect("poisoned").clone()
329    }
330
331    /// Default protocol preset stored on the connection. `Copy`, so returned by value.
332    /// Lock internal mutex for live mutation via `configure`.
333    pub fn protocol_default(&self) -> Option<crate::framing::ProtocolPreset> {
334        *self
335            .protocol_default
336            .lock()
337            .expect("protocol_default mutex poisoned")
338    }
339
340    /// Default max buffered bytes for `read` operations. Mutable live.
341    pub fn max_buffered_bytes_default(&self) -> usize {
342        self.max_buffered_bytes_default
343            .load(std::sync::atomic::Ordering::SeqCst)
344    }
345
346    /// The active profile-session binding, if this connection was opened
347    /// through a public open path.
348    pub fn active_profile_binding(&self) -> Option<ActiveProfileBinding> {
349        self.active_profile.lock().expect("poisoned").clone()
350    }
351
352    /// Attach (or clear) the active profile-session binding.
353    pub(crate) fn set_active_profile_binding(&self, binding: Option<ActiveProfileBinding>) {
354        *self.active_profile.lock().expect("poisoned") = binding;
355    }
356
357    /// Mutate the active profile-session binding in place
358    /// (dirty/stale/error/revision updates from write-through learning).
359    pub(crate) fn update_active_profile_binding(
360        &self,
361        update: impl FnOnce(&mut ActiveProfileBinding),
362    ) {
363        let mut guard = self.active_profile.lock().expect("poisoned");
364        if let Some(binding) = guard.as_mut() {
365            update(binding);
366        }
367    }
368
369    /// The per-connection learning lock. Durable operations hold this across
370    /// the live mutation, the effective snapshot, the CAS persistence
371    /// attempt, and the binding update.
372    pub(crate) fn learning_lock(&self) -> &tokio::sync::Mutex<()> {
373        &self.learning_lock
374    }
375
376    /// The per-connection line-control lock. `capture_boot` holds this
377    /// across its whole assert/hold/release sequence so a concurrent
378    /// `set_dtr_rts` cannot interleave inside the pulse. Callers acquiring
379    /// it must use the unlocked line setter
380    /// ([`Self::set_dtr_rts_unlocked`]).
381    pub(crate) fn control_lock(&self) -> &tokio::sync::Mutex<()> {
382        &self.control_lock
383    }
384
385    /// Snapshot the connection's full effective `ProfileDefaults`: current
386    /// serial parameters, framing/parser/protocol defaults, the stored RX
387    /// buffer size, read defaults, reconnect policy, log
388    /// configuration, and the connection name. Used by write-through
389    /// learning, close retry, and explicit `save_profile` — never consults
390    /// a handler-local `RxSessionManager`.
391    pub(crate) fn effective_defaults(&self) -> crate::profiles::ProfileDefaults {
392        crate::profiles::ProfileDefaults {
393            baud_rate: self.baud_rate(),
394            data_bits: data_bits_to_str(self.data_bits()),
395            stop_bits: stop_bits_to_str(self.stop_bits()),
396            parity: parity_to_str(self.parity()),
397            flow_control: flow_control_to_str(self.flow_control()),
398            name: self.name.clone(),
399            tx_framing: self.tx_framing_default(),
400            rx_framing: self.rx_framing_default(),
401            rx_parser: self.rx_parser_default(),
402            protocol: self.protocol_default(),
403            rx_buffer_size: self.rx_buffer_size(),
404            max_buffered_bytes: self.max_buffered_bytes_default(),
405            reconnect_policy: self.reconnect_policy.lock().expect("poisoned").clone(),
406            log_capacity: self.log.capacity(),
407            log_enabled: self.log.is_enabled(),
408        }
409    }
410
411    /// The effective RX ring buffer size configured at open time.
412    pub fn rx_buffer_size(&self) -> usize {
413        self.rx_buffer_size
414    }
415
416    // ── Live mutators (pub(crate); exposed via `configure` tool) ──────────
417
418    /// Set the default TX framing on a live connection.
419    pub(crate) fn set_tx_framing_default(&self, v: Option<crate::framing::TxFramingConfig>) {
420        *self.tx_framing_default.lock().expect("poisoned") = v;
421    }
422
423    /// Set the default RX framing on a live connection.
424    pub(crate) fn set_rx_framing_default(&self, v: Option<crate::framing::RxFramingConfig>) {
425        *self.rx_framing_default.lock().expect("poisoned") = v;
426    }
427
428    /// Set the default RX parser on a live connection.
429    pub(crate) fn set_rx_parser_default(&self, v: Option<crate::framing::ParserConfig>) {
430        *self.rx_parser_default.lock().expect("poisoned") = v;
431    }
432
433    /// Set the default protocol preset on a live connection.
434    pub(crate) fn set_protocol_default(&self, v: Option<crate::framing::ProtocolPreset>) {
435        *self.protocol_default.lock().expect("poisoned") = v;
436    }
437
438    /// Set the default max buffered bytes on a live connection.
439    pub(crate) fn set_max_buffered_bytes_default(&self, v: usize) {
440        self.max_buffered_bytes_default
441            .store(v, std::sync::atomic::Ordering::SeqCst);
442    }
443
444    /// Return the current connection health state.
445    pub fn state(&self) -> ConnectionState {
446        *self.state.lock().expect("state mutex poisoned")
447    }
448
449    /// Set the connection state and log the transition.
450    fn set_state(&self, new_state: ConnectionState) {
451        *self.state.lock().expect("state mutex poisoned") = new_state;
452    }
453
454    /// Mark the connection as disconnected due to a fatal I/O error.
455    /// Takes the io handle out (sets to None), cancels in-flight operations,
456    /// and clears RX buffers.
457    pub async fn mark_disconnected(&self, error_message: String) {
458        let was_healthy = self.state().is_healthy();
459        self.set_state(ConnectionState::Disconnected);
460        self.last_error
461            .lock()
462            .expect("poisoned")
463            .replace((std::time::SystemTime::now(), error_message.clone()));
464        // We do NOT cancel close_token here — that is reserved for explicit
465        // close(). The pump and in-flight reads will time out naturally and
466        // retry when the port is reconnected.
467        self.log.rx_data(0); // dummy to trigger log
468        self.log.record(
469            None,
470            crate::log_buffer::LogEvent::Disconnect {
471                error: error_message,
472            },
473        );
474        // Take the io handle out so subsequent I/O calls get ConnectionClosed
475        let mut io_lock = self.io.lock().await;
476        if let Some(mut io) = io_lock.take() {
477            // Best-effort: clear OS buffers and shutdown
478            let _ = io.clear_os_buffers(FlushTarget::Input);
479            let _ = io.shutdown().await;
480        }
481        if was_healthy {
482            tracing::warn!("Connection {} disconnected", self.display_name());
483        }
484    }
485
486    /// Attempt to re-establish the serial port connection.
487    ///
488    /// Rebuilds a `SerialStream` from the stored config and replaces the
489    /// current `io` handle in place. Preserves all counters, id, name,
490    /// and log buffer. Called by auto-reconnect tasks and the reconnect
491    /// tool.
492    pub async fn reconnect(&self) -> Result<()> {
493        let state = self.state();
494        if state == ConnectionState::Open {
495            return Ok(()); // already connected
496        }
497        if state == ConnectionState::Closed {
498            return Err(SerialError::ConnectionClosed(self.display_name()));
499        }
500
501        self.set_state(ConnectionState::Reconnecting);
502        self.reconnect_attempts.fetch_add(1, Ordering::SeqCst);
503        let attempt = self.reconnect_attempts.load(Ordering::SeqCst) as u32;
504        self.log.record(
505            None,
506            crate::log_buffer::LogEvent::ReconnectStart { attempt },
507        );
508
509        let config = self.build_config();
510        match build_stream(&config) {
511            Ok(stream) => {
512                let mut io_lock = self.io.lock().await;
513                *io_lock = Some(Box::new(stream));
514                self.closed.store(false, Ordering::SeqCst);
515                self.set_state(ConnectionState::Open);
516                self.log
517                    .record(None, crate::log_buffer::LogEvent::ReconnectSuccess);
518                tracing::info!("Connection {} reconnected", self.display_name());
519                Ok(())
520            }
521            Err(e) => {
522                self.set_state(ConnectionState::Disconnected);
523                let msg = e.to_string();
524                self.log.record(
525                    None,
526                    crate::log_buffer::LogEvent::ReconnectFailed {
527                        attempt,
528                        error: msg,
529                    },
530                );
531                Err(e)
532            }
533        }
534    }
535
536    /// Reset the reconnect-attempt counter after a successful reconnect.
537    pub(super) fn reset_reconnect_attempts(&self) {
538        self.reconnect_attempts.store(0, Ordering::SeqCst);
539    }
540
541    /// Build a `ConnectionConfig` from the current connection state,
542    /// for use in reconnect.
543    fn build_config(&self) -> ConnectionConfig {
544        ConnectionConfig {
545            port: self.port.clone(),
546            name: self.name.clone(),
547            baud_rate: self.baud_rate(),
548            data_bits: self.data_bits(),
549            stop_bits: self.stop_bits(),
550            parity: self.parity(),
551            flow_control: self.flow_control(),
552            port_info: self.port_info.clone(),
553            log_capacity: 1024, // preserve log config
554            log_enabled: self.log.is_enabled(),
555            tx_framing: self.tx_framing_default(),
556            rx_framing: self.rx_framing_default(),
557            rx_parser: self.rx_parser_default(),
558            protocol: self.protocol_default(),
559            rx_buffer_size: self.rx_buffer_size(),
560            max_buffered_bytes: self.max_buffered_bytes_default(),
561        }
562    }
563
564    /// Record `n` bytes written to the device.
565    pub fn record_tx_bytes(&self, n: usize) {
566        self.tx_bytes.fetch_add(n as u64, Ordering::SeqCst);
567        *self.last_activity.lock().expect("poisoned") = Some(std::time::SystemTime::now());
568    }
569
570    /// Record `n` bytes read from the device.
571    pub fn record_rx_bytes(&self, n: usize) {
572        self.rx_bytes.fetch_add(n as u64, Ordering::SeqCst);
573        *self.last_activity.lock().expect("poisoned") = Some(std::time::SystemTime::now());
574    }
575
576    /// Return the last I/O activity as milliseconds since Unix epoch.
577    pub fn last_activity_ms(&self) -> Option<u64> {
578        self.last_activity.lock().expect("poisoned").and_then(|t| {
579            t.duration_since(std::time::UNIX_EPOCH)
580                .map(|d| d.as_millis() as u64)
581                .ok()
582        })
583    }
584
585    /// Record one successful read-pipeline operation (`read`, `transact` read
586    /// half, or `capture_boot`).
587    pub fn record_read_op(&self) {
588        self.read_ops.fetch_add(1, Ordering::SeqCst);
589    }
590
591    /// Record one successful write operation.
592    pub fn record_write_op(&self) {
593        self.write_ops.fetch_add(1, Ordering::SeqCst);
594    }
595
596    /// Record one RX truncation (bytes_returned < bytes_observed).
597    pub fn record_truncation(&self) {
598        self.truncation_count.fetch_add(1, Ordering::SeqCst);
599    }
600
601    /// Build a snapshot of the current status of this connection.
602    pub fn status_snapshot(&self) -> ConnectionStatus {
603        ConnectionStatus {
604            connection_id: self.id().to_string(),
605            name: self.name().map(str::to_string),
606            port: self.port().to_string(),
607            baud_rate: self.baud_rate(),
608            data_bits: data_bits_to_str(self.data_bits()),
609            stop_bits: stop_bits_to_str(self.stop_bits()),
610            parity: parity_to_str(self.parity()),
611            flow_control: flow_control_to_str(self.flow_control()),
612            is_closed: self.closed.load(Ordering::SeqCst),
613            tx_bytes: self.tx_bytes.load(Ordering::SeqCst),
614            rx_bytes: self.rx_bytes.load(Ordering::SeqCst),
615            last_activity_ms: self.last_activity_ms(),
616            read_ops: self.read_ops.load(Ordering::SeqCst),
617            write_ops: self.write_ops.load(Ordering::SeqCst),
618            truncation_count: self.truncation_count.load(Ordering::SeqCst),
619            port_info: self.port_info.clone(),
620            state: self.state(),
621            reconnect_attempts: self.reconnect_attempts.load(Ordering::SeqCst),
622            last_error: self
623                .last_error
624                .lock()
625                .expect("poisoned")
626                .as_ref()
627                .map(|(_, msg)| msg.clone()),
628            profile: self.active_profile_binding().map(|b| b.to_session_result()),
629        }
630    }
631
632    pub fn cancel_token(&self) -> CancellationToken {
633        self.close_token.clone()
634    }
635
636    pub fn summary(&self) -> ConnectionSummary {
637        ConnectionSummary {
638            connection_id: self.id().to_string(),
639            name: self.name().map(str::to_string),
640            port: self.port().to_string(),
641            baud_rate: self.baud_rate(),
642            flow_control: self.flow_control(),
643            profile: self.active_profile_binding().map(|b| b.to_session_result()),
644        }
645    }
646
647    fn ensure_open(&self) -> Result<()> {
648        if self.closed.load(Ordering::SeqCst) {
649            return Err(SerialError::ConnectionClosed(self.display_name()));
650        }
651        Ok(())
652    }
653
654    fn display_name(&self) -> String {
655        self.name.clone().unwrap_or_else(|| self.id.clone())
656    }
657
658    /// Write a byte slice, flushing before returning.
659    pub async fn write(&self, data: &[u8]) -> Result<usize> {
660        self.ensure_open()?;
661        self.log.tx_data(data.len());
662        let mut io = self.io.lock().await;
663        let io = io
664            .as_mut()
665            .ok_or_else(|| SerialError::ConnectionClosed(self.display_name()))?;
666        io.write_all(data).await?;
667        io.flush().await?;
668        self.record_tx_bytes(data.len());
669        Ok(data.len())
670    }
671
672    /// Read up to `dst.len()` bytes. Returns [`SerialError::ReadTimeout`] if
673    /// `timeout_ms` is set and elapses before any byte arrives.
674    ///
675    /// When a timeout is given, the lock on the underlying IO is held for at
676    /// most `POLL_MS` milliseconds at a time and released between polls.  This
677    /// lets concurrent `write` calls on the same connection proceed without
678    /// waiting for the full read timeout — which is essential for the
679    /// request/response pattern (`transact`) on CDC-ACM devices.
680    pub async fn read(&self, dst: &mut [u8], timeout_ms: Option<u64>) -> Result<usize> {
681        const POLL_MS: u64 = 50;
682        self.ensure_open()?;
683        match timeout_ms {
684            None => {
685                let mut io = self.io.lock().await;
686                let io = io
687                    .as_mut()
688                    .ok_or_else(|| SerialError::ConnectionClosed(self.display_name()))?;
689                let n = tokio::select! {
690                    _ = self.close_token.cancelled() => Err(SerialError::ConnectionClosed(self.display_name())),
691                    res = io.read(dst) => Ok(res?),
692                }?;
693                self.record_rx_bytes(n);
694                Ok(n)
695            }
696            Some(ms) => {
697                let deadline = Instant::now() + Duration::from_millis(ms);
698                loop {
699                    if self.close_token.is_cancelled() {
700                        return Err(SerialError::ConnectionClosed(self.display_name()));
701                    }
702                    let remaining = deadline.saturating_duration_since(Instant::now());
703                    if remaining.is_zero() {
704                        return Err(SerialError::ReadTimeout);
705                    }
706                    let poll_dur = remaining.min(Duration::from_millis(POLL_MS));
707                    {
708                        let mut io = self.io.lock().await;
709                        let io = io
710                            .as_mut()
711                            .ok_or_else(|| SerialError::ConnectionClosed(self.display_name()))?;
712                        match tokio::select! {
713                            _ = self.close_token.cancelled() => return Err(SerialError::ConnectionClosed(self.display_name())),
714                            res = timeout(poll_dur, io.read(dst)) => res,
715                        } {
716                            Ok(Ok(n)) if n > 0 => {
717                                self.record_rx_bytes(n);
718                                return Ok(n);
719                            }
720                            Ok(Ok(_)) => {}
721                            Ok(Err(e)) => return Err(SerialError::from(e)),
722                            Err(_elapsed) => {}
723                        }
724                    }
725                    // Yield to allow the I/O driver time to process epoll events
726                    // before re-acquiring the mutex for the next poll.
727                    tokio::time::sleep(Duration::from_millis(5)).await;
728                }
729            }
730        }
731    }
732
733    /// Read up to `max_bytes` with a brief timeout (100ms) to capture any
734    /// immediately available data without blocking long.
735    pub async fn read_latest(&self, max_bytes: usize) -> Result<Vec<u8>> {
736        let mut buf = vec![0u8; max_bytes];
737        let n = self.read(&mut buf, Some(100)).await?;
738        buf.truncate(n);
739        Ok(buf)
740    }
741
742    /// Discard data buffered in the OS for the input, output, or both
743    /// directions of this port.
744    pub async fn flush_buffers(&self, target: FlushTarget) -> Result<()> {
745        self.ensure_open()?;
746        let io = self.io.lock().await;
747        io.as_ref()
748            .ok_or_else(|| SerialError::ConnectionClosed(self.display_name()))?
749            .clear_os_buffers(target)
750            .map_err(SerialError::from)
751    }
752
753    /// Drive the DTR and RTS control lines. Common use case: pulse DTR low
754    /// to soft-reset an Arduino, or hold both low to enter the ESP32
755    /// bootloader.
756    ///
757    /// Takes the per-connection line-control lock so the change cannot
758    /// interleave with a `capture_boot` reset pulse.
759    pub async fn set_dtr_rts(&self, dtr: bool, rts: bool) -> Result<()> {
760        let _control = self.control_lock().lock().await;
761        self.set_dtr_rts_unlocked(dtr, rts).await
762    }
763
764    /// Set DTR/RTS without taking the per-connection line-control lock.
765    /// Callers must already hold the lock (see [`Self::control_lock`]);
766    /// `capture_boot` uses this for its assert/hold/release sequence.
767    pub(crate) async fn set_dtr_rts_unlocked(&self, dtr: bool, rts: bool) -> Result<()> {
768        self.ensure_open()?;
769        let mut io = self.io.lock().await;
770        io.as_mut()
771            .ok_or_else(|| SerialError::ConnectionClosed(self.display_name()))?
772            .set_dtr_rts(dtr, rts)
773            .map_err(SerialError::from)
774    }
775
776    pub async fn set_flow_control(&self, flow_control: FlowControl) -> Result<()> {
777        self.ensure_open()?;
778        let mut io = self.io.lock().await;
779        io.as_mut()
780            .ok_or_else(|| SerialError::ConnectionClosed(self.display_name()))?
781            .set_flow_control(flow_control)
782            .map_err(SerialError::from)?;
783        *self
784            .flow_control
785            .lock()
786            .expect("flow_control mutex poisoned") = flow_control;
787        Ok(())
788    }
789
790    /// Set the BREAK condition on the TX line.
791    pub async fn set_break_state(&self, enabled: bool) -> Result<()> {
792        self.ensure_open()?;
793        let io = self.io.lock().await;
794        io.as_ref()
795            .ok_or_else(|| SerialError::ConnectionClosed(self.display_name()))?
796            .set_break_state(enabled)
797            .map_err(SerialError::from)
798    }
799
800    /// Assert the BREAK condition on the TX line for `duration_ms`
801    /// milliseconds, then release it.
802    pub async fn send_break(&self, duration_ms: u64) -> Result<()> {
803        self.set_break_state(true).await?;
804        tokio::time::sleep(Duration::from_millis(duration_ms)).await;
805        self.set_break_state(false).await
806    }
807
808    /// Reconfigure serial parameters on a live connection. Parameters passed
809    /// as `None` are left unchanged. Returns the effective config after the
810    /// operation completes.
811    pub async fn reconfigure(
812        &self,
813        baud_rate: Option<u32>,
814        data_bits: Option<DataBits>,
815        stop_bits: Option<StopBits>,
816        parity: Option<Parity>,
817        flow_control: Option<FlowControl>,
818    ) -> Result<ConnectionStatus> {
819        self.ensure_open()?;
820
821        if let Some(rate) = baud_rate {
822            ensure_valid_baud_rate(rate)?;
823        }
824
825        // Apply requested changes to the underlying serial port hardware.
826        {
827            let mut io = self.io.lock().await;
828            let io = io
829                .as_mut()
830                .ok_or_else(|| SerialError::ConnectionClosed(self.display_name()))?;
831
832            if let Some(rate) = baud_rate {
833                io.reconfigure_baud_rate(rate).map_err(SerialError::from)?;
834            }
835            if let Some(db) = data_bits {
836                io.reconfigure_data_bits(db.into())
837                    .map_err(SerialError::from)?;
838            }
839            if let Some(sb) = stop_bits {
840                io.reconfigure_stop_bits(sb.into())
841                    .map_err(SerialError::from)?;
842            }
843            if let Some(p) = parity {
844                io.reconfigure_parity(p.into()).map_err(SerialError::from)?;
845            }
846            if let Some(fc) = flow_control {
847                io.set_flow_control(fc).map_err(SerialError::from)?;
848            }
849        }
850
851        // Update stored configuration.
852        if let Some(rate) = baud_rate {
853            *self.baud_rate.lock().expect("poisoned") = rate;
854        }
855        if let Some(db) = data_bits {
856            *self.data_bits.lock().expect("poisoned") = db;
857        }
858        if let Some(sb) = stop_bits {
859            *self.stop_bits.lock().expect("poisoned") = sb;
860        }
861        if let Some(p) = parity {
862            *self.parity.lock().expect("poisoned") = p;
863        }
864        if let Some(fc) = flow_control {
865            *self.flow_control.lock().expect("poisoned") = fc;
866        }
867
868        Ok(self.status_snapshot())
869    }
870
871    pub async fn close(&self) -> Result<()> {
872        if self.closed.swap(true, Ordering::SeqCst) {
873            return Ok(());
874        }
875        self.set_state(ConnectionState::Closed);
876        self.close_token.cancel();
877
878        let mut io = self.io.lock().await;
879        if let Some(mut io) = io.take() {
880            io.clear_os_buffers(FlushTarget::Input)
881                .map_err(SerialError::from)?;
882            io.shutdown().await?;
883        }
884        Ok(())
885    }
886}
887
888fn ensure_valid_baud_rate(baud_rate: u32) -> Result<()> {
889    if baud_rate == 0 || baud_rate > MAX_BAUD_RATE {
890        Err(SerialError::InvalidBaudRate(baud_rate))
891    } else {
892        Ok(())
893    }
894}
895
896fn build_stream(config: &ConnectionConfig) -> Result<SerialStream> {
897    tokio_serial::new(&config.port, config.baud_rate)
898        .data_bits(config.data_bits.into())
899        .stop_bits(config.stop_bits.into())
900        .parity(config.parity.into())
901        .flow_control(config.flow_control.into())
902        .open_native_async()
903        .map_err(|e| SerialError::OpenFailed(format!("{}: {}", config.port, e)))
904}
905
906/// Test-only helpers for `SerialConnection`.
907#[cfg(test)]
908impl SerialConnection {
909    /// Set the connection state directly. Only available in tests so unit
910    /// tests can exercise `disconnect_state` classification without
911    /// driving the full reconnect state machine.
912    pub(crate) fn set_state_for_test(&mut self, state: ConnectionState) {
913        *self.state.lock().unwrap() = state;
914    }
915}
916
917#[cfg(test)]
918mod tests {
919    use super::*;
920    use crate::serial::manager::ConnectionManager;
921    use crate::serial::test_support::loopback_connection;
922    use crate::stop_controller::RxStopController;
923    use tokio::io::{AsyncReadExt, AsyncWriteExt};
924
925    #[test]
926    fn baud_rate_zero_rejected() {
927        assert!(matches!(
928            ensure_valid_baud_rate(0),
929            Err(SerialError::InvalidBaudRate(0))
930        ));
931    }
932
933    #[test]
934    fn baud_rate_over_max_rejected() {
935        assert!(matches!(
936            ensure_valid_baud_rate(MAX_BAUD_RATE + 1),
937            Err(SerialError::InvalidBaudRate(_))
938        ));
939    }
940
941    #[test]
942    fn baud_rate_within_range_accepted() {
943        assert!(ensure_valid_baud_rate(115200).is_ok());
944        assert!(ensure_valid_baud_rate(1).is_ok());
945        assert!(ensure_valid_baud_rate(MAX_BAUD_RATE).is_ok());
946    }
947
948    #[tokio::test]
949    async fn write_pushes_bytes_to_peer() {
950        let (conn, mut peer) = loopback_connection("test");
951        let n = conn.write(b"hello").await.unwrap();
952        assert_eq!(n, 5);
953        let mut buf = [0u8; 5];
954        peer.read_exact(&mut buf).await.unwrap();
955        assert_eq!(&buf, b"hello");
956    }
957
958    #[tokio::test]
959    async fn read_returns_peer_bytes() {
960        let (conn, mut peer) = loopback_connection("test");
961        peer.write_all(b"world").await.unwrap();
962        let mut buf = [0u8; 5];
963        let n = conn.read(&mut buf, Some(500)).await.unwrap();
964        assert_eq!(n, 5);
965        assert_eq!(&buf, b"world");
966    }
967
968    #[tokio::test]
969    async fn read_times_out_when_no_data() {
970        let (conn, _peer) = loopback_connection("test");
971        let mut buf = [0u8; 16];
972        let result = conn.read(&mut buf, Some(40)).await;
973        assert!(matches!(result, Err(SerialError::ReadTimeout)));
974    }
975
976    #[tokio::test]
977    async fn flush_set_dtr_rts_send_break_are_noops_on_loopback() {
978        let (conn, _peer) = loopback_connection("test");
979        conn.flush_buffers(FlushTarget::Both).await.unwrap();
980        conn.set_dtr_rts(true, false).await.unwrap();
981        conn.send_break(15).await.unwrap();
982    }
983
984    #[tokio::test]
985    async fn close_cancels_inflight_read() {
986        let mgr = ConnectionManager::new();
987        let (conn, _peer) = loopback_connection("port-read-close");
988        let id = mgr.insert(conn).await.unwrap();
989        let connection = mgr.get(&id).await.unwrap();
990
991        let reader = tokio::spawn(async move {
992            let mut buf = [0u8; 16];
993            connection.read(&mut buf, Some(2_000)).await
994        });
995
996        tokio::time::sleep(Duration::from_millis(100)).await;
997        mgr.close(&id).await.unwrap();
998
999        let err = reader.await.unwrap().unwrap_err();
1000        assert!(matches!(err, SerialError::ConnectionClosed(_)));
1001    }
1002
1003    #[test]
1004    fn disconnect_state_maps_connection_state_correctly() {
1005        use crate::tools::rx_consume::{disconnect_state, DisconnectState};
1006        use std::time::Instant;
1007
1008        let (mut conn, _peer) = loopback_connection("test");
1009        let mut ctrl = RxStopController::new(Instant::now(), Some(5000), 0, None);
1010
1011        // Open → Active.
1012        assert!(matches!(
1013            disconnect_state(&conn, &mut ctrl),
1014            DisconnectState::Active
1015        ));
1016
1017        // Set state to Closed → Closed.
1018        conn.set_state_for_test(ConnectionState::Closed);
1019        assert!(matches!(
1020            disconnect_state(&conn, &mut ctrl),
1021            DisconnectState::Closed
1022        ));
1023
1024        // Set state to Reconnecting with reconnect enabled → Reconnecting.
1025        // Note: constructing a Reconnecting state requires a real serial port
1026        // (the reconnect state machine drives it), so this test directly sets
1027        // the internal state and enable flag.
1028        conn.set_state_for_test(ConnectionState::Reconnecting);
1029        conn.reconnect_policy.lock().unwrap().enabled = true;
1030        assert!(matches!(
1031            disconnect_state(&conn, &mut ctrl),
1032            DisconnectState::Reconnecting
1033        ));
1034
1035        // Reconnecting with reconnect disabled → Closed.
1036        conn.reconnect_policy.lock().unwrap().enabled = false;
1037        assert!(matches!(
1038            disconnect_state(&conn, &mut ctrl),
1039            DisconnectState::Closed
1040        ));
1041    }
1042}