serial-mcp 0.4.2

MCP server for serial port communication. 13 tools (open/read/read_line/write/wait_for/subscribe/...), resources, prompts, task cancellation, stdio + streamable-HTTP transports.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
//! Serial port discovery, configuration, and a session-less connection manager.
//!
//! Public surface:
//! - [`PortInfo::list_available`] enumerates serial ports on the host.
//! - [`SerialConnection::open`] opens a single configured port.
//! - [`ConnectionManager`] holds a set of open connections indexed by id and
//!   rejects double-opens of the same port.

use std::collections::{HashMap, HashSet};
use std::fmt;
use std::sync::{Arc, Mutex as StdMutex};
use std::time::{Duration, Instant};

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serialport::{available_ports, SerialPortInfo, SerialPortType};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::sync::Mutex;
use tokio::time::timeout;
use tokio_serial::{ClearBuffer, SerialPort, SerialPortBuilderExt, SerialStream};
use uuid::Uuid;

use crate::error::{Result, SerialError};

/// Largest baud rate accepted by [`SerialConnection::open`]. Anything higher
/// is treated as a typo or accidental overflow and rejected.
pub const MAX_BAUD_RATE: u32 = 4_000_000;

// ---- Configuration enums -----------------------------------------------------

#[derive(Debug, Clone, Copy, Deserialize, JsonSchema)]
pub enum DataBits {
    #[serde(rename = "5")]
    Five,
    #[serde(rename = "6")]
    Six,
    #[serde(rename = "7")]
    Seven,
    #[serde(rename = "8")]
    Eight,
}

impl From<DataBits> for serialport::DataBits {
    fn from(value: DataBits) -> Self {
        match value {
            DataBits::Five => Self::Five,
            DataBits::Six => Self::Six,
            DataBits::Seven => Self::Seven,
            DataBits::Eight => Self::Eight,
        }
    }
}

#[derive(Debug, Clone, Copy, Deserialize, JsonSchema)]
pub enum StopBits {
    #[serde(rename = "1")]
    One,
    #[serde(rename = "2")]
    Two,
}

impl From<StopBits> for serialport::StopBits {
    fn from(value: StopBits) -> Self {
        match value {
            StopBits::One => Self::One,
            StopBits::Two => Self::Two,
        }
    }
}

#[derive(Debug, Clone, Copy, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum Parity {
    None,
    Odd,
    Even,
}

impl From<Parity> for serialport::Parity {
    fn from(value: Parity) -> Self {
        match value {
            Parity::None => Self::None,
            Parity::Odd => Self::Odd,
            Parity::Even => Self::Even,
        }
    }
}

#[derive(Debug, Clone, Copy, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum FlowControl {
    None,
    Software,
    Hardware,
}

impl From<FlowControl> for serialport::FlowControl {
    fn from(value: FlowControl) -> Self {
        match value {
            FlowControl::None => Self::None,
            FlowControl::Software => Self::Software,
            FlowControl::Hardware => Self::Hardware,
        }
    }
}

/// Concrete parameters required to open a serial port.
#[derive(Debug, Clone, JsonSchema)]
pub struct ConnectionConfig {
    pub port: String,
    pub baud_rate: u32,
    pub data_bits: DataBits,
    pub stop_bits: StopBits,
    pub parity: Parity,
    pub flow_control: FlowControl,
}

// ---- Port enumeration --------------------------------------------------------

/// Information about a serial port reported by the OS.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
pub struct PortInfo {
    pub name: String,
    pub description: String,
    pub hardware_id: Option<String>,
}

impl PortInfo {
    /// Enumerate all serial ports the operating system currently exposes.
    pub fn list_available() -> Result<Vec<PortInfo>> {
        let ports = available_ports()?;
        Ok(ports.into_iter().map(PortInfo::from_os).collect())
    }

    fn from_os(port: SerialPortInfo) -> Self {
        PortInfo {
            hardware_id: format_hardware_id(&port),
            description: describe_port(&port),
            name: port.port_name,
        }
    }
}

fn format_hardware_id(port: &SerialPortInfo) -> Option<String> {
    match &port.port_type {
        SerialPortType::UsbPort(info) => {
            Some(format!("USB VID:{:04X} PID:{:04X}", info.vid, info.pid))
        }
        SerialPortType::PciPort => Some("PCI".to_string()),
        SerialPortType::BluetoothPort => Some("Bluetooth".to_string()),
        SerialPortType::Unknown => None,
    }
}

fn describe_port(port: &SerialPortInfo) -> String {
    match &port.port_type {
        SerialPortType::UsbPort(info) => format!(
            "{} {}",
            info.manufacturer.as_deref().unwrap_or("Unknown"),
            info.product.as_deref().unwrap_or("USB Serial Device")
        ),
        SerialPortType::PciPort => "PCI Serial Port".to_string(),
        SerialPortType::BluetoothPort => "Bluetooth Serial Port".to_string(),
        SerialPortType::Unknown => "Serial Port".to_string(),
    }
}

// ---- I/O backend trait -------------------------------------------------------

/// Abstraction over the underlying byte stream plus the modem-control lines
/// of a serial port.
///
/// The production backend ([`SerialStream`]) talks to a real OS-level
/// serial port. Tests substitute an in-memory implementation backed by
/// [`tokio::io::duplex`] so that read/write/wait_for can be exercised
/// without any hardware.
///
/// Control-line operations (`clear_os_buffers`, `set_dtr_rts`,
/// `set_break_state`) are required methods so the trait can stay
/// object-safe even when the backend doesn't have a real port behind it;
/// in-memory backends typically implement them as no-ops.
pub trait SerialIo: AsyncRead + AsyncWrite + Send + Unpin {
    fn clear_os_buffers(&self, target: FlushTarget) -> std::io::Result<()>;
    fn set_dtr_rts(&mut self, dtr: bool, rts: bool) -> std::io::Result<()>;
    fn set_break_state(&self, asserted: bool) -> std::io::Result<()>;
}

impl SerialIo for SerialStream {
    fn clear_os_buffers(&self, target: FlushTarget) -> std::io::Result<()> {
        self.clear(target.into()).map_err(io_error_from_serialport)
    }

    fn set_dtr_rts(&mut self, dtr: bool, rts: bool) -> std::io::Result<()> {
        self.write_data_terminal_ready(dtr)
            .map_err(io_error_from_serialport)?;
        self.write_request_to_send(rts)
            .map_err(io_error_from_serialport)
    }

    fn set_break_state(&self, asserted: bool) -> std::io::Result<()> {
        if asserted {
            self.set_break().map_err(io_error_from_serialport)
        } else {
            self.clear_break().map_err(io_error_from_serialport)
        }
    }
}

fn io_error_from_serialport(err: serialport::Error) -> std::io::Error {
    std::io::Error::other(err.to_string())
}

// ---- Single open connection --------------------------------------------------

/// A single open serial port. Cheap to clone via [`Arc`] because all state lives
/// behind a [`Mutex`].
pub struct SerialConnection {
    id: String,
    port: String,
    rx_owner: StdMutex<Option<&'static str>>,
    state: Mutex<SerialState>,
}

#[derive(Debug)]
pub struct SerialRxLease {
    connection: Arc<SerialConnection>,
    owner: &'static str,
}

impl Drop for SerialRxLease {
    fn drop(&mut self) {
        if let Ok(mut current) = self.connection.rx_owner.lock() {
            if current.as_ref() == Some(&self.owner) {
                *current = None;
            }
        }
    }
}

struct SerialState {
    io: Box<dyn SerialIo>,
    unread: Vec<u8>,
}

impl fmt::Debug for SerialConnection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SerialConnection")
            .field("id", &self.id)
            .field("port", &self.port)
            .finish()
    }
}

impl SerialConnection {
    /// Open a serial port using the supplied configuration.
    pub async fn open(config: ConnectionConfig) -> Result<Self> {
        ensure_valid_baud_rate(config.baud_rate)?;
        let stream = build_stream(&config)?;
        Ok(Self::from_io(config.port, Box::new(stream)))
    }

    /// Build a connection from an arbitrary [`SerialIo`] backend. Used by
    /// tests to inject an in-memory duplex stream.
    pub fn from_io(port: String, io: Box<dyn SerialIo>) -> Self {
        Self {
            id: Uuid::new_v4().to_string(),
            port,
            rx_owner: StdMutex::new(None),
            state: Mutex::new(SerialState {
                io,
                unread: Vec::new(),
            }),
        }
    }

    pub fn id(&self) -> &str {
        &self.id
    }

    pub fn port(&self) -> &str {
        &self.port
    }

    pub fn acquire_rx(
        connection: &Arc<Self>,
        owner: &'static str,
    ) -> std::result::Result<SerialRxLease, String> {
        let mut current = connection.rx_owner.lock().map_err(|_| {
            format!(
                "Connection busy: failed to inspect RX owner on {}",
                connection.id
            )
        })?;

        if let Some(active_owner) = *current {
            return Err(format!("Connection busy: {active_owner} already owns RX"));
        }

        *current = Some(owner);
        Ok(SerialRxLease {
            connection: Arc::clone(connection),
            owner,
        })
    }

    /// Write a byte slice, flushing before returning.
    pub async fn write(&self, data: &[u8]) -> Result<usize> {
        let mut state = self.state.lock().await;
        let written = state.io.write(data).await?;
        state.io.flush().await?;
        Ok(written)
    }

    fn read_from_unread(state: &mut SerialState, dst: &mut [u8]) -> usize {
        let to_copy = dst.len().min(state.unread.len());
        if to_copy == 0 {
            return 0;
        }

        dst[..to_copy].copy_from_slice(&state.unread[..to_copy]);
        state.unread.drain(..to_copy);
        to_copy
    }

    /// Read up to `dst.len()` bytes. Returns [`SerialError::ReadTimeout`] if
    /// `timeout_ms` is set and elapses before any byte arrives.
    ///
    /// When a timeout is given, the lock on the underlying IO is held for at
    /// most `POLL_MS` milliseconds at a time and released between polls.  This
    /// lets concurrent `write` calls on the same connection proceed without
    /// waiting for the full read timeout — which is essential for the
    /// request/response pattern (`wait_for` + `write`) on CDC-ACM devices.
    pub async fn read(&self, dst: &mut [u8], timeout_ms: Option<u64>) -> Result<usize> {
        const POLL_MS: u64 = 50;

        {
            let mut state = self.state.lock().await;
            let unread = Self::read_from_unread(&mut state, dst);
            if unread > 0 {
                return Ok(unread);
            }
        }

        match timeout_ms {
            None => Ok(self.state.lock().await.io.read(dst).await?),
            Some(ms) => {
                let deadline = Instant::now() + Duration::from_millis(ms);
                loop {
                    let remaining = deadline.saturating_duration_since(Instant::now());
                    if remaining.is_zero() {
                        return Err(SerialError::ReadTimeout);
                    }
                    let poll_dur = remaining.min(Duration::from_millis(POLL_MS));
                    {
                        let mut state = self.state.lock().await;
                        let unread = Self::read_from_unread(&mut state, dst);
                        if unread > 0 {
                            return Ok(unread);
                        }

                        match timeout(poll_dur, state.io.read(dst)).await {
                            Ok(Ok(n)) if n > 0 => return Ok(n),
                            Ok(Ok(_)) => {}
                            Ok(Err(e)) => return Err(SerialError::from(e)),
                            Err(_elapsed) => {}
                        }
                    }
                    // Yield to allow the I/O driver time to process epoll events
                    // before re-acquiring the mutex for the next poll.
                    tokio::time::sleep(Duration::from_millis(5)).await;
                }
            }
        }
    }

    /// Read up to `max_bytes` with a brief timeout (100ms) to capture any
    /// immediately available data without blocking long.
    pub async fn read_latest(&self, max_bytes: usize) -> Result<Vec<u8>> {
        let mut buf = vec![0u8; max_bytes];
        let n = self.read(&mut buf, Some(100)).await?;
        buf.truncate(n);
        Ok(buf)
    }

    pub async fn unread(&self, data: &[u8]) {
        if data.is_empty() {
            return;
        }

        let mut state = self.state.lock().await;
        state.unread.extend_from_slice(data);
    }

    /// Discard data buffered in the OS for the input, output, or both
    /// directions of this port.
    pub async fn flush_buffers(&self, target: FlushTarget) -> Result<()> {
        let mut state = self.state.lock().await;
        if matches!(target, FlushTarget::Input | FlushTarget::Both) {
            state.unread.clear();
        }
        state.io.clear_os_buffers(target).map_err(SerialError::from)
    }

    /// Drive the DTR and RTS control lines. Common use case: pulse DTR low
    /// to soft-reset an Arduino, or hold both low to enter the ESP32
    /// bootloader.
    pub async fn set_dtr_rts(&self, dtr: bool, rts: bool) -> Result<()> {
        let mut state = self.state.lock().await;
        state.io.set_dtr_rts(dtr, rts).map_err(SerialError::from)
    }

    /// Set the BREAK condition on the TX line.
    pub async fn set_break_state(&self, enabled: bool) -> Result<()> {
        let state = self.state.lock().await;
        state.io.set_break_state(enabled).map_err(SerialError::from)
    }

    /// Assert the BREAK condition on the TX line for `duration_ms`
    /// milliseconds, then release it.
    pub async fn send_break(&self, duration_ms: u64) -> Result<()> {
        self.set_break_state(true).await?;
        tokio::time::sleep(Duration::from_millis(duration_ms)).await;
        self.set_break_state(false).await
    }
}

/// Which OS-side buffer(s) a flush should clear.
#[derive(Debug, Clone, Copy, Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum FlushTarget {
    /// Bytes the OS has received from the device but the app has not yet read.
    Input,
    /// Bytes the app has queued but the OS has not yet sent to the device.
    Output,
    /// Both input and output buffers.
    Both,
}

impl From<FlushTarget> for ClearBuffer {
    fn from(value: FlushTarget) -> Self {
        match value {
            FlushTarget::Input => ClearBuffer::Input,
            FlushTarget::Output => ClearBuffer::Output,
            FlushTarget::Both => ClearBuffer::All,
        }
    }
}

fn ensure_valid_baud_rate(baud_rate: u32) -> Result<()> {
    if baud_rate == 0 || baud_rate > MAX_BAUD_RATE {
        Err(SerialError::InvalidBaudRate(baud_rate))
    } else {
        Ok(())
    }
}

fn build_stream(config: &ConnectionConfig) -> Result<SerialStream> {
    tokio_serial::new(&config.port, config.baud_rate)
        .data_bits(config.data_bits.into())
        .stop_bits(config.stop_bits.into())
        .parity(config.parity.into())
        .flow_control(config.flow_control.into())
        .open_native_async()
        .map_err(|e| SerialError::OpenFailed(format!("{}: {}", config.port, e)))
}

// ---- Multi-connection registry ----------------------------------------------

/// Registry of currently open serial connections, indexed by an opaque
/// connection id. Rejects opening the same port twice.
#[derive(Debug, Default)]
pub struct ConnectionManager {
    state: Mutex<ConnectionRegistry>,
}

#[derive(Debug, Default)]
struct ConnectionRegistry {
    connections: HashMap<String, Arc<SerialConnection>>,
    opening_ports: HashSet<String>,
}

impl ConnectionManager {
    pub fn new() -> Self {
        Self::default()
    }

    /// Open a new connection and store it. Returns the new connection id.
    pub async fn open(&self, config: ConnectionConfig) -> Result<String> {
        let port = config.port.clone();
        {
            let mut state = self.state.lock().await;
            if is_port_in_use(&state.connections, &port) || state.opening_ports.contains(&port) {
                return Err(SerialError::PortAlreadyOpen(port));
            }
            state.opening_ports.insert(port.clone());
        }

        let opened = SerialConnection::open(config).await;
        let mut state = self.state.lock().await;
        state.opening_ports.remove(&port);
        let connection = Arc::new(opened?);
        let id = connection.id().to_string();
        state.connections.insert(id.clone(), connection);
        Ok(id)
    }

    /// Insert an already-built [`SerialConnection`] (typically one backed
    /// by an in-memory loopback) into the registry. Honours the same
    /// port-uniqueness invariant as [`Self::open`].
    ///
    /// Exposed for integration tests that want to drive the MCP surface
    /// against a fake connection without going through the OS serial layer.
    pub async fn insert(&self, connection: SerialConnection) -> Result<String> {
        let mut state = self.state.lock().await;
        if is_port_in_use(&state.connections, connection.port())
            || state.opening_ports.contains(connection.port())
        {
            return Err(SerialError::PortAlreadyOpen(connection.port().to_string()));
        }
        let id = connection.id().to_string();
        state.connections.insert(id.clone(), Arc::new(connection));
        Ok(id)
    }

    /// Remove a connection. The serial port is closed when the last [`Arc`]
    /// reference is dropped, which happens here if no caller still holds one.
    pub async fn close(&self, id: &str) -> Result<()> {
        self.state
            .lock()
            .await
            .connections
            .remove(id)
            .ok_or_else(|| SerialError::ConnectionNotFound(id.to_string()))?;
        Ok(())
    }

    /// Look up an existing connection by id.
    pub async fn get(&self, id: &str) -> Result<Arc<SerialConnection>> {
        self.state
            .lock()
            .await
            .connections
            .get(id)
            .cloned()
            .ok_or_else(|| SerialError::ConnectionNotFound(id.to_string()))
    }

    /// Number of currently open connections.
    pub async fn count(&self) -> usize {
        self.state.lock().await.connections.len()
    }

    /// Lightweight snapshot of all currently-open connections. Cheap because
    /// it only clones the id + port pair, not the underlying IO.
    pub async fn list_open(&self) -> Vec<ConnectionSummary> {
        self.state
            .lock()
            .await
            .connections
            .values()
            .map(|c| ConnectionSummary {
                connection_id: c.id().to_string(),
                port: c.port().to_string(),
            })
            .collect()
    }
}

/// Public-facing summary of an open connection.
#[derive(Debug, Clone, Serialize, JsonSchema)]
pub struct ConnectionSummary {
    pub connection_id: String,
    pub port: String,
}

fn is_port_in_use(connections: &HashMap<String, Arc<SerialConnection>>, port: &str) -> bool {
    connections.values().any(|c| c.port() == port)
}

// ---- Test support ----------------------------------------------------------

/// In-memory implementations of [`SerialIo`] used by unit and integration
/// tests that need a fake connection. The module is `pub` so that
/// integration tests in `tests/` can build a [`SerialConnection`] backed
/// by a [`tokio::io::DuplexStream`] without going through the OS serial
/// layer.
pub mod test_support {
    use std::pin::Pin;
    use std::task::{Context, Poll};

    use tokio::io::{DuplexStream, ReadBuf};

    use super::*;

    /// Wraps a [`DuplexStream`] half so it satisfies the [`SerialIo`] trait.
    /// All control-line operations are no-ops.
    pub struct LoopbackIo(DuplexStream);

    impl AsyncRead for LoopbackIo {
        fn poll_read(
            mut self: Pin<&mut Self>,
            cx: &mut Context<'_>,
            buf: &mut ReadBuf<'_>,
        ) -> Poll<std::io::Result<()>> {
            Pin::new(&mut self.0).poll_read(cx, buf)
        }
    }

    impl AsyncWrite for LoopbackIo {
        fn poll_write(
            mut self: Pin<&mut Self>,
            cx: &mut Context<'_>,
            buf: &[u8],
        ) -> Poll<std::io::Result<usize>> {
            Pin::new(&mut self.0).poll_write(cx, buf)
        }

        fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
            Pin::new(&mut self.0).poll_flush(cx)
        }

        fn poll_shutdown(
            mut self: Pin<&mut Self>,
            cx: &mut Context<'_>,
        ) -> Poll<std::io::Result<()>> {
            Pin::new(&mut self.0).poll_shutdown(cx)
        }
    }

    impl SerialIo for LoopbackIo {
        fn clear_os_buffers(&self, _target: FlushTarget) -> std::io::Result<()> {
            Ok(())
        }
        fn set_dtr_rts(&mut self, _dtr: bool, _rts: bool) -> std::io::Result<()> {
            Ok(())
        }
        fn set_break_state(&self, _asserted: bool) -> std::io::Result<()> {
            Ok(())
        }
    }

    /// Build an in-memory connection plus the peer end of the duplex.
    /// The peer can be driven directly by the test to push bytes into the
    /// connection's read side or to consume bytes the connection writes.
    pub fn loopback_connection(port: &str) -> (SerialConnection, DuplexStream) {
        let (a, b) = tokio::io::duplex(4096);
        let conn = SerialConnection::from_io(port.to_string(), Box::new(LoopbackIo(a)));
        (conn, b)
    }
}

#[cfg(test)]
mod tests {
    use super::test_support::loopback_connection;
    use super::*;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    #[test]
    fn baud_rate_zero_rejected() {
        assert!(matches!(
            ensure_valid_baud_rate(0),
            Err(SerialError::InvalidBaudRate(0))
        ));
    }

    #[test]
    fn baud_rate_over_max_rejected() {
        assert!(matches!(
            ensure_valid_baud_rate(MAX_BAUD_RATE + 1),
            Err(SerialError::InvalidBaudRate(_))
        ));
    }

    #[test]
    fn baud_rate_within_range_accepted() {
        assert!(ensure_valid_baud_rate(115200).is_ok());
        assert!(ensure_valid_baud_rate(1).is_ok());
        assert!(ensure_valid_baud_rate(MAX_BAUD_RATE).is_ok());
    }

    #[tokio::test]
    async fn write_pushes_bytes_to_peer() {
        let (conn, mut peer) = loopback_connection("test");
        let n = conn.write(b"hello").await.unwrap();
        assert_eq!(n, 5);
        let mut buf = [0u8; 5];
        peer.read_exact(&mut buf).await.unwrap();
        assert_eq!(&buf, b"hello");
    }

    #[tokio::test]
    async fn read_returns_peer_bytes() {
        let (conn, mut peer) = loopback_connection("test");
        peer.write_all(b"world").await.unwrap();
        let mut buf = [0u8; 5];
        let n = conn.read(&mut buf, Some(500)).await.unwrap();
        assert_eq!(n, 5);
        assert_eq!(&buf, b"world");
    }

    #[tokio::test]
    async fn read_times_out_when_no_data() {
        let (conn, _peer) = loopback_connection("test");
        let mut buf = [0u8; 16];
        let result = conn.read(&mut buf, Some(40)).await;
        assert!(matches!(result, Err(SerialError::ReadTimeout)));
    }

    #[tokio::test]
    async fn flush_set_dtr_rts_send_break_are_noops_on_loopback() {
        let (conn, _peer) = loopback_connection("test");
        conn.flush_buffers(FlushTarget::Both).await.unwrap();
        conn.set_dtr_rts(true, false).await.unwrap();
        conn.send_break(15).await.unwrap();
    }

    #[tokio::test]
    async fn unread_bytes_are_returned_before_os_reads() {
        let (conn, mut peer) = loopback_connection("test");
        conn.unread(b"hello").await;
        peer.write_all(b"world").await.unwrap();

        let mut buf = [0u8; 5];
        let n = conn.read(&mut buf, Some(100)).await.unwrap();
        assert_eq!(n, 5);
        assert_eq!(&buf, b"hello");

        let n = conn.read(&mut buf, Some(100)).await.unwrap();
        assert_eq!(n, 5);
        assert_eq!(&buf, b"world");
    }

    #[tokio::test]
    async fn flush_input_clears_unread_bytes() {
        let (conn, _peer) = loopback_connection("test");
        conn.unread(b"stale").await;
        conn.flush_buffers(FlushTarget::Input).await.unwrap();

        let mut buf = [0u8; 5];
        let result = conn.read(&mut buf, Some(40)).await;
        assert!(matches!(result, Err(SerialError::ReadTimeout)));
    }

    #[tokio::test]
    async fn acquire_rx_reports_owner_and_releases_on_drop() {
        let (conn, _peer) = loopback_connection("test");
        let conn = Arc::new(conn);

        let lease = SerialConnection::acquire_rx(&conn, "subscribe").unwrap();
        let err = SerialConnection::acquire_rx(&conn, "read").unwrap_err();
        assert_eq!(err, "Connection busy: subscribe already owns RX");

        drop(lease);

        SerialConnection::acquire_rx(&conn, "read").unwrap();
    }

    #[tokio::test]
    async fn manager_rejects_duplicate_port() {
        let mgr = ConnectionManager::new();
        let (c1, _p1) = loopback_connection("port-a");
        mgr.insert(c1).await.unwrap();
        let (c2, _p2) = loopback_connection("port-a");
        let err = mgr.insert(c2).await.unwrap_err();
        assert!(matches!(err, SerialError::PortAlreadyOpen(_)));
    }

    #[tokio::test]
    async fn manager_close_then_get_returns_connection_not_found() {
        let mgr = ConnectionManager::new();
        let (c, _p) = loopback_connection("port-z");
        let id = mgr.insert(c).await.unwrap();
        mgr.close(&id).await.unwrap();
        let err = mgr.get(&id).await.unwrap_err();
        assert!(matches!(err, SerialError::ConnectionNotFound(_)));
    }

    #[tokio::test]
    async fn manager_get_unknown_id_returns_connection_not_found() {
        let mgr = ConnectionManager::new();
        let err = mgr.get("does-not-exist").await.unwrap_err();
        assert!(matches!(err, SerialError::ConnectionNotFound(_)));
    }
}