use crate::match_config::PatternEncoding;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct RxFramingConfig {
#[serde(flatten)]
pub mode: RxFramingMode,
#[serde(default)]
#[schemars(schema_with = "crate::schema_helpers::option_uint_schema")]
pub max_frames: Option<usize>,
#[serde(default)]
pub include_terminators: bool,
#[serde(default)]
pub skip_empty: bool,
}
impl Default for RxFramingConfig {
fn default() -> Self {
Self {
mode: RxFramingMode::Line {
ending: LineEnding::Auto,
},
max_frames: None,
include_terminators: false,
skip_empty: false,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum RxFramingMode {
#[serde(rename_all = "snake_case")]
Line {
#[serde(default)]
ending: LineEnding,
},
#[serde(rename_all = "snake_case")]
Delimiter {
delimiter: String,
#[serde(default = "default_encoding")]
delimiter_encoding: PatternEncoding,
},
#[serde(rename_all = "snake_case")]
LengthPrefixed {
#[schemars(schema_with = "crate::schema_helpers::uint_schema")]
prefix_size: u8,
#[serde(default)]
endianness: Endianness,
#[serde(default)]
#[schemars(schema_with = "crate::schema_helpers::option_uint_schema")]
initial_offset: Option<usize>,
},
#[serde(rename_all = "snake_case")]
StartEnd {
start: Vec<String>,
end: String,
#[serde(default = "default_encoding")]
marker_encoding: PatternEncoding,
#[serde(default)]
include_markers: bool,
},
#[serde(rename_all = "snake_case")]
Slip,
#[serde(rename_all = "snake_case")]
Cobs,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
#[serde(rename_all = "snake_case")]
pub enum LineEnding {
#[default]
Auto,
Lf,
Cr,
Crlf,
}
fn default_encoding() -> PatternEncoding {
PatternEncoding::Utf8
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum ProtocolPreset {
AtCommand,
Slip,
JsonLines,
Cobs,
Ndjson,
Nmea0183,
ModbusAscii,
}
pub fn preset_tx_framing(p: ProtocolPreset) -> TxFramingConfig {
match p {
ProtocolPreset::AtCommand => TxFramingConfig {
mode: TxFramingMode::Line {
ending: TxLineEnding::Cr,
},
},
ProtocolPreset::Slip => TxFramingConfig {
mode: TxFramingMode::Slip,
},
ProtocolPreset::JsonLines | ProtocolPreset::Ndjson => TxFramingConfig {
mode: TxFramingMode::Line {
ending: TxLineEnding::Lf,
},
},
ProtocolPreset::Cobs => TxFramingConfig {
mode: TxFramingMode::Cobs,
},
ProtocolPreset::Nmea0183 => TxFramingConfig {
mode: TxFramingMode::Nmea,
},
ProtocolPreset::ModbusAscii => TxFramingConfig {
mode: TxFramingMode::StartEnd {
start: vec![":".into()],
end: "\r\n".into(),
marker_encoding: PatternEncoding::Utf8,
},
},
}
}
pub fn preset_rx_framing(p: ProtocolPreset) -> RxFramingConfig {
let (mode, skip_empty) = match p {
ProtocolPreset::AtCommand | ProtocolPreset::JsonLines => (
RxFramingMode::Line {
ending: LineEnding::Auto,
},
false,
),
ProtocolPreset::Slip => (RxFramingMode::Slip, false),
ProtocolPreset::Cobs => (RxFramingMode::Cobs, false),
ProtocolPreset::Ndjson => (
RxFramingMode::Line {
ending: LineEnding::Auto,
},
true,
),
ProtocolPreset::Nmea0183 => (
RxFramingMode::StartEnd {
start: vec!["$".into(), "!".into()],
end: "\r\n".into(),
marker_encoding: PatternEncoding::Utf8,
include_markers: false,
},
false,
),
ProtocolPreset::ModbusAscii => (
RxFramingMode::StartEnd {
start: vec![":".into()],
end: "\r\n".into(),
marker_encoding: PatternEncoding::Utf8,
include_markers: false,
},
false,
),
};
RxFramingConfig {
mode,
max_frames: None,
include_terminators: false,
skip_empty,
}
}
pub fn preset_rx_parser(p: ProtocolPreset) -> ParserConfig {
let (parser_type, validate) = match p {
ProtocolPreset::AtCommand => (ParserType::AtCommand, false),
ProtocolPreset::Slip | ProtocolPreset::Cobs => (ParserType::Raw, false),
ProtocolPreset::JsonLines | ProtocolPreset::Ndjson => (ParserType::JsonLines, false),
ProtocolPreset::Nmea0183 => (ParserType::Nmea, true),
ProtocolPreset::ModbusAscii => (ParserType::ModbusAscii, true),
};
ParserConfig {
parser_type,
custom_prompt: None,
validate,
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct TxFramingConfig {
#[serde(flatten)]
pub mode: TxFramingMode,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum TxFramingMode {
#[serde(rename_all = "snake_case")]
Line {
ending: TxLineEnding,
},
#[serde(rename_all = "snake_case")]
Delimiter {
delimiter: String,
#[serde(default = "default_encoding")]
delimiter_encoding: PatternEncoding,
},
#[serde(rename_all = "snake_case")]
LengthPrefixed {
#[schemars(schema_with = "crate::schema_helpers::uint_schema")]
prefix_size: u8,
#[serde(default)]
endianness: Endianness,
},
#[serde(rename_all = "snake_case")]
StartEnd {
start: Vec<String>,
end: String,
#[serde(default = "default_encoding")]
marker_encoding: PatternEncoding,
},
#[serde(rename_all = "snake_case")]
Slip,
#[serde(rename_all = "snake_case")]
Cobs,
#[serde(rename_all = "snake_case")]
Nmea,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum TxLineEnding {
Lf,
Cr,
Crlf,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Default)]
#[serde(rename_all = "snake_case")]
pub enum Endianness {
#[default]
Big,
Little,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct ParserConfig {
#[serde(rename = "type")]
pub parser_type: ParserType,
#[serde(default)]
pub custom_prompt: Option<String>,
#[serde(default)]
pub validate: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ParserType {
AtCommand,
JsonLines,
ShellPrompt,
Raw,
Nmea,
ModbusAscii,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn line_ending_default_is_auto() {
let val = serde_json::json!({"type": "line"});
let mode: RxFramingMode = serde_json::from_value(val).unwrap();
assert!(matches!(
mode,
RxFramingMode::Line {
ending: LineEnding::Auto
}
));
}
fn assert_preset_roundtrip(variant_str: &str, expected: ProtocolPreset) {
let val = serde_json::json!({ "type": variant_str });
let p: ProtocolPreset = serde_json::from_value(val.clone()).unwrap();
assert_eq!(p, expected);
assert_eq!(serde_json::to_value(p).unwrap(), val);
assert!(
serde_json::from_value::<ProtocolPreset>(serde_json::json!(variant_str)).is_err(),
"bare string form {variant_str:?} must be rejected (tagged-object shape required)"
);
}
struct PresetTestRow {
preset: ProtocolPreset,
wire_name: &'static str,
expected_tx: TxFramingConfig,
expected_rx: RxFramingConfig,
expected_parser: ParserConfig,
equivalence_skip: Option<&'static str>,
}
fn preset_test_table() -> Vec<PresetTestRow> {
vec![
PresetTestRow {
preset: ProtocolPreset::AtCommand,
wire_name: "at_command",
expected_tx: TxFramingConfig {
mode: TxFramingMode::Line {
ending: TxLineEnding::Cr,
},
},
expected_rx: RxFramingConfig {
mode: RxFramingMode::Line {
ending: LineEnding::Auto,
},
max_frames: None,
include_terminators: false,
skip_empty: false,
},
expected_parser: ParserConfig {
parser_type: ParserType::AtCommand,
custom_prompt: None,
validate: false,
},
equivalence_skip: None,
},
PresetTestRow {
preset: ProtocolPreset::Slip,
wire_name: "slip",
expected_tx: TxFramingConfig {
mode: TxFramingMode::Slip,
},
expected_rx: RxFramingConfig {
mode: RxFramingMode::Slip,
max_frames: None,
include_terminators: false,
skip_empty: false,
},
expected_parser: ParserConfig {
parser_type: ParserType::Raw,
custom_prompt: None,
validate: false,
},
equivalence_skip: None,
},
PresetTestRow {
preset: ProtocolPreset::JsonLines,
wire_name: "json_lines",
expected_tx: TxFramingConfig {
mode: TxFramingMode::Line {
ending: TxLineEnding::Lf,
},
},
expected_rx: RxFramingConfig {
mode: RxFramingMode::Line {
ending: LineEnding::Auto,
},
max_frames: None,
include_terminators: false,
skip_empty: false,
},
expected_parser: ParserConfig {
parser_type: ParserType::JsonLines,
custom_prompt: None,
validate: false,
},
equivalence_skip: None,
},
PresetTestRow {
preset: ProtocolPreset::Cobs,
wire_name: "cobs",
expected_tx: TxFramingConfig {
mode: TxFramingMode::Cobs,
},
expected_rx: RxFramingConfig {
mode: RxFramingMode::Cobs,
max_frames: None,
include_terminators: false,
skip_empty: false,
},
expected_parser: ParserConfig {
parser_type: ParserType::Raw,
custom_prompt: None,
validate: false,
},
equivalence_skip: None,
},
PresetTestRow {
preset: ProtocolPreset::Ndjson,
wire_name: "ndjson",
expected_tx: TxFramingConfig {
mode: TxFramingMode::Line {
ending: TxLineEnding::Lf,
},
},
expected_rx: RxFramingConfig {
mode: RxFramingMode::Line {
ending: LineEnding::Auto,
},
max_frames: None,
include_terminators: false,
skip_empty: true,
},
expected_parser: ParserConfig {
parser_type: ParserType::JsonLines,
custom_prompt: None,
validate: false,
},
equivalence_skip: None,
},
PresetTestRow {
preset: ProtocolPreset::Nmea0183,
wire_name: "nmea0183",
expected_tx: TxFramingConfig {
mode: TxFramingMode::Nmea,
},
expected_rx: RxFramingConfig {
mode: RxFramingMode::StartEnd {
start: vec!["$".into(), "!".into()],
end: "\r\n".into(),
marker_encoding: PatternEncoding::Utf8,
include_markers: false,
},
max_frames: None,
include_terminators: false,
skip_empty: false,
},
expected_parser: ParserConfig {
parser_type: ParserType::Nmea,
custom_prompt: None,
validate: true,
},
equivalence_skip: None,
},
PresetTestRow {
preset: ProtocolPreset::ModbusAscii,
wire_name: "modbus_ascii",
expected_tx: TxFramingConfig {
mode: TxFramingMode::StartEnd {
start: vec![":".into()],
end: "\r\n".into(),
marker_encoding: PatternEncoding::Utf8,
},
},
expected_rx: RxFramingConfig {
mode: RxFramingMode::StartEnd {
start: vec![":".into()],
end: "\r\n".into(),
marker_encoding: PatternEncoding::Utf8,
include_markers: false,
},
max_frames: None,
include_terminators: false,
skip_empty: false,
},
expected_parser: ParserConfig {
parser_type: ParserType::ModbusAscii,
custom_prompt: None,
validate: true,
},
equivalence_skip: None,
},
]
}
#[test]
fn preset_tx_framing_matches_table() {
for row in preset_test_table() {
let cfg = preset_tx_framing(row.preset);
assert_eq!(cfg.mode, row.expected_tx.mode);
}
}
#[test]
fn preset_rx_framing_matches_table() {
for row in preset_test_table() {
let cfg = preset_rx_framing(row.preset);
assert_eq!(cfg.mode, row.expected_rx.mode);
assert_eq!(cfg.skip_empty, row.expected_rx.skip_empty);
}
}
#[test]
fn preset_rx_parser_matches_table() {
for row in preset_test_table() {
let cfg = preset_rx_parser(row.preset);
assert_eq!(cfg.parser_type, row.expected_parser.parser_type);
assert_eq!(cfg.validate, row.expected_parser.validate);
}
}
#[test]
fn protocol_preset_tagged_object_roundtrips() {
for row in preset_test_table() {
assert_preset_roundtrip(row.wire_name, row.preset);
}
}
#[test]
fn presets_equivalent_to_bare_configs() {
for row in preset_test_table() {
if let Some(reason) = row.equivalence_skip {
eprintln!("skipping equivalence for {}: {}", row.wire_name, reason);
continue;
}
let preset_tx = preset_tx_framing(row.preset);
assert_eq!(preset_tx, row.expected_tx, "{} TX", row.wire_name);
let preset_rx = preset_rx_framing(row.preset);
assert_eq!(preset_rx, row.expected_rx, "{} RX", row.wire_name);
let preset_parser = preset_rx_parser(row.preset);
assert_eq!(
preset_parser, row.expected_parser,
"{} parser",
row.wire_name
);
}
}
#[test]
fn skip_empty_default_is_false() {
assert!(!RxFramingConfig::default().skip_empty);
}
#[test]
fn skip_empty_off_by_default_in_preset_json_lines() {
assert!(!preset_rx_framing(ProtocolPreset::JsonLines).skip_empty);
}
#[test]
fn skip_empty_on_in_preset_ndjson() {
assert!(preset_rx_framing(ProtocolPreset::Ndjson).skip_empty);
}
}