serial-mcp 0.7.2

MCP server for serial port communication. 22 tools (list/open/read/write/subscribe/get_status/reconfigure/list_profiles/open_profile/save_profile/delete_profile/get_log/clear_log/export_log/reconnect/...), 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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
//! 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::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
use std::sync::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 tokio_util::sync::CancellationToken;
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, Serialize, 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,
        }
    }
}

pub(crate) fn data_bits_to_str(d: DataBits) -> String {
    match d {
        DataBits::Five => "5".into(),
        DataBits::Six => "6".into(),
        DataBits::Seven => "7".into(),
        DataBits::Eight => "8".into(),
    }
}

pub(crate) fn stop_bits_to_str(s: StopBits) -> String {
    match s {
        StopBits::One => "1".into(),
        StopBits::Two => "2".into(),
    }
}

pub(crate) fn parity_to_str(p: Parity) -> String {
    match p {
        Parity::None => "none".into(),
        Parity::Odd => "odd".into(),
        Parity::Even => "even".into(),
    }
}

pub(crate) fn flow_control_to_str(f: FlowControl) -> String {
    match f {
        FlowControl::None => "none".into(),
        FlowControl::Software => "software".into(),
        FlowControl::Hardware => "hardware".into(),
    }
}

// ---- String parsing (single source of truth) --------------------------------

impl std::str::FromStr for DataBits {
    type Err = String;
    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "5" => Ok(DataBits::Five),
            "6" => Ok(DataBits::Six),
            "7" => Ok(DataBits::Seven),
            "8" => Ok(DataBits::Eight),
            other => Err(format!("Invalid data_bits {other:?} (expected 5/6/7/8)")),
        }
    }
}

impl std::str::FromStr for StopBits {
    type Err = String;
    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "1" => Ok(StopBits::One),
            "2" => Ok(StopBits::Two),
            other => Err(format!("Invalid stop_bits {other:?} (expected 1/2)")),
        }
    }
}

impl std::str::FromStr for Parity {
    type Err = String;
    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "none" => Ok(Parity::None),
            "odd" => Ok(Parity::Odd),
            "even" => Ok(Parity::Even),
            other => Err(format!("Invalid parity {other:?} (expected none/odd/even)")),
        }
    }
}

impl std::str::FromStr for FlowControl {
    type Err = String;
    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "none" => Ok(FlowControl::None),
            "software" => Ok(FlowControl::Software),
            "hardware" => Ok(FlowControl::Hardware),
            other => Err(format!(
                "Invalid flow_control {other:?} (expected none/software/hardware)"
            )),
        }
    }
}

/// Concrete parameters required to open a serial port.
#[derive(Debug, Clone, JsonSchema)]
pub struct ConnectionConfig {
    pub port: String,
    pub name: Option<String>,
    pub baud_rate: u32,
    pub data_bits: DataBits,
    pub stop_bits: StopBits,
    pub parity: Parity,
    pub flow_control: FlowControl,
    /// OS-level port identity (VID, PID, serial, transport, etc.)
    /// Captured at open time for status and profile save operations.
    pub port_info: Option<PortInfo>,
    /// Log buffer capacity in events. 0 or None disables logging.
    /// Default: 1024.
    #[serde(default = "default_log_capacity")]
    #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
    pub log_capacity: usize,
    /// Whether logging is enabled. Default: true when capacity > 0.
    #[serde(default = "default_true")]
    pub log_enabled: bool,
    /// Default TX framing applied when `write` omits `tx_framing`.
    #[serde(default)]
    pub tx_framing: Option<crate::framing::TxFramingConfig>,
    /// Default RX framing applied when `read`/`subscribe` omit `rx_framing`.
    #[serde(default)]
    pub rx_framing: Option<crate::framing::RxFramingConfig>,
    /// Default RX parser applied when `read`/`subscribe` omit `rx_parser`.
    #[serde(default)]
    pub rx_parser: Option<crate::framing::ParserConfig>,
    /// Default protocol preset. Expands to fill framing/parser gaps.
    #[serde(default)]
    pub protocol: Option<crate::framing::ProtocolPreset>,
}

fn default_log_capacity() -> usize {
    1024
}

fn default_true() -> bool {
    true
}

// ---- Connection state -------------------------------------------------------

/// The health state of a live serial connection.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ConnectionState {
    Open,
    Disconnected,
    Reconnecting,
    Closed,
}

impl ConnectionState {
    pub fn is_healthy(&self) -> bool {
        matches!(self, ConnectionState::Open)
    }
}

/// Reconnect policy for a connection. When enabled and the port
/// disappears, the server will try to re-establish the connection
/// automatically with exponential backoff.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ReconnectPolicy {
    /// Enable automatic reconnect. Default: false.
    #[serde(default)]
    pub enabled: bool,
    /// Maximum reconnect attempts. 0 = unlimited. Default: 10.
    #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
    #[serde(default = "default_max_reconnect_attempts")]
    pub max_attempts: u32,
    /// Initial delay between reconnect attempts in milliseconds. Default: 500.
    #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
    #[serde(default = "default_initial_reconnect_delay_ms")]
    pub initial_delay_ms: u64,
    /// Maximum delay between attempts in milliseconds. Default: 30000.
    #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
    #[serde(default = "default_max_reconnect_delay_ms")]
    pub max_delay_ms: u64,
    /// Backoff multiplier. Default: 2.0.
    #[serde(default = "default_backoff_multiplier")]
    pub backoff_multiplier: f64,
}

impl Default for ReconnectPolicy {
    fn default() -> Self {
        Self {
            enabled: false,
            max_attempts: 10,
            initial_delay_ms: 500,
            max_delay_ms: 30_000,
            backoff_multiplier: 2.0,
        }
    }
}

fn default_max_reconnect_attempts() -> u32 {
    10
}
fn default_initial_reconnect_delay_ms() -> u64 {
    500
}
fn default_max_reconnect_delay_ms() -> u64 {
    30_000
}
fn default_backoff_multiplier() -> f64 {
    2.0
}

/// Classify an I/O error as a fatal disconnect (port vanished).
pub fn is_fatal_disconnect(err: &std::io::Error) -> bool {
    use std::io::ErrorKind;
    matches!(
        err.kind(),
        ErrorKind::NotFound
            | ErrorKind::PermissionDenied
            | ErrorKind::ConnectionReset
            | ErrorKind::ConnectionAborted
            | ErrorKind::BrokenPipe
            | ErrorKind::Interrupted
    )
}

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

/// Transport type observed on the host OS for a serial port.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum PortTransport {
    Usb,
    Pci,
    Bluetooth,
    Unknown,
}

impl std::fmt::Display for PortTransport {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PortTransport::Usb => f.write_str("usb"),
            PortTransport::Pci => f.write_str("pci"),
            PortTransport::Bluetooth => f.write_str("bluetooth"),
            PortTransport::Unknown => f.write_str("unknown"),
        }
    }
}

/// Information about a single serial port on the system.
///
/// Fields are populated from OS-level enumeration. USB ports carry
/// the richest identity; other transports provide more limited metadata.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
pub struct PortInfo {
    /// OS-level path, e.g. `/dev/ttyUSB0` or `COM3`.
    pub name: String,
    /// Short platform-local name, e.g. `ttyUSB0`.
    pub display_name: String,
    /// Human-readable description (manufacturer + product when available).
    pub description: String,
    /// Formatted hardware identifier string.
    pub hardware_id: Option<String>,
    /// Transport type — `usb`, `pci`, `bluetooth`, or `unknown`.
    pub transport: PortTransport,
    /// USB Vendor ID. `None` for non-USB ports.
    ///
    /// `#[schemars(schema_with = ...)]` overrides schemars so it emits
    /// `{"type": ["integer", "null"], "minimum": 0}` instead of the
    /// non-standard `"format": "uint16"` keyword. The `uint16` format is not
    /// part of the JSON Schema spec and is silently dropped by most
    /// validators (logging a warning per call). Every `Option<uN>`/`uN`
    /// field that derives `JsonSchema` MUST carry this override — see
    /// `src/schema_helpers.rs` and the regression test
    /// `serial::schema::no_nonstandard_uint_formats_in_all_public_schemas`.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[schemars(schema_with = "crate::schema_helpers::option_uint_schema")]
    pub vid: Option<u16>,
    /// USB Product ID. `None` for non-USB ports.
    ///
    /// See `vid` for why the `#[schemars(schema_with = ...)]` override is
    /// required on every unsigned-integer field that derives `JsonSchema`.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[schemars(schema_with = "crate::schema_helpers::option_uint_schema")]
    pub pid: Option<u16>,
    /// USB serial number string from the device descriptor.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub serial_number: Option<String>,
    /// USB manufacturer string.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub manufacturer: Option<String>,
    /// USB product string.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub product: Option<String>,
    /// USB interface index. `None` when not available or not a USB port.
    ///
    /// See `vid` for why the `#[schemars(schema_with = ...)]` override is
    /// required on every unsigned-integer field that derives `JsonSchema`.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[schemars(schema_with = "crate::schema_helpers::option_uint_schema")]
    pub interface: Option<u8>,
}

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 {
        let transport = transport_from_os(&port.port_type);
        let (vid, pid, serial_number, manufacturer, product, interface) =
            usb_fields(&port.port_type);
        let description = describe_port(&port);
        let hardware_id = format_hardware_id(&port);
        let display_name = short_display_name(&port.port_name);

        PortInfo {
            display_name,
            name: port.port_name,
            description,
            hardware_id,
            transport,
            vid,
            pid,
            serial_number,
            manufacturer,
            product,
            interface,
        }
    }
}

/// Extract the last path component or the full name when no separator exists.
fn short_display_name(port_name: &str) -> String {
    port_name
        .rsplit(&['/', '\\'][..])
        .next()
        .unwrap_or(port_name)
        .to_string()
}

fn transport_from_os(port_type: &SerialPortType) -> PortTransport {
    match port_type {
        SerialPortType::UsbPort(_) => PortTransport::Usb,
        SerialPortType::PciPort => PortTransport::Pci,
        SerialPortType::BluetoothPort => PortTransport::Bluetooth,
        SerialPortType::Unknown => PortTransport::Unknown,
    }
}

#[allow(clippy::type_complexity)]
fn usb_fields(
    port_type: &SerialPortType,
) -> (
    Option<u16>,
    Option<u16>,
    Option<String>,
    Option<String>,
    Option<String>,
    Option<u8>,
) {
    if let SerialPortType::UsbPort(info) = port_type {
        (
            Some(info.vid),
            Some(info.pid),
            info.serial_number.clone(),
            info.manufacturer.clone(),
            info.product.clone(),
            info.interface,
        )
    } else {
        (None, None, None, None, None, None)
    }
}

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_flow_control`, `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_flow_control(&mut self, flow_control: FlowControl) -> std::io::Result<()>;
    fn set_break_state(&self, asserted: bool) -> std::io::Result<()>;

    /// Reconfigure baud rate on an already-open port. Default is no-op
    /// for backends that don't support hardware reconfiguration.
    fn reconfigure_baud_rate(&mut self, _baud_rate: u32) -> std::io::Result<()> {
        Ok(())
    }

    /// Reconfigure data bits on an already-open port.
    fn reconfigure_data_bits(&mut self, _data_bits: serialport::DataBits) -> std::io::Result<()> {
        Ok(())
    }

    /// Reconfigure stop bits on an already-open port.
    fn reconfigure_stop_bits(&mut self, _stop_bits: serialport::StopBits) -> std::io::Result<()> {
        Ok(())
    }

    /// Reconfigure parity on an already-open port.
    fn reconfigure_parity(&mut self, _parity: serialport::Parity) -> std::io::Result<()> {
        Ok(())
    }
}

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_flow_control(&mut self, flow_control: FlowControl) -> std::io::Result<()> {
        SerialPort::set_flow_control(self, flow_control.into()).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 reconfigure_baud_rate(&mut self, baud_rate: u32) -> std::io::Result<()> {
        SerialPort::set_baud_rate(self, baud_rate).map_err(io_error_from_serialport)
    }

    fn reconfigure_data_bits(&mut self, data_bits: serialport::DataBits) -> std::io::Result<()> {
        SerialPort::set_data_bits(self, data_bits).map_err(io_error_from_serialport)
    }

    fn reconfigure_stop_bits(&mut self, stop_bits: serialport::StopBits) -> std::io::Result<()> {
        SerialPort::set_stop_bits(self, stop_bits).map_err(io_error_from_serialport)
    }

    fn reconfigure_parity(&mut self, parity: serialport::Parity) -> std::io::Result<()> {
        SerialPort::set_parity(self, parity).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,
    name: Option<String>,
    baud_rate: StdMutex<u32>,
    data_bits: StdMutex<DataBits>,
    stop_bits: StdMutex<StopBits>,
    parity: StdMutex<Parity>,
    flow_control: StdMutex<FlowControl>,
    io: Mutex<Option<Box<dyn SerialIo>>>,
    close_token: CancellationToken,
    closed: AtomicBool,
    /// Total bytes written to the device via the `write` tool.
    tx_bytes: AtomicU64,
    /// Total bytes read from the device and delivered through any RX path.
    rx_bytes: AtomicU64,
    /// Wall-clock time of the last rx or tx byte operation.
    last_activity: StdMutex<Option<std::time::SystemTime>>,
    /// Number of successful `read` or `subscribe` operations.
    read_ops: AtomicU64,
    /// Number of successful `write` operations.
    write_ops: AtomicU64,
    /// Number of RX operations where data was truncated
    /// (bytes_returned < bytes_observed).
    truncation_count: AtomicU64,
    /// Number of notification drops (encoding errors or disconnected peers).
    notification_drop_count: AtomicU64,
    /// OS-level port identity captured at open time.
    port_info: Option<PortInfo>,
    /// Per-connection event log buffer.
    log: Arc<crate::log_buffer::LogBuffer>,
    /// Current connection health state.
    state: StdMutex<ConnectionState>,
    /// Reconnect policy for this connection.
    pub(crate) reconnect_policy: StdMutex<ReconnectPolicy>,
    /// Count of reconnect attempts since the last disconnect.
    reconnect_attempts: AtomicU64,
    /// Last fatal I/O error message and timestamp.
    last_error: StdMutex<Option<(std::time::SystemTime, String)>>,
    /// Default TX framing from profile/open call.
    tx_framing_default: Option<crate::framing::TxFramingConfig>,
    /// Default RX framing from profile/open call.
    rx_framing_default: Option<crate::framing::RxFramingConfig>,
    /// Default RX parser from profile/open call.
    rx_parser_default: Option<crate::framing::ParserConfig>,
    /// Default protocol preset from profile/open call.
    protocol_default: Option<crate::framing::ProtocolPreset>,
}

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)
            .field("name", &self.name)
            .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_with_config(config, 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::from_io_with_config(
            ConnectionConfig {
                port,
                name: None,
                baud_rate: 115200,
                data_bits: DataBits::Eight,
                stop_bits: StopBits::One,
                parity: Parity::None,
                flow_control: FlowControl::None,
                port_info: None,
                log_capacity: 1024,
                log_enabled: true,
                tx_framing: None,
                rx_framing: None,
                rx_parser: None,
                protocol: None,
            },
            io,
        )
    }

    pub fn from_io_with_config(config: ConnectionConfig, io: Box<dyn SerialIo>) -> Self {
        let log = crate::log_buffer::LogBuffer::new_shared(config.log_capacity, config.log_enabled);
        log.opened();
        Self {
            id: Uuid::new_v4().to_string(),
            port: config.port,
            name: config.name,
            baud_rate: StdMutex::new(config.baud_rate),
            data_bits: StdMutex::new(config.data_bits),
            stop_bits: StdMutex::new(config.stop_bits),
            parity: StdMutex::new(config.parity),
            flow_control: StdMutex::new(config.flow_control),
            io: Mutex::new(Some(io)),
            close_token: CancellationToken::new(),
            closed: AtomicBool::new(false),
            tx_bytes: AtomicU64::new(0),
            rx_bytes: AtomicU64::new(0),
            last_activity: StdMutex::new(None),
            read_ops: AtomicU64::new(0),
            write_ops: AtomicU64::new(0),
            truncation_count: AtomicU64::new(0),
            notification_drop_count: AtomicU64::new(0),
            port_info: config.port_info,
            log: crate::log_buffer::LogBuffer::new_shared(config.log_capacity, config.log_enabled),
            state: StdMutex::new(ConnectionState::Open),
            reconnect_policy: StdMutex::new(ReconnectPolicy::default()),
            reconnect_attempts: AtomicU64::new(0),
            last_error: StdMutex::new(None),
            tx_framing_default: config.tx_framing,
            rx_framing_default: config.rx_framing,
            rx_parser_default: config.rx_parser,
            protocol_default: config.protocol,
        }
    }

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

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

    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    pub fn baud_rate(&self) -> u32 {
        *self.baud_rate.lock().expect("baud_rate mutex poisoned")
    }

    pub fn flow_control(&self) -> FlowControl {
        *self
            .flow_control
            .lock()
            .expect("flow_control mutex poisoned")
    }

    pub fn data_bits(&self) -> DataBits {
        *self.data_bits.lock().expect("data_bits mutex poisoned")
    }

    pub fn stop_bits(&self) -> StopBits {
        *self.stop_bits.lock().expect("stop_bits mutex poisoned")
    }

    pub fn parity(&self) -> Parity {
        *self.parity.lock().expect("parity mutex poisoned")
    }

    /// Return the OS-level port identity captured at open time.
    pub fn port_info(&self) -> Option<&PortInfo> {
        self.port_info.as_ref()
    }

    /// Return the per-connection event log buffer.
    pub fn log(&self) -> &Arc<crate::log_buffer::LogBuffer> {
        &self.log
    }

    /// Default TX framing stored on the connection (from profile or `open`).
    pub fn tx_framing_default(&self) -> Option<&crate::framing::TxFramingConfig> {
        self.tx_framing_default.as_ref()
    }

    /// Default RX framing stored on the connection.
    pub fn rx_framing_default(&self) -> Option<&crate::framing::RxFramingConfig> {
        self.rx_framing_default.as_ref()
    }

    /// Default RX parser stored on the connection.
    pub fn rx_parser_default(&self) -> Option<&crate::framing::ParserConfig> {
        self.rx_parser_default.as_ref()
    }

    /// Default protocol preset stored on the connection. `Copy`, so returned by value.
    pub fn protocol_default(&self) -> Option<crate::framing::ProtocolPreset> {
        self.protocol_default
    }

    /// Return the current connection health state.
    pub fn state(&self) -> ConnectionState {
        *self.state.lock().expect("state mutex poisoned")
    }

    /// Set the connection state and log the transition.
    fn set_state(&self, new_state: ConnectionState) {
        *self.state.lock().expect("state mutex poisoned") = new_state;
    }

    /// Mark the connection as disconnected due to a fatal I/O error.
    /// Takes the io handle out (sets to None), cancels in-flight operations,
    /// and clears RX buffers.
    pub async fn mark_disconnected(&self, error_message: String) {
        let was_healthy = self.state().is_healthy();
        self.set_state(ConnectionState::Disconnected);
        self.last_error
            .lock()
            .expect("poisoned")
            .replace((std::time::SystemTime::now(), error_message.clone()));
        // We do NOT cancel close_token here — that is reserved for explicit
        // close(). The pump and in-flight reads will time out naturally and
        // retry when the port is reconnected.
        self.log.rx_data(0); // dummy to trigger log
        self.log.record(
            None,
            crate::log_buffer::LogEvent::Disconnect {
                error: error_message,
            },
        );
        // Take the io handle out so subsequent I/O calls get ConnectionClosed
        let mut io_lock = self.io.lock().await;
        if let Some(mut io) = io_lock.take() {
            // Best-effort: clear OS buffers and shutdown
            let _ = io.clear_os_buffers(FlushTarget::Input);
            let _ = io.shutdown().await;
        }
        if was_healthy {
            tracing::warn!("Connection {} disconnected", self.display_name());
        }
    }

    /// Attempt to re-establish the serial port connection.
    ///
    /// Rebuilds a `SerialStream` from the stored config and replaces the
    /// current `io` handle in place. Preserves all counters, id, name,
    /// and log buffer. Called by auto-reconnect tasks and the reconnect
    /// tool.
    pub async fn reconnect(&self) -> Result<()> {
        let state = self.state();
        if state == ConnectionState::Open {
            return Ok(()); // already connected
        }
        if state == ConnectionState::Closed {
            return Err(SerialError::ConnectionClosed(self.display_name()));
        }

        self.set_state(ConnectionState::Reconnecting);
        self.reconnect_attempts.fetch_add(1, Ordering::SeqCst);
        let attempt = self.reconnect_attempts.load(Ordering::SeqCst) as u32;
        self.log.record(
            None,
            crate::log_buffer::LogEvent::ReconnectStart { attempt },
        );

        let config = self.build_config();
        match build_stream(&config) {
            Ok(stream) => {
                let mut io_lock = self.io.lock().await;
                *io_lock = Some(Box::new(stream));
                self.closed.store(false, Ordering::SeqCst);
                self.set_state(ConnectionState::Open);
                self.log
                    .record(None, crate::log_buffer::LogEvent::ReconnectSuccess);
                tracing::info!("Connection {} reconnected", self.display_name());
                Ok(())
            }
            Err(e) => {
                self.set_state(ConnectionState::Disconnected);
                let msg = e.to_string();
                self.log.record(
                    None,
                    crate::log_buffer::LogEvent::ReconnectFailed {
                        attempt,
                        error: msg,
                    },
                );
                Err(e)
            }
        }
    }

    /// Build a `ConnectionConfig` from the current connection state,
    /// for use in reconnect.
    fn build_config(&self) -> ConnectionConfig {
        ConnectionConfig {
            port: self.port.clone(),
            name: self.name.clone(),
            baud_rate: self.baud_rate(),
            data_bits: self.data_bits(),
            stop_bits: self.stop_bits(),
            parity: self.parity(),
            flow_control: self.flow_control(),
            port_info: self.port_info.clone(),
            log_capacity: 1024, // preserve log config
            log_enabled: self.log.is_enabled(),
            tx_framing: self.tx_framing_default().cloned(),
            rx_framing: self.rx_framing_default().cloned(),
            rx_parser: self.rx_parser_default().cloned(),
            protocol: self.protocol_default(),
        }
    }

    /// Record `n` bytes written to the device.
    pub fn record_tx_bytes(&self, n: usize) {
        self.tx_bytes.fetch_add(n as u64, Ordering::SeqCst);
        *self.last_activity.lock().expect("poisoned") = Some(std::time::SystemTime::now());
    }

    /// Record `n` bytes read from the device.
    pub fn record_rx_bytes(&self, n: usize) {
        self.rx_bytes.fetch_add(n as u64, Ordering::SeqCst);
        *self.last_activity.lock().expect("poisoned") = Some(std::time::SystemTime::now());
    }

    /// Return the last I/O activity as milliseconds since Unix epoch.
    pub fn last_activity_ms(&self) -> Option<u64> {
        self.last_activity.lock().expect("poisoned").and_then(|t| {
            t.duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_millis() as u64)
                .ok()
        })
    }

    /// Record one successful read or subscribe operation.
    pub fn record_read_op(&self) {
        self.read_ops.fetch_add(1, Ordering::SeqCst);
    }

    /// Record one successful write operation.
    pub fn record_write_op(&self) {
        self.write_ops.fetch_add(1, Ordering::SeqCst);
    }

    /// Record one RX truncation (bytes_returned < bytes_observed).
    pub fn record_truncation(&self) {
        self.truncation_count.fetch_add(1, Ordering::SeqCst);
    }

    /// Record one notification drop (encoding error or disconnected peer).
    pub fn record_notification_drop(&self) {
        self.notification_drop_count.fetch_add(1, Ordering::SeqCst);
    }

    /// Build a snapshot of the current status of this connection.
    pub fn status_snapshot(&self) -> ConnectionStatus {
        ConnectionStatus {
            connection_id: self.id().to_string(),
            name: self.name().map(str::to_string),
            port: self.port().to_string(),
            baud_rate: self.baud_rate(),
            data_bits: data_bits_to_str(self.data_bits()),
            stop_bits: stop_bits_to_str(self.stop_bits()),
            parity: parity_to_str(self.parity()),
            flow_control: flow_control_to_str(self.flow_control()),
            is_closed: self.closed.load(Ordering::SeqCst),
            tx_bytes: self.tx_bytes.load(Ordering::SeqCst),
            rx_bytes: self.rx_bytes.load(Ordering::SeqCst),
            last_activity_ms: self.last_activity_ms(),
            read_ops: self.read_ops.load(Ordering::SeqCst),
            write_ops: self.write_ops.load(Ordering::SeqCst),
            truncation_count: self.truncation_count.load(Ordering::SeqCst),
            notification_drop_count: self.notification_drop_count.load(Ordering::SeqCst),
            port_info: self.port_info.clone(),
            state: self.state(),
            reconnect_attempts: self.reconnect_attempts.load(Ordering::SeqCst),
            last_error: self
                .last_error
                .lock()
                .expect("poisoned")
                .as_ref()
                .map(|(_, msg)| msg.clone()),
        }
    }

    pub fn cancel_token(&self) -> CancellationToken {
        self.close_token.clone()
    }

    pub fn summary(&self) -> ConnectionSummary {
        ConnectionSummary {
            connection_id: self.id().to_string(),
            name: self.name().map(str::to_string),
            port: self.port().to_string(),
            baud_rate: self.baud_rate(),
            flow_control: self.flow_control(),
        }
    }

    fn ensure_open(&self) -> Result<()> {
        if self.closed.load(Ordering::SeqCst) {
            return Err(SerialError::ConnectionClosed(self.display_name()));
        }
        Ok(())
    }

    fn display_name(&self) -> String {
        self.name.clone().unwrap_or_else(|| self.id.clone())
    }

    /// Write a byte slice, flushing before returning.
    pub async fn write(&self, data: &[u8]) -> Result<usize> {
        self.ensure_open()?;
        self.log.tx_data(data.len());
        let mut io = self.io.lock().await;
        let io = io
            .as_mut()
            .ok_or_else(|| SerialError::ConnectionClosed(self.display_name()))?;
        io.write_all(data).await?;
        io.flush().await?;
        self.record_tx_bytes(data.len());
        Ok(data.len())
    }

    /// 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;
        self.ensure_open()?;
        match timeout_ms {
            None => {
                let mut io = self.io.lock().await;
                let io = io
                    .as_mut()
                    .ok_or_else(|| SerialError::ConnectionClosed(self.display_name()))?;
                let n = tokio::select! {
                    _ = self.close_token.cancelled() => Err(SerialError::ConnectionClosed(self.display_name())),
                    res = io.read(dst) => Ok(res?),
                }?;
                self.record_rx_bytes(n);
                Ok(n)
            }
            Some(ms) => {
                let deadline = Instant::now() + Duration::from_millis(ms);
                loop {
                    if self.close_token.is_cancelled() {
                        return Err(SerialError::ConnectionClosed(self.display_name()));
                    }
                    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 io = self.io.lock().await;
                        let io = io
                            .as_mut()
                            .ok_or_else(|| SerialError::ConnectionClosed(self.display_name()))?;
                        match tokio::select! {
                            _ = self.close_token.cancelled() => return Err(SerialError::ConnectionClosed(self.display_name())),
                            res = timeout(poll_dur, io.read(dst)) => res,
                        } {
                            Ok(Ok(n)) if n > 0 => {
                                self.record_rx_bytes(n);
                                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)
    }

    /// 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<()> {
        self.ensure_open()?;
        let io = self.io.lock().await;
        io.as_ref()
            .ok_or_else(|| SerialError::ConnectionClosed(self.display_name()))?
            .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<()> {
        self.ensure_open()?;
        let mut io = self.io.lock().await;
        io.as_mut()
            .ok_or_else(|| SerialError::ConnectionClosed(self.display_name()))?
            .set_dtr_rts(dtr, rts)
            .map_err(SerialError::from)
    }

    pub async fn set_flow_control(&self, flow_control: FlowControl) -> Result<()> {
        self.ensure_open()?;
        let mut io = self.io.lock().await;
        io.as_mut()
            .ok_or_else(|| SerialError::ConnectionClosed(self.display_name()))?
            .set_flow_control(flow_control)
            .map_err(SerialError::from)?;
        *self
            .flow_control
            .lock()
            .expect("flow_control mutex poisoned") = flow_control;
        Ok(())
    }

    /// Set the BREAK condition on the TX line.
    pub async fn set_break_state(&self, enabled: bool) -> Result<()> {
        self.ensure_open()?;
        let io = self.io.lock().await;
        io.as_ref()
            .ok_or_else(|| SerialError::ConnectionClosed(self.display_name()))?
            .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
    }

    /// Reconfigure serial parameters on a live connection. Parameters passed
    /// as `None` are left unchanged. Returns the effective config after the
    /// operation completes.
    pub async fn reconfigure(
        &self,
        baud_rate: Option<u32>,
        data_bits: Option<DataBits>,
        stop_bits: Option<StopBits>,
        parity: Option<Parity>,
        flow_control: Option<FlowControl>,
    ) -> Result<ConnectionStatus> {
        self.ensure_open()?;

        if let Some(rate) = baud_rate {
            ensure_valid_baud_rate(rate)?;
        }

        // Apply requested changes to the underlying serial port hardware.
        {
            let mut io = self.io.lock().await;
            let io = io
                .as_mut()
                .ok_or_else(|| SerialError::ConnectionClosed(self.display_name()))?;

            if let Some(rate) = baud_rate {
                io.reconfigure_baud_rate(rate).map_err(SerialError::from)?;
            }
            if let Some(db) = data_bits {
                io.reconfigure_data_bits(db.into())
                    .map_err(SerialError::from)?;
            }
            if let Some(sb) = stop_bits {
                io.reconfigure_stop_bits(sb.into())
                    .map_err(SerialError::from)?;
            }
            if let Some(p) = parity {
                io.reconfigure_parity(p.into()).map_err(SerialError::from)?;
            }
            if let Some(fc) = flow_control {
                io.set_flow_control(fc).map_err(SerialError::from)?;
            }
        }

        // Update stored configuration.
        if let Some(rate) = baud_rate {
            *self.baud_rate.lock().expect("poisoned") = rate;
        }
        if let Some(db) = data_bits {
            *self.data_bits.lock().expect("poisoned") = db;
        }
        if let Some(sb) = stop_bits {
            *self.stop_bits.lock().expect("poisoned") = sb;
        }
        if let Some(p) = parity {
            *self.parity.lock().expect("poisoned") = p;
        }
        if let Some(fc) = flow_control {
            *self.flow_control.lock().expect("poisoned") = fc;
        }

        Ok(self.status_snapshot())
    }

    pub async fn close(&self) -> Result<()> {
        if self.closed.swap(true, Ordering::SeqCst) {
            return Ok(());
        }
        self.close_token.cancel();

        let mut io = self.io.lock().await;
        if let Some(mut io) = io.take() {
            io.clear_os_buffers(FlushTarget::Input)
                .map_err(SerialError::from)?;
            io.shutdown().await?;
        }
        Ok(())
    }
}

/// Which OS-side buffer(s) a flush should clear.
#[derive(Debug, Clone, Copy, PartialEq, Eq, 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>,
    closing_ports: HashSet<String>,
    reconnect_tasks: HashMap<String, tokio::task::JoinHandle<()>>,
}

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 let Some(connection) = find_connection_by_port(&state.connections, &port) {
                return Err(SerialError::PortAlreadyOpen {
                    port,
                    connection_id: Some(connection.id().to_string()),
                    name: connection.name().map(str::to_string),
                });
            }
            if state.opening_ports.contains(&port) || state.closing_ports.contains(&port) {
                return Err(SerialError::PortAlreadyOpening(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 let Some(existing) = find_connection_by_port(&state.connections, connection.port()) {
            return Err(SerialError::PortAlreadyOpen {
                port: connection.port().to_string(),
                connection_id: Some(existing.id().to_string()),
                name: existing.name().map(str::to_string),
            });
        }
        if state.opening_ports.contains(connection.port())
            || state.closing_ports.contains(connection.port())
        {
            return Err(SerialError::PortAlreadyOpening(
                connection.port().to_string(),
            ));
        }
        let id = connection.id().to_string();
        state.connections.insert(id.clone(), Arc::new(connection));
        Ok(id)
    }

    /// Remove a connection, cancel in-flight operations, flush RX, and close
    /// the underlying port before allowing a reopen.
    pub async fn close(&self, id: &str) -> Result<()> {
        let connection = {
            let mut state = self.state.lock().await;
            let connection = state
                .connections
                .remove(id)
                .ok_or_else(|| SerialError::ConnectionNotFound(id.to_string()))?;
            state.closing_ports.insert(connection.port().to_string());
            connection
        };

        let port = connection.port().to_string();
        // Abort any running reconnect task for this connection.
        {
            let mut state = self.state.lock().await;
            if let Some(handle) = state.reconnect_tasks.remove(id) {
                handle.abort();
            }
        }
        connection.log().closed();
        let result = connection.close().await;

        self.state.lock().await.closing_ports.remove(&port);
        result
    }

    /// 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()))
    }

    /// Return all currently-registered connections with their ids.
    pub async fn list_all(&self) -> Vec<(String, Arc<SerialConnection>)> {
        self.state
            .lock()
            .await
            .connections
            .iter()
            .map(|(k, v)| (k.clone(), Arc::clone(v)))
            .collect()
    }

    /// Start a background reconnect task for the given connection.
    /// The task retries `reconnect()` with exponential backoff,
    /// respecting the connection's `ReconnectPolicy`. On success,
    /// restarts the RX pump via `rx_sessions`.
    pub async fn start_reconnect(
        &self,
        id: &str,
        rx_sessions: Arc<crate::rx_session::RxSessionManager>,
    ) {
        let conn = match self.get(id).await {
            Ok(c) => c,
            Err(_) => return,
        };
        let policy = conn.reconnect_policy.lock().expect("poisoned").clone();
        if !policy.enabled {
            return;
        }
        // Avoid spawning a duplicate task. Prune finished handles first.
        {
            let mut state = self.state.lock().await;
            state.reconnect_tasks.retain(|_, h| !h.is_finished());
            if state.reconnect_tasks.contains_key(id) {
                return;
            }
        }

        let id_owned = id.to_string();
        let conn_clone = Arc::clone(&conn);
        let handle = tokio::spawn(async move {
            let mut delay_ms = policy.initial_delay_ms;
            let mut attempts: u32 = 0;
            loop {
                // Check if still disconnected / not cancelled.
                let state = conn_clone.state();
                if state == ConnectionState::Open || state == ConnectionState::Closed {
                    break;
                }
                tokio::time::sleep(std::time::Duration::from_millis(delay_ms)).await;

                match conn_clone.reconnect().await {
                    Ok(()) => {
                        // Reset attempt counter after successful reconnect.
                        conn_clone.reconnect_attempts.store(0, Ordering::SeqCst);
                        // Restart the RX pump so data flows again.
                        if let Some(session) = rx_sessions.get(&id_owned).await {
                            session.ensure_pump_running();
                        }
                        break;
                    }
                    Err(_e) => {
                        attempts += 1;
                        if policy.max_attempts > 0 && attempts >= policy.max_attempts {
                            conn_clone
                                .log()
                                .record(None, crate::log_buffer::LogEvent::ReconnectExhausted);
                            break;
                        }
                        // Exponential backoff with cap.
                        delay_ms = ((delay_ms as f64) * policy.backoff_multiplier)
                            .min(policy.max_delay_ms as f64)
                            as u64;
                    }
                }
            }
            // Task completes: handle stays in reconnect_tasks; supervisor
            // prunes finished handles on its next poll.
        });

        let mut state = self.state.lock().await;
        state.reconnect_tasks.insert(id.to_string(), handle);
    }

    /// Cancel a running reconnect task for the given connection.
    pub async fn cancel_reconnect(&self, id: &str) {
        let mut state = self.state.lock().await;
        if let Some(handle) = state.reconnect_tasks.remove(id) {
            handle.abort();
        }
    }

    /// 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| c.summary())
            .collect()
    }
}

/// Public-facing summary of an open connection.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ConnectionSummary {
    pub connection_id: String,
    pub name: Option<String>,
    pub port: String,
    #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
    pub baud_rate: u32,
    pub flow_control: FlowControl,
}

/// Full status snapshot of a connection used by the `get_status` tool.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ConnectionStatus {
    pub connection_id: String,
    pub name: Option<String>,
    pub port: String,
    #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
    pub baud_rate: u32,
    pub data_bits: String,
    pub stop_bits: String,
    pub parity: String,
    pub flow_control: String,
    pub is_closed: bool,
    #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
    pub tx_bytes: u64,
    #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
    pub rx_bytes: u64,
    /// Last I/O activity as milliseconds since Unix epoch, or null.
    #[schemars(schema_with = "crate::schema_helpers::option_uint_schema")]
    pub last_activity_ms: Option<u64>,
    #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
    pub read_ops: u64,
    #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
    pub write_ops: u64,
    #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
    pub truncation_count: u64,
    #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
    pub notification_drop_count: u64,
    /// OS-level port identity captured at open time (vid, pid, serial,
    /// manufacturer, etc.). `null` for connections opened without
    /// identity data (e.g. loopback tests).
    pub port_info: Option<PortInfo>,
    /// Current connection health state.
    pub state: ConnectionState,
    /// Number of reconnect attempts since last disconnect.
    #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
    pub reconnect_attempts: u64,
    /// Last fatal error message, or null.
    pub last_error: Option<String>,
}

fn find_connection_by_port<'a>(
    connections: &'a HashMap<String, Arc<SerialConnection>>,
    port: &str,
) -> Option<&'a Arc<SerialConnection>> {
    connections.values().find(|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_flow_control(&mut self, _flow_control: FlowControl) -> 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)
    }

    pub fn loopback_connection_with_config(
        config: ConnectionConfig,
    ) -> (SerialConnection, DuplexStream) {
        let (a, b) = tokio::io::duplex(4096);
        let conn = SerialConnection::from_io_with_config(config, Box::new(LoopbackIo(a)));
        (conn, b)
    }

    // ── QueuedTxIo ───────────────────────────────────────────────────────
    //
    // A `SerialIo` backend that models an OS transmit queue the way a real
    // serialport does on Linux: `write()` lands bytes in a TX queue, and
    // `clear_os_buffers(Output)` (the backend behind `flush(target=output)`)
    // discards bytes still in that queue before the device has drained them.
    //
    // Unlike `LoopbackIo` (which is backed by `tokio::io::duplex` and so
    // delivers every written byte to the peer immediately), `QueuedTxIo`
    // keeps written bytes in an internal queue until the test explicitly
    // drains them via the `QueuedTxHandle`. This lets unit tests exercise
    // the "flushed-before-delivery" path: write, flush(output), then assert
    // the device received nothing because the queued bytes were discarded
    // before the device drained them.
    //
    // RX direction (device -> host) is fed by `QueuedTxHandle::inject_rx`,
    // which pushes bytes the host can then `read`.

    /// Shared state between [`QueuedTxIo`] and its [`QueuedTxHandle`].
    struct QueuedTxState {
        /// Bytes written by the host, awaiting delivery to the device.
        /// `clear_os_buffers(Output)` discards these.
        tx_queue: std::collections::VecDeque<u8>,
        /// Bytes the device injected for the host to read.
        /// `clear_os_buffers(Input)` discards these.
        rx_queue: std::collections::VecDeque<u8>,
        /// Waker for the host-side `poll_read`, notified when rx_queue grows.
        rx_waker: Option<std::task::Waker>,
    }

    impl QueuedTxState {
        fn new() -> Self {
            Self {
                tx_queue: std::collections::VecDeque::new(),
                rx_queue: std::collections::VecDeque::new(),
                rx_waker: None,
            }
        }
    }

    /// A `SerialIo` backend whose TX path models an OS transmit queue.
    pub struct QueuedTxIo {
        state: std::sync::Arc<std::sync::Mutex<QueuedTxState>>,
    }

    /// Test handle that can drain the TX queue (simulate the device reading),
    /// inject RX bytes (simulate the device writing), and inspect queue state.
    pub struct QueuedTxHandle {
        state: std::sync::Arc<std::sync::Mutex<QueuedTxState>>,
    }

    /// Build a [`SerialConnection`] backed by [`QueuedTxIo`] plus the
    /// [`QueuedTxHandle`] for driving the simulated device side.
    pub fn queued_tx_connection(port: &str) -> (SerialConnection, QueuedTxHandle) {
        let state = std::sync::Arc::new(std::sync::Mutex::new(QueuedTxState::new()));
        let conn = SerialConnection::from_io(
            port.to_string(),
            Box::new(QueuedTxIo {
                state: state.clone(),
            }),
        );
        (conn, QueuedTxHandle { state })
    }

    impl QueuedTxHandle {
        /// Number of bytes currently queued in the OS TX queue (written by
        /// the host, not yet drained by the device, not yet flushed).
        pub fn tx_queue_len(&self) -> usize {
            self.state.lock().expect("tx state poisoned").tx_queue.len()
        }

        /// Drain up to `max` bytes from the OS TX queue, simulating the
        /// device reading its RX. Returns the drained bytes in order.
        pub fn drain_tx(&self, max: usize) -> Vec<u8> {
            let mut state = self.state.lock().expect("tx state poisoned");
            let take = max.min(state.tx_queue.len());
            let mut out = Vec::with_capacity(take);
            for _ in 0..take {
                out.push(state.tx_queue.pop_front().expect("len checked"));
            }
            out
        }

        /// Inject bytes for the host to read (simulates the device writing).
        pub fn inject_rx(&self, bytes: &[u8]) {
            let mut state = self.state.lock().expect("tx state poisoned");
            state.rx_queue.extend(bytes);
            if let Some(w) = state.rx_waker.take() {
                w.wake();
            }
        }

        /// Number of bytes currently buffered for the host to read.
        pub fn rx_queue_len(&self) -> usize {
            self.state.lock().expect("tx state poisoned").rx_queue.len()
        }
    }

    impl AsyncRead for QueuedTxIo {
        fn poll_read(
            self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
            buf: &mut ReadBuf<'_>,
        ) -> Poll<std::io::Result<()>> {
            let mut state = self.state.lock().expect("tx state poisoned");
            let n = buf.initialize_unfilled().len().min(state.rx_queue.len());
            if n == 0 {
                // Remember the waker so a later inject_rx can wake us.
                state.rx_waker = Some(_cx.waker().clone());
                return Poll::Pending;
            }
            let filled = buf.initialize_unfilled();
            for slot in filled.iter_mut().take(n) {
                *slot = state.rx_queue.pop_front().expect("len checked");
            }
            buf.advance(n);
            Poll::Ready(Ok(()))
        }
    }

    impl AsyncWrite for QueuedTxIo {
        fn poll_write(
            self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
            buf: &[u8],
        ) -> Poll<std::io::Result<usize>> {
            let mut state = self.state.lock().expect("tx state poisoned");
            state.tx_queue.extend(buf);
            Poll::Ready(Ok(buf.len()))
        }

        fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
            // No-op: bytes stay in tx_queue until drain_tx or
            // clear_os_buffers(Output). This models a real OS TX queue where
            // a successful write does not imply the device has consumed.
            Poll::Ready(Ok(()))
        }

        fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
            Poll::Ready(Ok(()))
        }
    }

    impl SerialIo for QueuedTxIo {
        fn clear_os_buffers(&self, target: FlushTarget) -> std::io::Result<()> {
            let mut state = self.state.lock().expect("tx state poisoned");
            match target {
                FlushTarget::Input => {
                    state.rx_queue.clear();
                }
                FlushTarget::Output => {
                    state.tx_queue.clear();
                }
                FlushTarget::Both => {
                    state.tx_queue.clear();
                    state.rx_queue.clear();
                }
            }
            Ok(())
        }
        fn set_dtr_rts(&mut self, _dtr: bool, _rts: bool) -> std::io::Result<()> {
            Ok(())
        }
        fn set_flow_control(&mut self, _flow_control: FlowControl) -> std::io::Result<()> {
            Ok(())
        }
        fn set_break_state(&self, _asserted: bool) -> std::io::Result<()> {
            Ok(())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::test_support::{loopback_connection, loopback_connection_with_config};
    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 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_duplicate_port_error_includes_owner_metadata() {
        let mgr = ConnectionManager::new();
        let (c1, _peer_a) = loopback_connection_with_config(ConnectionConfig {
            port: "port-owner".into(),
            name: Some("console".into()),
            baud_rate: 115200,
            data_bits: DataBits::Eight,
            stop_bits: StopBits::One,
            parity: Parity::None,
            flow_control: FlowControl::None,
            port_info: None,
            log_capacity: 1024,
            log_enabled: true,
            tx_framing: None,
            rx_framing: None,
            rx_parser: None,
            protocol: None,
        });
        let owner_id = mgr.insert(c1).await.unwrap();

        let (c2, _p2) = loopback_connection("port-owner");
        let err = mgr.insert(c2).await.unwrap_err();
        match err {
            SerialError::PortAlreadyOpen {
                port,
                connection_id,
                name,
            } => {
                assert_eq!(port, "port-owner");
                assert_eq!(connection_id.as_deref(), Some(owner_id.as_str()));
                assert_eq!(name.as_deref(), Some("console"));
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[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(_)));
    }

    #[tokio::test]
    async fn close_cancels_inflight_read() {
        let mgr = ConnectionManager::new();
        let (conn, _peer) = loopback_connection("port-read-close");
        let id = mgr.insert(conn).await.unwrap();
        let connection = mgr.get(&id).await.unwrap();

        let reader = tokio::spawn(async move {
            let mut buf = [0u8; 16];
            connection.read(&mut buf, Some(2_000)).await
        });

        tokio::time::sleep(Duration::from_millis(100)).await;
        mgr.close(&id).await.unwrap();

        let err = reader.await.unwrap().unwrap_err();
        assert!(matches!(err, SerialError::ConnectionClosed(_)));
    }

    #[test]
    fn from_str_parses_config_enums() {
        use std::str::FromStr;
        assert!(matches!("5".parse::<DataBits>(), Ok(DataBits::Five)));
        assert!(matches!("8".parse::<DataBits>(), Ok(DataBits::Eight)));
        assert!("9".parse::<DataBits>().is_err());

        assert!(matches!("1".parse::<StopBits>(), Ok(StopBits::One)));
        assert!(matches!("2".parse::<StopBits>(), Ok(StopBits::Two)));
        assert!("3".parse::<StopBits>().is_err());

        // Parity / flow_control are case-insensitive (the intended shared behavior).
        assert!(matches!(Parity::from_str("none"), Ok(Parity::None)));
        assert!(matches!(Parity::from_str("Even"), Ok(Parity::Even)));
        assert!(matches!("ODD".parse::<Parity>(), Ok(Parity::Odd)));
        assert!("weird".parse::<Parity>().is_err());

        assert!(matches!(
            "NONE".parse::<FlowControl>(),
            Ok(FlowControl::None)
        ));
        assert!(matches!(
            "Software".parse::<FlowControl>(),
            Ok(FlowControl::Software)
        ));
        assert!(matches!(
            "hardware".parse::<FlowControl>(),
            Ok(FlowControl::Hardware)
        ));
        assert!("xon".parse::<FlowControl>().is_err());
    }

    #[test]
    fn from_str_round_trips_with_to_str() {
        for d in [
            DataBits::Five,
            DataBits::Six,
            DataBits::Seven,
            DataBits::Eight,
        ] {
            let s = data_bits_to_str(d);
            assert_eq!(data_bits_to_str(s.parse::<DataBits>().unwrap()), s);
        }
        for sb in [StopBits::One, StopBits::Two] {
            let s = stop_bits_to_str(sb);
            assert_eq!(stop_bits_to_str(s.parse::<StopBits>().unwrap()), s);
        }
        for p in [Parity::None, Parity::Odd, Parity::Even] {
            let s = parity_to_str(p);
            assert_eq!(parity_to_str(s.parse::<Parity>().unwrap()), s);
        }
        for f in [
            FlowControl::None,
            FlowControl::Software,
            FlowControl::Hardware,
        ] {
            let s = flow_control_to_str(f);
            assert_eq!(flow_control_to_str(s.parse::<FlowControl>().unwrap()), s);
        }
    }

    #[test]
    fn from_str_error_messages_are_descriptive() {
        assert!("9"
            .parse::<DataBits>()
            .unwrap_err()
            .contains("expected 5/6/7/8"));
        assert!("3"
            .parse::<StopBits>()
            .unwrap_err()
            .contains("expected 1/2"));
        assert!("weird"
            .parse::<Parity>()
            .unwrap_err()
            .contains("expected none/odd/even"));
        assert!("xon"
            .parse::<FlowControl>()
            .unwrap_err()
            .contains("expected none/software/hardware"));
    }
}

// =============================================================================
// JSON Schema regression tests — DO NOT DELETE.
//
// These tests guard against the schemars "non-standard uint format" regression
// that has bitten this crate repeatedly (commits b12b09fd, bc37a0b0, and the
// regression fixed in this commit on `PortInfo`).
//
// Background
// ----------
// schemars (1.x) emits a `"format": "uintN"` keyword for unsigned integer
// types: `uint8`, `uint16`, `uint32`, `uint64`, `uint`. None of these are part
// of the JSON Schema spec. Validators (jsonschema, AJV, …) log a warning like
//     unknown format "uint16" ignored in schema at path "#/properties/vid"
// and then drop the constraint. Functionally harmless but noisy, and a sign
// that a field was added without the required `#[schemars(schema_with = ...)]`
// override.
//
// Every time a new struct with a `uN`/`Option<uN>` field is added and derives
// `JsonSchema`, it MUST annotate that field with `crate::schema_helpers::uint_schema`
// (for `uN`) or `crate::schema_helpers::option_uint_schema` (for `Option<uN>`).
//
// Why this keeps coming back
// --------------------------
// The previous guard (`tool_schemas_have_no_nonstandard_uint_formats` in
// `src/tools/mod.rs`) only checked the tool `outputSchema` strings and only
// asserted on `uint`/`uint32`/`uint64`. It missed:
//   1. `u8`/`u16` formats (this regression's `PortInfo.vid`/`pid`/`interface`).
//   2. Types that appear in resource/prompt schemas but are also reachable via
//      tool outputs (e.g. `PortInfo` is in `ListPortsResult` AND
//      `ConnectionStatus.port_info`).
//
// The tests below close both gaps:
//   - They enumerate every known public `JsonSchema`-deriving struct and
//     reject *any* `uint*` format keyword.
//   - They also keep the tool-level string scan, now covering uint8/uint16
//     (see `src/tools/mod.rs`).
//
// If you add a new public type that derives `JsonSchema` and has unsigned
// integer fields, ADD IT to the `check_schema!` list below. The compile-time
// cost is tiny; the cost of shipping noisy schemas to every MCP client is not.
// =============================================================================
#[cfg(test)]
mod schema {
    use schemars::schema_for;
    use serde_json::{self, Value};

    use crate::framing::{
        Frame, ParsedFrame, RxFramingConfig, RxFramingMode, TxFramingConfig, TxFramingMode,
    };
    use crate::profiles::{Profile, ProfileSelector};
    use crate::serial::{ConnectionStatus, PortInfo};
    use crate::tools::types::{
        ClearLogResult, CloseResult, DeleteProfileResult, ExportLogResult, FlushResult,
        GetLogResult, GetStatusResult, ListConnectionsResult, ListPortsResult, ListProfilesResult,
        OpenResult, ReadResult, ReconfigureResult, ReconnectResult, SaveProfileResult,
        SendBreakResult, SetDtrRtsResult, SetFlowControlResult, SubscribeResult, UnsubscribeResult,
        WriteResult,
    };

    /// Walk a JSON Schema `Value` and collect every `"format"` whose value
    /// starts with `uint`. Returns the dotted path of each offending node so
    /// failures point at the exact field.
    fn collect_nonstandard_uint_formats(schema: &Value) -> Vec<String> {
        let mut offenders = Vec::new();
        let mut stack: Vec<(String, &Value)> = Vec::new();
        stack.push((String::new(), schema));

        while let Some((path, value)) = stack.pop() {
            match value {
                Value::Object(map) => {
                    if let Some(Value::String(fmt)) = map.get("format") {
                        if fmt.starts_with("uint") {
                            offenders.push(format!("{path} (format={fmt})"));
                        }
                    }
                    for (k, v) in map {
                        let next = if path.is_empty() {
                            k.clone()
                        } else {
                            format!("{path}.{k}")
                        };
                        stack.push((next, v));
                    }
                }
                Value::Array(arr) => {
                    for (i, v) in arr.iter().enumerate() {
                        stack.push((format!("{path}[{i}]"), v));
                    }
                }
                _ => {}
            }
        }

        offenders
    }

    /// Generate a focused test for one type that asserts its JSON Schema
    /// contains no non-standard `uint*` format keywords.
    macro_rules! check_schema {
        ($name:ident, $ty:ty) => {
            #[test]
            fn $name() {
                let schema = schema_for!($ty);
                let json = serde_json::to_value(&schema).expect("schema serializes");
                let offenders = collect_nonstandard_uint_formats(&json);
                assert!(
                    offenders.is_empty(),
                    "{} schema emits non-standard JSON Schema uint formats: {offenders:?}.\n\
                         Fix: annotate each uN/Option<uN> field on the type with\n\
                         `#[schemars(schema_with = \"crate::schema_helpers::uint_schema\")]`\n\
                         (or `option_uint_schema` for Option<uN>). See\n\
                         src/schema_helpers.rs and the header comment of this test\n\
                         module (serial::schema) for the full rationale.",
                    stringify!($ty),
                );
            }
        };
    }

    // Core identity + status types (the source of this regression).
    check_schema!(port_info_has_no_uint_formats, PortInfo);
    check_schema!(connection_status_has_no_uint_formats, ConnectionStatus);

    // Profile types (already fixed in b12b09fd; guarded against regressions).
    check_schema!(profile_has_no_uint_formats, Profile);
    check_schema!(profile_selector_has_no_uint_formats, ProfileSelector);

    // Tool result types reachable by clients.
    // Keep this list in sync with the `#[tool]` methods in `src/server.rs`
    // and with `all_tool_attrs()` in `src/tools/mod.rs`.
    check_schema!(list_ports_result_has_no_uint_formats, ListPortsResult);
    check_schema!(
        list_connections_result_has_no_uint_formats,
        ListConnectionsResult
    );
    check_schema!(open_result_has_no_uint_formats, OpenResult);
    check_schema!(close_result_has_no_uint_formats, CloseResult);
    check_schema!(write_result_has_no_uint_formats, WriteResult);
    check_schema!(read_result_has_no_uint_formats, ReadResult);
    check_schema!(flush_result_has_no_uint_formats, FlushResult);
    check_schema!(set_dtr_rts_result_has_no_uint_formats, SetDtrRtsResult);
    check_schema!(
        set_flow_control_result_has_no_uint_formats,
        SetFlowControlResult
    );
    check_schema!(send_break_result_has_no_uint_formats, SendBreakResult);
    check_schema!(subscribe_result_has_no_uint_formats, SubscribeResult);
    check_schema!(unsubscribe_result_has_no_uint_formats, UnsubscribeResult);
    check_schema!(get_status_result_has_no_uint_formats, GetStatusResult);
    check_schema!(reconfigure_result_has_no_uint_formats, ReconfigureResult);
    check_schema!(list_profiles_result_has_no_uint_formats, ListProfilesResult);
    check_schema!(save_profile_result_has_no_uint_formats, SaveProfileResult);
    check_schema!(
        delete_profile_result_has_no_uint_formats,
        DeleteProfileResult
    );
    check_schema!(get_log_result_has_no_uint_formats, GetLogResult);
    check_schema!(clear_log_result_has_no_uint_formats, ClearLogResult);
    check_schema!(export_log_result_has_no_uint_formats, ExportLogResult);
    check_schema!(reconnect_result_has_no_uint_formats, ReconnectResult);

    // Framing config types (checked for uint format regressions on fields like
    // prefix_size, max_frames, and cobs delimiter).
    check_schema!(tx_framing_config_has_no_uint_formats, TxFramingConfig);
    check_schema!(tx_framing_mode_has_no_uint_formats, TxFramingMode);
    check_schema!(rx_framing_config_has_no_uint_formats, RxFramingConfig);
    check_schema!(rx_framing_mode_has_no_uint_formats, RxFramingMode);

    // Parsed frame enum (guards uint fields on ParsedFrame::ModbusAscii
    // and any future variants that carry unsigned integers).
    check_schema!(parsed_frame_has_no_uint_formats, ParsedFrame);

    // Decoded frame (guards the Vec<u8> data field + the usize index field).
    check_schema!(frame_has_no_uint_formats, Frame);

    // Profile defaults (Phase 5 framing fields — no unsigned fields, but guard).
    check_schema!(
        profile_defaults_has_no_uint_formats,
        crate::profiles::ProfileDefaults
    );
}