Skip to main content

serial_mcp/serial/
config.rs

1//! Serial-line and lifecycle data/config declarations: the configuration
2//! enums (`DataBits`/`StopBits`/`Parity`/`FlowControl`) with serialport
3//! conversions, string parsing, and to-string helpers; `ConnectionConfig`
4//! and its defaults; connection state types (`ConnectionState`,
5//! `ReconnectPolicy`, `is_fatal_disconnect`); the active profile-session
6//! binding; `FlushTarget`; and the connection summary/status snapshot
7//! shapes. `PortInfo` is imported from the sibling `port_info` module.
8
9use schemars::JsonSchema;
10use serde::{Deserialize, Serialize};
11use tokio_serial::ClearBuffer;
12
13use super::port_info::PortInfo;
14
15/// Largest baud rate accepted by [`crate::serial::SerialConnection::open`].
16/// Anything higher is treated as a typo or accidental overflow and rejected.
17pub const MAX_BAUD_RATE: u32 = 4_000_000;
18
19// ---- Configuration enums -----------------------------------------------------
20
21#[derive(Debug, Clone, Copy, Deserialize, JsonSchema)]
22pub enum DataBits {
23    #[serde(rename = "5")]
24    Five,
25    #[serde(rename = "6")]
26    Six,
27    #[serde(rename = "7")]
28    Seven,
29    #[serde(rename = "8")]
30    Eight,
31}
32
33impl From<DataBits> for serialport::DataBits {
34    fn from(value: DataBits) -> Self {
35        match value {
36            DataBits::Five => Self::Five,
37            DataBits::Six => Self::Six,
38            DataBits::Seven => Self::Seven,
39            DataBits::Eight => Self::Eight,
40        }
41    }
42}
43
44#[derive(Debug, Clone, Copy, Deserialize, JsonSchema)]
45pub enum StopBits {
46    #[serde(rename = "1")]
47    One,
48    #[serde(rename = "2")]
49    Two,
50}
51
52impl From<StopBits> for serialport::StopBits {
53    fn from(value: StopBits) -> Self {
54        match value {
55            StopBits::One => Self::One,
56            StopBits::Two => Self::Two,
57        }
58    }
59}
60
61#[derive(Debug, Clone, Copy, Deserialize, JsonSchema)]
62#[serde(rename_all = "lowercase")]
63pub enum Parity {
64    None,
65    Odd,
66    Even,
67}
68
69impl From<Parity> for serialport::Parity {
70    fn from(value: Parity) -> Self {
71        match value {
72            Parity::None => Self::None,
73            Parity::Odd => Self::Odd,
74            Parity::Even => Self::Even,
75        }
76    }
77}
78
79#[derive(Debug, Clone, Copy, Deserialize, Serialize, JsonSchema)]
80#[serde(rename_all = "lowercase")]
81pub enum FlowControl {
82    None,
83    Software,
84    Hardware,
85}
86
87impl From<FlowControl> for serialport::FlowControl {
88    fn from(value: FlowControl) -> Self {
89        match value {
90            FlowControl::None => Self::None,
91            FlowControl::Software => Self::Software,
92            FlowControl::Hardware => Self::Hardware,
93        }
94    }
95}
96
97pub(crate) fn data_bits_to_str(d: DataBits) -> String {
98    match d {
99        DataBits::Five => "5".into(),
100        DataBits::Six => "6".into(),
101        DataBits::Seven => "7".into(),
102        DataBits::Eight => "8".into(),
103    }
104}
105
106pub(crate) fn stop_bits_to_str(s: StopBits) -> String {
107    match s {
108        StopBits::One => "1".into(),
109        StopBits::Two => "2".into(),
110    }
111}
112
113pub(crate) fn parity_to_str(p: Parity) -> String {
114    match p {
115        Parity::None => "none".into(),
116        Parity::Odd => "odd".into(),
117        Parity::Even => "even".into(),
118    }
119}
120
121pub(crate) fn flow_control_to_str(f: FlowControl) -> String {
122    match f {
123        FlowControl::None => "none".into(),
124        FlowControl::Software => "software".into(),
125        FlowControl::Hardware => "hardware".into(),
126    }
127}
128
129// ---- String parsing (single source of truth) --------------------------------
130
131impl std::str::FromStr for DataBits {
132    type Err = String;
133    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
134        match s {
135            "5" => Ok(DataBits::Five),
136            "6" => Ok(DataBits::Six),
137            "7" => Ok(DataBits::Seven),
138            "8" => Ok(DataBits::Eight),
139            other => Err(format!("Invalid data_bits {other:?} (expected 5/6/7/8)")),
140        }
141    }
142}
143
144impl std::str::FromStr for StopBits {
145    type Err = String;
146    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
147        match s {
148            "1" => Ok(StopBits::One),
149            "2" => Ok(StopBits::Two),
150            other => Err(format!("Invalid stop_bits {other:?} (expected 1/2)")),
151        }
152    }
153}
154
155impl std::str::FromStr for Parity {
156    type Err = String;
157    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
158        match s.to_lowercase().as_str() {
159            "none" => Ok(Parity::None),
160            "odd" => Ok(Parity::Odd),
161            "even" => Ok(Parity::Even),
162            other => Err(format!("Invalid parity {other:?} (expected none/odd/even)")),
163        }
164    }
165}
166
167impl std::str::FromStr for FlowControl {
168    type Err = String;
169    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
170        match s.to_lowercase().as_str() {
171            "none" => Ok(FlowControl::None),
172            "software" => Ok(FlowControl::Software),
173            "hardware" => Ok(FlowControl::Hardware),
174            other => Err(format!(
175                "Invalid flow_control {other:?} (expected none/software/hardware)"
176            )),
177        }
178    }
179}
180
181/// Concrete parameters required to open a serial port.
182#[derive(Debug, Clone, JsonSchema)]
183pub struct ConnectionConfig {
184    pub port: String,
185    pub name: Option<String>,
186    pub baud_rate: u32,
187    pub data_bits: DataBits,
188    pub stop_bits: StopBits,
189    pub parity: Parity,
190    pub flow_control: FlowControl,
191    /// OS-level port identity (VID, PID, serial, transport, etc.)
192    /// Captured at open time for status and profile save operations.
193    pub port_info: Option<PortInfo>,
194    /// Log buffer capacity in events. 0 or None disables logging.
195    /// Default: 1024.
196    #[serde(default = "default_log_capacity")]
197    #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
198    pub log_capacity: usize,
199    /// Whether logging is enabled. Default: true when capacity > 0.
200    #[serde(default = "default_true")]
201    pub log_enabled: bool,
202    /// Default TX framing applied when `write` omits `tx_framing`.
203    #[serde(default)]
204    pub tx_framing: Option<crate::framing::TxFramingConfig>,
205    /// Default RX framing applied when `read`/`transact`/`capture_boot` omit
206    /// `rx_framing`.
207    #[serde(default)]
208    pub rx_framing: Option<crate::framing::RxFramingConfig>,
209    /// Default RX parser applied when `read`/`transact`/`capture_boot` omit
210    /// `rx_parser`.
211    #[serde(default)]
212    pub rx_parser: Option<crate::framing::ParserConfig>,
213    /// Default protocol preset. Expands to fill framing/parser gaps.
214    #[serde(default)]
215    pub protocol: Option<crate::framing::ProtocolPreset>,
216    /// RX ring buffer size in bytes for the always-on pump.
217    #[serde(default = "default_rx_buffer_size")]
218    #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
219    pub rx_buffer_size: usize,
220    /// Default max buffered bytes for `read` operations.
221    #[serde(default = "default_max_buffered_bytes")]
222    #[schemars(schema_with = "crate::schema_helpers::read_max_buffered_bytes_schema")]
223    pub max_buffered_bytes: usize,
224}
225
226fn default_rx_buffer_size() -> usize {
227    crate::limits::DEFAULT_RX_BUFFER_SIZE
228}
229fn default_log_capacity() -> usize {
230    1024
231}
232
233fn default_true() -> bool {
234    true
235}
236
237fn default_max_buffered_bytes() -> usize {
238    32768
239}
240
241// ---- Connection state -------------------------------------------------------
242
243/// The health state of a live serial connection.
244#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
245#[serde(rename_all = "snake_case")]
246pub enum ConnectionState {
247    Open,
248    Disconnected,
249    Reconnecting,
250    Closed,
251}
252
253impl ConnectionState {
254    pub fn is_healthy(&self) -> bool {
255        matches!(self, ConnectionState::Open)
256    }
257}
258
259/// Reconnect policy for a connection. When enabled and the port
260/// disappears, the server will try to re-establish the connection
261/// automatically with exponential backoff.
262#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
263pub struct ReconnectPolicy {
264    /// Enable automatic reconnect. Default: false.
265    #[serde(default)]
266    pub enabled: bool,
267    /// Maximum reconnect attempts. 0 = unlimited. Default: 10.
268    #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
269    #[serde(default = "default_max_reconnect_attempts")]
270    pub max_attempts: u32,
271    /// Initial delay between reconnect attempts in milliseconds. Default: 500.
272    #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
273    #[serde(default = "default_initial_reconnect_delay_ms")]
274    pub initial_delay_ms: u64,
275    /// Maximum delay between attempts in milliseconds. Default: 30000.
276    #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
277    #[serde(default = "default_max_reconnect_delay_ms")]
278    pub max_delay_ms: u64,
279    /// Backoff multiplier. Default: 2.0.
280    #[serde(default = "default_backoff_multiplier")]
281    pub backoff_multiplier: f64,
282}
283
284impl Default for ReconnectPolicy {
285    fn default() -> Self {
286        Self {
287            enabled: false,
288            max_attempts: 10,
289            initial_delay_ms: 500,
290            max_delay_ms: 30_000,
291            backoff_multiplier: 2.0,
292        }
293    }
294}
295
296fn default_max_reconnect_attempts() -> u32 {
297    10
298}
299fn default_initial_reconnect_delay_ms() -> u64 {
300    500
301}
302fn default_max_reconnect_delay_ms() -> u64 {
303    30_000
304}
305fn default_backoff_multiplier() -> f64 {
306    2.0
307}
308
309/// Classify an I/O error as a fatal disconnect (port vanished).
310pub fn is_fatal_disconnect(err: &std::io::Error) -> bool {
311    use std::io::ErrorKind;
312    matches!(
313        err.kind(),
314        ErrorKind::NotFound
315            | ErrorKind::PermissionDenied
316            | ErrorKind::ConnectionReset
317            | ErrorKind::ConnectionAborted
318            | ErrorKind::BrokenPipe
319            | ErrorKind::Interrupted
320    )
321}
322
323// ---- Active profile-session binding -----------------------------------------
324
325/// Active profile-session binding stored on a connection.
326///
327/// Every connection opened through the public `open`/`open_profile` tools
328/// carries one. Connections inserted directly by low-level tests may have
329/// `None`. Converts losslessly into the wire type
330/// [`crate::profiles::ProfileSessionResult`] for open/status/connection
331/// summaries.
332#[derive(Debug, Clone)]
333pub struct ActiveProfileBinding {
334    pub profile_name: String,
335    pub source: crate::profiles::ProfileSelectionSource,
336    pub confidence: crate::profiles::IdentityConfidence,
337    pub persistent: bool,
338    pub generated: bool,
339    pub revision: Option<u64>,
340    pub dirty: bool,
341    /// `true` when the durable profile revision changed externally (CAS
342    /// conflict or rollback) and this connection must not overwrite it.
343    pub stale: bool,
344    pub candidates: Vec<String>,
345    pub last_persistence_error: Option<String>,
346}
347
348impl ActiveProfileBinding {
349    /// Lossless conversion to the serializable session-result shape.
350    pub fn to_session_result(&self) -> crate::profiles::ProfileSessionResult {
351        crate::profiles::ProfileSessionResult {
352            profile_name: self.profile_name.clone(),
353            source: self.source,
354            confidence: self.confidence,
355            persistent: self.persistent,
356            generated: self.generated,
357            revision: self.revision,
358            dirty: self.dirty,
359            stale: self.stale,
360            candidates: self.candidates.clone(),
361            last_persistence_error: self.last_persistence_error.clone(),
362        }
363    }
364}
365
366// ---- Flush target -----------------------------------------------------------
367
368/// Which OS-side buffer(s) a flush should clear.
369#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
370#[serde(rename_all = "lowercase")]
371pub enum FlushTarget {
372    /// Bytes the OS has received from the device but the app has not yet read.
373    Input,
374    /// Bytes the app has queued but the OS has not yet sent to the device.
375    Output,
376    /// Both input and output buffers.
377    Both,
378}
379
380impl From<FlushTarget> for ClearBuffer {
381    fn from(value: FlushTarget) -> Self {
382        match value {
383            FlushTarget::Input => ClearBuffer::Input,
384            FlushTarget::Output => ClearBuffer::Output,
385            FlushTarget::Both => ClearBuffer::All,
386        }
387    }
388}
389
390// ---- Connection summary / status --------------------------------------------
391
392/// Public-facing summary of an open connection.
393#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
394pub struct ConnectionSummary {
395    pub connection_id: String,
396    pub name: Option<String>,
397    pub port: String,
398    #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
399    pub baud_rate: u32,
400    pub flow_control: FlowControl,
401    /// Active profile-session binding. `null` for connections inserted
402    /// directly by low-level tests.
403    pub profile: Option<crate::profiles::ProfileSessionResult>,
404}
405
406/// Full status snapshot of a connection used by the `get_status` tool.
407#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
408pub struct ConnectionStatus {
409    pub connection_id: String,
410    pub name: Option<String>,
411    pub port: String,
412    #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
413    pub baud_rate: u32,
414    pub data_bits: String,
415    pub stop_bits: String,
416    pub parity: String,
417    pub flow_control: String,
418    pub is_closed: bool,
419    #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
420    pub tx_bytes: u64,
421    #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
422    pub rx_bytes: u64,
423    /// Last I/O activity as milliseconds since Unix epoch, or null.
424    #[schemars(schema_with = "crate::schema_helpers::option_uint_schema")]
425    pub last_activity_ms: Option<u64>,
426    #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
427    pub read_ops: u64,
428    #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
429    pub write_ops: u64,
430    #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
431    pub truncation_count: u64,
432    /// OS-level port identity captured at open time (vid, pid, serial,
433    /// manufacturer, etc.). `null` for connections opened without
434    /// identity data (e.g. loopback tests).
435    pub port_info: Option<PortInfo>,
436    /// Current connection health state.
437    pub state: ConnectionState,
438    /// Number of reconnect attempts since last disconnect.
439    #[schemars(schema_with = "crate::schema_helpers::uint_schema")]
440    pub reconnect_attempts: u64,
441    /// Last fatal error message, or null.
442    pub last_error: Option<String>,
443    /// Active profile-session binding. `null` for connections inserted
444    /// directly by low-level tests.
445    pub profile: Option<crate::profiles::ProfileSessionResult>,
446}
447
448// ---- Config parsing tests ---------------------------------------------------
449
450#[cfg(test)]
451mod tests {
452    use super::*;
453
454    #[test]
455    fn from_str_parses_config_enums() {
456        use std::str::FromStr;
457        assert!(matches!("5".parse::<DataBits>(), Ok(DataBits::Five)));
458        assert!(matches!("8".parse::<DataBits>(), Ok(DataBits::Eight)));
459        assert!("9".parse::<DataBits>().is_err());
460
461        assert!(matches!("1".parse::<StopBits>(), Ok(StopBits::One)));
462        assert!(matches!("2".parse::<StopBits>(), Ok(StopBits::Two)));
463        assert!("3".parse::<StopBits>().is_err());
464
465        // Parity / flow_control are case-insensitive (the intended shared behavior).
466        assert!(matches!(Parity::from_str("none"), Ok(Parity::None)));
467        assert!(matches!(Parity::from_str("Even"), Ok(Parity::Even)));
468        assert!(matches!("ODD".parse::<Parity>(), Ok(Parity::Odd)));
469        assert!("weird".parse::<Parity>().is_err());
470
471        assert!(matches!(
472            "NONE".parse::<FlowControl>(),
473            Ok(FlowControl::None)
474        ));
475        assert!(matches!(
476            "Software".parse::<FlowControl>(),
477            Ok(FlowControl::Software)
478        ));
479        assert!(matches!(
480            "hardware".parse::<FlowControl>(),
481            Ok(FlowControl::Hardware)
482        ));
483        assert!("xon".parse::<FlowControl>().is_err());
484    }
485
486    #[test]
487    fn from_str_round_trips_with_to_str() {
488        for d in [
489            DataBits::Five,
490            DataBits::Six,
491            DataBits::Seven,
492            DataBits::Eight,
493        ] {
494            let s = data_bits_to_str(d);
495            assert_eq!(data_bits_to_str(s.parse::<DataBits>().unwrap()), s);
496        }
497        for sb in [StopBits::One, StopBits::Two] {
498            let s = stop_bits_to_str(sb);
499            assert_eq!(stop_bits_to_str(s.parse::<StopBits>().unwrap()), s);
500        }
501        for p in [Parity::None, Parity::Odd, Parity::Even] {
502            let s = parity_to_str(p);
503            assert_eq!(parity_to_str(s.parse::<Parity>().unwrap()), s);
504        }
505        for f in [
506            FlowControl::None,
507            FlowControl::Software,
508            FlowControl::Hardware,
509        ] {
510            let s = flow_control_to_str(f);
511            assert_eq!(flow_control_to_str(s.parse::<FlowControl>().unwrap()), s);
512        }
513    }
514
515    #[test]
516    fn from_str_error_messages_are_descriptive() {
517        assert!("9"
518            .parse::<DataBits>()
519            .unwrap_err()
520            .contains("expected 5/6/7/8"));
521        assert!("3"
522            .parse::<StopBits>()
523            .unwrap_err()
524            .contains("expected 1/2"));
525        assert!("weird"
526            .parse::<Parity>()
527            .unwrap_err()
528            .contains("expected none/odd/even"));
529        assert!("xon"
530            .parse::<FlowControl>()
531            .unwrap_err()
532            .contains("expected none/software/hardware"));
533    }
534}