mod config;
mod connection;
mod manager;
mod port_info;
pub mod test_support;
pub(crate) use config::{data_bits_to_str, flow_control_to_str, parity_to_str, stop_bits_to_str};
pub use config::{
is_fatal_disconnect, ActiveProfileBinding, ConnectionConfig, ConnectionState, ConnectionStatus,
ConnectionSummary, DataBits, FlowControl, FlushTarget, Parity, ReconnectPolicy, StopBits,
MAX_BAUD_RATE,
};
pub use connection::{SerialConnection, SerialIo};
pub use manager::{ConnectionManager, ConnectionOpener};
pub use port_info::{PortInfo, PortProvider, PortTransport, SystemPortProvider};
#[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, ProfileMetadata, ProfilePersistenceResult, ProfileRevision, ProfileSelector,
ProfileSessionResult,
};
use crate::serial::{ConnectionStatus, PortInfo, PortTransport};
use crate::tools::types::{
CaptureBootArgs, CaptureBootReset, CaptureBootResult, ClearLogResult, CloseResult,
ComputeChecksumResult, ConfigureResult, DeleteProfileResult, ExportLogResult, FlushResult,
GetLogResult, GetStatusResult, ListConnectionsResult, ListPortsResult, ListProfilesResult,
OpenResult, PortProfileMatch, ProfileMatchCandidate, ReadResult, ReconfigureResult,
ReconnectResult, RollbackProfileArgs, RollbackProfileResult, SaveProfileResult,
SendBreakResult, SetDtrRtsResult, SetFlowControlResult, TransactResult, WriteResult,
};
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
}
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),
);
}
};
}
check_schema!(port_info_has_no_uint_formats, PortInfo);
check_schema!(connection_status_has_no_uint_formats, ConnectionStatus);
#[test]
fn port_info_optional_usb_fields_not_required() {
let schema = schema_for!(PortInfo);
let json = serde_json::to_value(&schema).expect("schema serializes");
let required: Vec<&str> = json
.pointer("/required")
.and_then(Value::as_array)
.expect("PortInfo schema must have a required list")
.iter()
.filter_map(Value::as_str)
.collect();
for field in ["vid", "pid", "interface"] {
assert!(
!required.contains(&field),
"PortInfo schema lists optional USB field `{field}` in \
required={required:?}; non-USB ports omit it during \
serialization and MCP clients reject the payload. Keep \
`#[serde(skip_serializing_if = \"Option::is_none\")]` and \
add `default` (see src/port_info.rs)."
);
assert!(
json.pointer(&format!("/properties/{field}")).is_some(),
"PortInfo schema is missing the `{field}` property"
);
}
for field in ["name", "display_name", "description", "transport"] {
assert!(
required.contains(&field),
"PortInfo schema must keep `{field}` in required, got \
required={required:?}"
);
}
let non_usb = PortInfo {
name: "/dev/ttyS0".into(),
display_name: "ttyS0".into(),
description: "Serial Port".into(),
hardware_id: None,
transport: PortTransport::Unknown,
vid: None,
pid: None,
serial_number: None,
manufacturer: None,
product: None,
interface: None,
};
let serialized = serde_json::to_value(&non_usb).expect("PortInfo serializes");
let obj = serialized
.as_object()
.expect("serialized PortInfo must be a JSON object");
for field in ["vid", "pid", "interface"] {
assert!(
!obj.contains_key(field),
"serialized non-USB PortInfo must omit `{field}`, got keys: {:?}",
obj.keys().collect::<Vec<_>>()
);
}
for field in ["vid", "pid", "interface"] {
let prop = json
.pointer(&format!("/properties/{field}"))
.expect("PortInfo schema must declare the `{field}` property");
assert!(
prop.get("default").is_none(),
"PortInfo schema property `{field}` must not carry a \
\"default\" key, got: {prop}"
);
}
}
#[test]
fn diagnose_port_args_baud_rate_not_required() {
let schema = schema_for!(crate::prompts::types::DiagnosePortArgs);
let json = serde_json::to_value(&schema).expect("schema serializes");
let required: Vec<&str> = json
.pointer("/required")
.and_then(Value::as_array)
.expect("DiagnosePortArgs schema must have a required list")
.iter()
.filter_map(Value::as_str)
.collect();
assert!(
!required.contains(&"baud_rate"),
"DiagnosePortArgs schema lists optional field `baud_rate` in \
required={required:?}; callers omit it during serialization \
and strict MCP clients reject the arguments. Keep \
`#[serde(skip_serializing_if = \"Option::is_none\")]` and add \
`default` (see src/prompts/types.rs)."
);
assert!(
json.pointer("/properties/baud_rate").is_some(),
"DiagnosePortArgs schema is missing the `baud_rate` property"
);
let prop = json
.pointer("/properties/baud_rate")
.expect("DiagnosePortArgs schema must declare `baud_rate`");
assert!(
prop.get("default").is_none(),
"DiagnosePortArgs schema property `baud_rate` must not carry a \
\"default\" key, got: {prop}"
);
let args = crate::prompts::types::DiagnosePortArgs {
port: "/dev/ttyUSB0".into(),
baud_rate: None,
};
let obj = serde_json::to_value(&args)
.expect("DiagnosePortArgs serializes")
.as_object()
.expect("serialized DiagnosePortArgs must be a JSON object")
.clone();
assert!(
!obj.contains_key("baud_rate"),
"serialized DiagnosePortArgs must omit `baud_rate`, got keys: {:?}",
obj.keys().collect::<Vec<_>>()
);
}
check_schema!(profile_has_no_uint_formats, Profile);
check_schema!(profile_selector_has_no_uint_formats, ProfileSelector);
check_schema!(profile_metadata_has_no_uint_formats, ProfileMetadata);
check_schema!(profile_revision_has_no_uint_formats, ProfileRevision);
check_schema!(
profile_session_result_has_no_uint_formats,
ProfileSessionResult
);
check_schema!(list_ports_result_has_no_uint_formats, ListPortsResult);
check_schema!(
profile_match_candidate_has_no_uint_formats,
ProfileMatchCandidate
);
check_schema!(port_profile_match_has_no_uint_formats, PortProfileMatch);
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!(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);
check_schema!(configure_result_has_no_uint_formats, ConfigureResult);
check_schema!(
compute_checksum_result_has_no_uint_formats,
ComputeChecksumResult
);
check_schema!(transact_result_has_no_uint_formats, TransactResult);
check_schema!(capture_boot_args_has_no_uint_formats, CaptureBootArgs);
check_schema!(capture_boot_reset_has_no_uint_formats, CaptureBootReset);
check_schema!(capture_boot_result_has_no_uint_formats, CaptureBootResult);
check_schema!(
rollback_profile_args_has_no_uint_formats,
RollbackProfileArgs
);
check_schema!(
rollback_profile_result_has_no_uint_formats,
RollbackProfileResult
);
check_schema!(
profile_persistence_result_has_no_uint_formats,
ProfilePersistenceResult
);
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);
check_schema!(parsed_frame_has_no_uint_formats, ParsedFrame);
check_schema!(frame_has_no_uint_formats, Frame);
check_schema!(
profile_defaults_has_no_uint_formats,
crate::profiles::ProfileDefaults
);
}