1use serde::Deserialize;
4use std::path::Path;
5
6#[derive(Debug, Default, Deserialize)]
7pub struct Config {
8 #[serde(default)]
9 pub project: ProjectSection,
10 #[serde(default)]
11 pub sim: SimSection,
12 #[serde(default)]
13 pub test: Vec<TestSpec>,
14 #[serde(default, rename = "board")]
18 pub boards: Vec<BoardSection>,
19 #[serde(default, rename = "probe")]
21 pub probes: Vec<ProbeSection>,
22 #[serde(default, rename = "decode")]
24 pub decodes: Vec<DecodeSection>,
25}
26
27#[derive(Debug, Clone, Deserialize)]
29pub struct ProbeSection {
30 #[serde(default)]
32 pub name: Option<String>,
33 pub point: String,
35}
36
37#[derive(Debug, Clone, Default, Deserialize)]
43pub struct DecodeSection {
44 pub kind: String,
46 #[serde(default)]
48 pub name: Option<String>,
49 #[serde(default)]
50 pub rx: Option<String>,
51 #[serde(default)]
52 pub sda: Option<String>,
53 #[serde(default)]
54 pub scl: Option<String>,
55 #[serde(default)]
56 pub sck: Option<String>,
57 #[serde(default)]
58 pub mosi: Option<String>,
59 #[serde(default)]
60 pub miso: Option<String>,
61 #[serde(default)]
62 pub cs: Option<String>,
63 #[serde(default)]
65 pub baud: Option<u32>,
66 #[serde(default)]
68 pub mode: Option<u8>,
69}
70
71impl DecodeSection {
72 pub fn validate(&self) -> Result<(), String> {
74 let missing = |field: &str| {
75 format!(
76 "decode {:?} needs {field}=<channel>",
77 self.name.as_deref().unwrap_or(&self.kind)
78 )
79 };
80 match self.kind.as_str() {
81 "uart" => {
82 if self.rx.as_deref().unwrap_or("").is_empty() {
83 return Err(missing("rx"));
84 }
85 }
86 "i2c" => {
87 for (field, value) in [("sda", &self.sda), ("scl", &self.scl)] {
88 if value.as_deref().unwrap_or("").is_empty() {
89 return Err(missing(field));
90 }
91 }
92 }
93 "spi" => {
94 for (field, value) in [("sck", &self.sck), ("mosi", &self.mosi), ("cs", &self.cs)] {
95 if value.as_deref().unwrap_or("").is_empty() {
96 return Err(missing(field));
97 }
98 }
99 }
100 other => {
101 return Err(format!(
102 "decode kind {other:?} is not one Litz reads; use uart, i2c or spi"
103 ));
104 }
105 }
106 if self.baud == Some(0) {
107 return Err("decode baud must be a positive number".into());
108 }
109 if self.mode.is_some_and(|mode| mode > 3) {
110 return Err("decode mode is 0 through 3".into());
111 }
112 Ok(())
113 }
114
115 pub fn label(&self) -> String {
117 if let Some(name) = &self.name {
118 return name.clone();
119 }
120 let channel = match self.kind.as_str() {
121 "i2c" => self.sda.as_deref().unwrap_or(""),
122 "spi" => self.mosi.as_deref().unwrap_or(""),
123 _ => self.rx.as_deref().unwrap_or(""),
124 };
125 if channel.is_empty() {
126 self.kind.clone()
127 } else {
128 format!("{} {}", self.kind, channel)
129 }
130 }
131}
132
133impl std::str::FromStr for DecodeSection {
134 type Err = String;
135
136 fn from_str(text: &str) -> Result<Self, String> {
140 let (kind, rest) = text
141 .split_once(':')
142 .ok_or_else(|| format!("decode {text:?} needs a kind and a colon, e.g. uart:rx=tx"))?;
143 let mut spec = DecodeSection {
144 kind: kind.trim().to_ascii_lowercase(),
145 ..DecodeSection::default()
146 };
147 if !matches!(spec.kind.as_str(), "uart" | "i2c" | "spi") {
148 return Err(format!(
149 "decode kind {:?} is not one Litz reads; use uart, i2c or spi",
150 spec.kind
151 ));
152 }
153 for pair in rest.split(',').filter(|pair| !pair.is_empty()) {
154 let (key, value) = pair
155 .split_once('=')
156 .ok_or_else(|| format!("decode option {pair:?} needs a value, as in baud=9600"))?;
157 let value = value.trim();
158 match key.trim() {
159 "name" => spec.name = Some(value.to_string()),
160 "rx" => spec.rx = Some(value.to_string()),
161 "sda" => spec.sda = Some(value.to_string()),
162 "scl" => spec.scl = Some(value.to_string()),
163 "sck" => spec.sck = Some(value.to_string()),
164 "mosi" => spec.mosi = Some(value.to_string()),
165 "miso" => spec.miso = Some(value.to_string()),
166 "cs" => spec.cs = Some(value.to_string()),
167 "baud" => {
168 spec.baud = Some(
169 value
170 .parse()
171 .map_err(|_| format!("decode baud {value:?} is not a whole number"))?,
172 );
173 }
174 "mode" => {
175 spec.mode = Some(
176 value
177 .parse()
178 .map_err(|_| format!("decode mode {value:?} is not a whole number"))?,
179 );
180 }
181 other => {
182 return Err(format!(
183 "decode option {other:?} is not one of name, rx, sda, scl, sck, \
184 mosi, miso, cs, baud, mode"
185 ));
186 }
187 }
188 }
189 spec.validate()?;
190 Ok(spec)
191 }
192}
193
194#[derive(Debug, Clone, Deserialize)]
197pub struct BoardSection {
198 pub id: String,
199 #[serde(default)]
202 pub firmware: Option<String>,
203 #[serde(default)]
204 pub bootloader: Option<String>,
205 #[serde(default)]
206 pub partition_table: Option<String>,
207 #[serde(default)]
208 pub rom: Option<String>,
209 #[serde(default)]
210 pub elf: Option<String>,
211 #[serde(default)]
212 pub runtime: Option<Runtime>,
213 #[serde(default)]
214 pub script: Option<String>,
215 #[serde(default)]
220 pub scripts: Vec<String>,
221 #[serde(default)]
222 pub flash_size: Option<String>,
223 #[serde(default)]
224 pub mac: Option<String>,
225}
226
227#[derive(Debug, Default, Deserialize)]
228pub struct ProjectSection {
229 #[serde(default)]
230 pub diagram: Option<String>,
231}
232
233impl ProjectSection {
234 pub fn diagram(&self) -> &str {
235 self.diagram.as_deref().unwrap_or("diagram.json")
236 }
237}
238
239#[derive(Debug, Default, Deserialize)]
240pub struct SimSection {
241 #[serde(default)]
242 pub firmware: Option<String>,
243 #[serde(default)]
244 pub bootloader: Option<String>,
245 #[serde(default)]
246 pub partition_table: Option<String>,
247 #[serde(default)]
248 pub rom: Option<String>,
249 #[serde(default)]
253 pub elf: Option<String>,
254 #[serde(default)]
255 pub flash_size: Option<String>,
256 #[serde(default)]
257 pub seed: Option<u64>,
258 #[serde(default)]
259 pub mac: Option<String>,
260 #[serde(default)]
264 pub runtime: Runtime,
265 #[serde(default)]
269 pub script: Option<String>,
270 #[serde(default)]
275 pub scripts: Vec<String>,
276 #[serde(default)]
279 pub analog: bool,
280 #[serde(default)]
285 pub wifi: Option<WifiSpec>,
286}
287
288#[derive(Debug, Clone, Deserialize)]
290#[serde(untagged)]
291pub enum WifiSpec {
292 Spec(String),
294 Table(WifiTable),
296}
297
298#[derive(Debug, Clone, Deserialize)]
299pub struct WifiTable {
300 pub ssid: String,
301 #[serde(default)]
302 pub psk: Option<String>,
303 #[serde(default)]
304 pub channel: Option<u8>,
305 #[serde(default)]
306 pub bssid: Option<String>,
307 #[serde(default)]
309 pub epoch: Option<u64>,
310 #[serde(default, rename = "ap")]
312 pub extra_aps: Vec<AccessPoint>,
313 #[serde(default)]
315 pub nearby: Vec<String>,
316 #[serde(default, rename = "service")]
319 pub services: Vec<ServiceSpec>,
320 #[serde(default = "yes", rename = "services")]
323 pub services_default: bool,
324 #[serde(default = "yes")]
326 pub resolve_unknown: bool,
327 #[serde(default)]
329 pub names: std::collections::BTreeMap<String, String>,
330}
331
332#[derive(Debug, Clone, Deserialize)]
333pub struct AccessPoint {
334 pub ssid: String,
335 #[serde(default)]
336 pub psk: Option<String>,
337 #[serde(default)]
338 pub channel: Option<u8>,
339 #[serde(default)]
340 pub bssid: Option<String>,
341 #[serde(default)]
342 pub epoch: Option<u64>,
343}
344
345#[derive(Debug, Clone, Deserialize)]
347pub struct ServiceSpec {
348 pub port: u16,
349 #[serde(default)]
351 pub reply: Option<String>,
352 #[serde(default)]
354 pub echo: bool,
355 #[serde(default)]
357 pub udp: bool,
358 #[serde(default)]
360 pub mqtt: bool,
361 #[serde(default)]
363 pub websocket: bool,
364 #[serde(default)]
366 pub tls: bool,
367 #[serde(default = "yes")]
370 pub wait: bool,
371}
372
373fn yes() -> bool {
374 true
375}
376
377#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize)]
378#[serde(rename_all = "lowercase")]
379pub enum Runtime {
380 #[default]
381 Native,
382 Micropython,
383 CircuitPython,
384}
385
386#[derive(Debug, Clone, Deserialize)]
387pub struct TestSpec {
388 pub name: String,
389 #[serde(default)]
390 pub timeout: Option<String>,
391 #[serde(default)]
392 pub expect: Option<OneOrMany>,
393 #[serde(default)]
394 pub fail: Option<OneOrMany>,
395 #[serde(default)]
396 pub input: Vec<Input>,
397 #[serde(default)]
398 pub expect_state: Option<OneOrMany>,
399 #[serde(default)]
402 pub state_at: Option<String>,
403 #[serde(default)]
406 pub state_stays: Option<String>,
407}
408
409impl TestSpec {
410 pub fn expect(&self) -> Vec<&str> {
411 self.expect
412 .as_ref()
413 .map(OneOrMany::as_slice)
414 .unwrap_or(&[])
415 .iter()
416 .map(String::as_str)
417 .collect()
418 }
419
420 pub fn fail(&self) -> Vec<&str> {
421 self.fail
422 .as_ref()
423 .map(OneOrMany::as_slice)
424 .unwrap_or(&[])
425 .iter()
426 .map(String::as_str)
427 .collect()
428 }
429
430 pub fn expect_state(&self) -> Vec<&str> {
431 self.expect_state
432 .as_ref()
433 .map(OneOrMany::as_slice)
434 .unwrap_or(&[])
435 .iter()
436 .map(String::as_str)
437 .collect()
438 }
439}
440
441#[derive(Debug, Clone, Deserialize)]
442#[serde(untagged)]
443pub enum OneOrMany {
444 One(String),
445 Many(Vec<String>),
446}
447
448impl OneOrMany {
449 pub fn as_slice(&self) -> &[String] {
450 match self {
451 OneOrMany::One(one) => std::slice::from_ref(one),
452 OneOrMany::Many(many) => many,
453 }
454 }
455}
456
457#[derive(Debug, Clone, Deserialize)]
458pub struct Input {
459 pub at: String,
460 #[serde(default)]
464 pub board: Option<String>,
465 #[serde(default)]
466 pub serial: Option<String>,
467 #[serde(default)]
468 pub pin: Option<String>,
469 #[serde(default)]
470 pub level: Option<u8>,
471}
472
473impl Config {
474 pub fn load(path: &Path) -> Result<Self, String> {
475 let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
476 toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))
477 }
478
479 pub fn load_project(dir: &Path) -> Result<Self, String> {
481 Self::load(&dir.join("litz.toml"))
482 }
483}
484
485pub fn parse_duration(text: &str) -> Result<u64, String> {
487 let text = text.trim();
488 let (number, scale) = if let Some(v) = text.strip_suffix("ms") {
489 (v, 1_000_000u64)
490 } else if let Some(v) = text.strip_suffix("us") {
491 (v, 1_000)
492 } else if let Some(v) = text.strip_suffix('s') {
493 (v, 1_000_000_000)
494 } else if let Some(v) = text.strip_suffix('m') {
495 (v, 60_000_000_000)
496 } else {
497 (text, 1_000_000_000)
498 };
499 let value: f64 = number
500 .trim()
501 .parse()
502 .map_err(|_| format!("{text:?} is not a duration"))?;
503 if value < 0.0 {
504 return Err(format!("{text:?} is negative"));
505 }
506 Ok((value * scale as f64) as u64)
507}
508
509pub fn parse_size(text: &str) -> Result<usize, String> {
511 let text = text.trim();
512 let upper = text.to_ascii_uppercase();
513 let (number, scale) = if let Some(v) = upper.strip_suffix("MB") {
514 (v, 1024 * 1024)
515 } else if let Some(v) = upper.strip_suffix("KB") {
516 (v, 1024)
517 } else if let Some(v) = upper.strip_suffix('M') {
518 (v, 1024 * 1024)
519 } else if let Some(v) = upper.strip_suffix('K') {
520 (v, 1024)
521 } else {
522 (upper.as_str(), 1)
523 };
524 let value: usize = number
525 .trim()
526 .parse()
527 .map_err(|_| format!("{text:?} is not a size"))?;
528 Ok(value * scale)
529}
530
531#[cfg(test)]
532mod tests {
533 use super::*;
534
535 #[test]
536 fn parses_durations() {
537 assert_eq!(parse_duration("500ms").unwrap(), 500_000_000);
538 assert_eq!(parse_duration("2s").unwrap(), 2_000_000_000);
539 assert_eq!(parse_duration("1.5s").unwrap(), 1_500_000_000);
540 assert!("soon".parse::<u64>().is_err());
541 }
542
543 #[test]
544 fn parses_sizes() {
545 assert_eq!(parse_size("4MB").unwrap(), 4 * 1024 * 1024);
546 assert_eq!(parse_size("512k").unwrap(), 512 * 1024);
547 }
548
549 #[test]
550 fn the_runtime_defaults_to_native_and_accepts_micropython() {
551 let plain: Config = toml::from_str("[sim]\nfirmware = \"app.bin\"\n").unwrap();
552 assert_eq!(plain.sim.runtime, Runtime::Native);
553 assert!(plain.sim.script.is_none());
554
555 let mp: Config = toml::from_str(
556 "[sim]\nfirmware = \"firmware.bin\"\nruntime = \"micropython\"\nscript = \"main.py\"\n",
557 )
558 .unwrap();
559 assert_eq!(mp.sim.runtime, Runtime::Micropython);
560 assert_eq!(mp.sim.script.as_deref(), Some("main.py"));
561 }
562
563 #[test]
564 fn the_runtime_accepts_circuitpython_at_sim_and_board_level() {
565 let sim: Config = toml::from_str(
566 "[sim]\nfirmware = \"firmware.bin\"\nruntime = \"circuitpython\"\nscript = \"code.py\"\n",
567 )
568 .unwrap();
569 assert_eq!(sim.sim.runtime, Runtime::CircuitPython);
570 assert_eq!(sim.sim.script.as_deref(), Some("code.py"));
571
572 let board: Config = toml::from_str(
575 "[[board]]\nid = \"esp\"\nfirmware = \"firmware.bin\"\nruntime = \"circuitpython\"\n",
576 )
577 .unwrap();
578 assert_eq!(board.boards[0].runtime, Some(Runtime::CircuitPython));
579 }
580
581 #[test]
582 fn micropython_scripts_stage_extra_modules() {
583 let config: Config = toml::from_str(
584 "[sim]\nfirmware = \"firmware.bin\"\nruntime = \"micropython\"\n\
585 script = \"main.py\"\nscripts = [\"lib/util.py\", \"board.py = src/board_esp.py\"]\n",
586 )
587 .unwrap();
588 assert_eq!(
589 config.sim.scripts,
590 ["lib/util.py", "board.py = src/board_esp.py"]
591 );
592 }
593
594 #[test]
595 fn a_test_may_have_one_expectation_or_many() {
596 let one: TestSpec = toml::from_str("name = \"a\"\nexpect = \"hi\"").unwrap();
597 assert_eq!(one.expect(), vec!["hi"]);
598 let many: TestSpec = toml::from_str("name = \"a\"\nexpect = [\"hi\", \"there\"]").unwrap();
599 assert_eq!(many.expect(), vec!["hi", "there"]);
600 }
601
602 #[test]
603 fn a_decode_command_line_names_its_channels() {
604 let uart: DecodeSection = "uart:rx=tx,baud=115200".parse().unwrap();
605 assert_eq!(uart.kind, "uart");
606 assert_eq!(uart.rx.as_deref(), Some("tx"));
607 assert_eq!(uart.baud, Some(115200));
608 assert_eq!(uart.label(), "uart tx");
609
610 let i2c: DecodeSection = "i2c:sda=sda,scl=scl,name=bus".parse().unwrap();
611 assert_eq!(i2c.label(), "bus");
612
613 let spi: DecodeSection = "spi:sck=sck,mosi=mosi,miso=miso,cs=cs,mode=3"
614 .parse()
615 .unwrap();
616 assert_eq!(spi.mode, Some(3));
617 assert_eq!(spi.miso.as_deref(), Some("miso"));
618 }
619
620 #[test]
621 fn a_decode_command_line_refuses_a_kind_without_its_channels() {
622 assert!("uart".parse::<DecodeSection>().is_err());
623 assert!("uart:tx".parse::<DecodeSection>().is_err());
624 assert!("uart:rx=tx,rate=9600".parse::<DecodeSection>().is_err());
625 assert!("i2c:sda=a".parse::<DecodeSection>().is_err());
626 assert!("spi:sck=c,mosi=d".parse::<DecodeSection>().is_err());
627 assert!("can:rx=tx".parse::<DecodeSection>().is_err());
628 assert!("uart:rx=tx,baud=0".parse::<DecodeSection>().is_err());
629 assert!(
630 "spi:sck=c,mosi=d,cs=e,mode=4"
631 .parse::<DecodeSection>()
632 .is_err()
633 );
634 }
635
636 #[test]
637 fn a_decode_table_reads_the_same_fields() {
638 let config: Config = toml::from_str(
639 "[[decode]]\nkind = \"i2c\"\nsda = \"sda\"\nscl = \"scl\"\nname = \"oled\"\n",
640 )
641 .unwrap();
642 assert_eq!(config.decodes.len(), 1);
643 assert_eq!(config.decodes[0].label(), "oled");
644 config.decodes[0].validate().unwrap();
645 }
646}