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 #[serde(default)]
291 pub wifi_sta: Option<String>,
292}
293
294#[derive(Debug, Clone, Deserialize)]
296#[serde(untagged)]
297pub enum WifiSpec {
298 Spec(String),
300 Table(WifiTable),
302}
303
304#[derive(Debug, Clone, Deserialize)]
305pub struct WifiTable {
306 pub ssid: String,
307 #[serde(default)]
308 pub psk: Option<String>,
309 #[serde(default)]
310 pub channel: Option<u8>,
311 #[serde(default)]
312 pub bssid: Option<String>,
313 #[serde(default)]
315 pub epoch: Option<u64>,
316 #[serde(default, rename = "ap")]
318 pub extra_aps: Vec<AccessPoint>,
319 #[serde(default)]
321 pub nearby: Vec<String>,
322 #[serde(default, rename = "service")]
325 pub services: Vec<ServiceSpec>,
326 #[serde(default = "yes", rename = "services")]
329 pub services_default: bool,
330 #[serde(default = "yes")]
332 pub resolve_unknown: bool,
333 #[serde(default)]
335 pub names: std::collections::BTreeMap<String, String>,
336}
337
338#[derive(Debug, Clone, Deserialize)]
339pub struct AccessPoint {
340 pub ssid: String,
341 #[serde(default)]
342 pub psk: Option<String>,
343 #[serde(default)]
344 pub channel: Option<u8>,
345 #[serde(default)]
346 pub bssid: Option<String>,
347 #[serde(default)]
348 pub epoch: Option<u64>,
349}
350
351#[derive(Debug, Clone, Deserialize)]
353pub struct ServiceSpec {
354 pub port: u16,
355 #[serde(default)]
357 pub reply: Option<String>,
358 #[serde(default)]
360 pub echo: bool,
361 #[serde(default)]
363 pub udp: bool,
364 #[serde(default)]
366 pub mqtt: bool,
367 #[serde(default)]
369 pub websocket: bool,
370 #[serde(default)]
372 pub tls: bool,
373 #[serde(default = "yes")]
376 pub wait: bool,
377}
378
379fn yes() -> bool {
380 true
381}
382
383#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize)]
384#[serde(rename_all = "lowercase")]
385pub enum Runtime {
386 #[default]
387 Native,
388 Micropython,
389 CircuitPython,
390}
391
392#[derive(Debug, Clone, Deserialize)]
393pub struct TestSpec {
394 pub name: String,
395 #[serde(default)]
396 pub timeout: Option<String>,
397 #[serde(default)]
398 pub expect: Option<OneOrMany>,
399 #[serde(default)]
400 pub fail: Option<OneOrMany>,
401 #[serde(default)]
402 pub input: Vec<Input>,
403 #[serde(default)]
404 pub expect_state: Option<OneOrMany>,
405 #[serde(default)]
408 pub state_at: Option<String>,
409 #[serde(default)]
412 pub state_stays: Option<String>,
413}
414
415impl TestSpec {
416 pub fn expect(&self) -> Vec<&str> {
417 self.expect
418 .as_ref()
419 .map(OneOrMany::as_slice)
420 .unwrap_or(&[])
421 .iter()
422 .map(String::as_str)
423 .collect()
424 }
425
426 pub fn fail(&self) -> Vec<&str> {
427 self.fail
428 .as_ref()
429 .map(OneOrMany::as_slice)
430 .unwrap_or(&[])
431 .iter()
432 .map(String::as_str)
433 .collect()
434 }
435
436 pub fn expect_state(&self) -> Vec<&str> {
437 self.expect_state
438 .as_ref()
439 .map(OneOrMany::as_slice)
440 .unwrap_or(&[])
441 .iter()
442 .map(String::as_str)
443 .collect()
444 }
445}
446
447#[derive(Debug, Clone, Deserialize)]
448#[serde(untagged)]
449pub enum OneOrMany {
450 One(String),
451 Many(Vec<String>),
452}
453
454impl OneOrMany {
455 pub fn as_slice(&self) -> &[String] {
456 match self {
457 OneOrMany::One(one) => std::slice::from_ref(one),
458 OneOrMany::Many(many) => many,
459 }
460 }
461}
462
463#[derive(Debug, Clone, Deserialize)]
464pub struct Input {
465 pub at: String,
466 #[serde(default)]
470 pub board: Option<String>,
471 #[serde(default)]
472 pub serial: Option<String>,
473 #[serde(default)]
474 pub pin: Option<String>,
475 #[serde(default)]
476 pub level: Option<u8>,
477}
478
479impl Config {
480 pub fn load(path: &Path) -> Result<Self, String> {
481 let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
482 toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))
483 }
484
485 pub fn load_project(dir: &Path) -> Result<Self, String> {
487 Self::load(&dir.join("litz.toml"))
488 }
489}
490
491pub fn parse_duration(text: &str) -> Result<u64, String> {
493 let text = text.trim();
494 let (number, scale) = if let Some(v) = text.strip_suffix("ms") {
495 (v, 1_000_000u64)
496 } else if let Some(v) = text.strip_suffix("us") {
497 (v, 1_000)
498 } else if let Some(v) = text.strip_suffix('s') {
499 (v, 1_000_000_000)
500 } else if let Some(v) = text.strip_suffix('m') {
501 (v, 60_000_000_000)
502 } else {
503 (text, 1_000_000_000)
504 };
505 let value: f64 = number
506 .trim()
507 .parse()
508 .map_err(|_| format!("{text:?} is not a duration"))?;
509 if value < 0.0 {
510 return Err(format!("{text:?} is negative"));
511 }
512 Ok((value * scale as f64) as u64)
513}
514
515pub fn parse_size(text: &str) -> Result<usize, String> {
517 let text = text.trim();
518 let upper = text.to_ascii_uppercase();
519 let (number, scale) = if let Some(v) = upper.strip_suffix("MB") {
520 (v, 1024 * 1024)
521 } else if let Some(v) = upper.strip_suffix("KB") {
522 (v, 1024)
523 } else if let Some(v) = upper.strip_suffix('M') {
524 (v, 1024 * 1024)
525 } else if let Some(v) = upper.strip_suffix('K') {
526 (v, 1024)
527 } else {
528 (upper.as_str(), 1)
529 };
530 let value: usize = number
531 .trim()
532 .parse()
533 .map_err(|_| format!("{text:?} is not a size"))?;
534 Ok(value * scale)
535}
536
537#[cfg(test)]
538mod tests {
539 use super::*;
540
541 #[test]
542 fn parses_durations() {
543 assert_eq!(parse_duration("500ms").unwrap(), 500_000_000);
544 assert_eq!(parse_duration("2s").unwrap(), 2_000_000_000);
545 assert_eq!(parse_duration("1.5s").unwrap(), 1_500_000_000);
546 assert!("soon".parse::<u64>().is_err());
547 }
548
549 #[test]
550 fn parses_sizes() {
551 assert_eq!(parse_size("4MB").unwrap(), 4 * 1024 * 1024);
552 assert_eq!(parse_size("512k").unwrap(), 512 * 1024);
553 }
554
555 #[test]
556 fn the_runtime_defaults_to_native_and_accepts_micropython() {
557 let plain: Config = toml::from_str("[sim]\nfirmware = \"app.bin\"\n").unwrap();
558 assert_eq!(plain.sim.runtime, Runtime::Native);
559 assert!(plain.sim.script.is_none());
560
561 let mp: Config = toml::from_str(
562 "[sim]\nfirmware = \"firmware.bin\"\nruntime = \"micropython\"\nscript = \"main.py\"\n",
563 )
564 .unwrap();
565 assert_eq!(mp.sim.runtime, Runtime::Micropython);
566 assert_eq!(mp.sim.script.as_deref(), Some("main.py"));
567 }
568
569 #[test]
570 fn the_runtime_accepts_circuitpython_at_sim_and_board_level() {
571 let sim: Config = toml::from_str(
572 "[sim]\nfirmware = \"firmware.bin\"\nruntime = \"circuitpython\"\nscript = \"code.py\"\n",
573 )
574 .unwrap();
575 assert_eq!(sim.sim.runtime, Runtime::CircuitPython);
576 assert_eq!(sim.sim.script.as_deref(), Some("code.py"));
577
578 let board: Config = toml::from_str(
581 "[[board]]\nid = \"esp\"\nfirmware = \"firmware.bin\"\nruntime = \"circuitpython\"\n",
582 )
583 .unwrap();
584 assert_eq!(board.boards[0].runtime, Some(Runtime::CircuitPython));
585 }
586
587 #[test]
588 fn micropython_scripts_stage_extra_modules() {
589 let config: Config = toml::from_str(
590 "[sim]\nfirmware = \"firmware.bin\"\nruntime = \"micropython\"\n\
591 script = \"main.py\"\nscripts = [\"lib/util.py\", \"board.py = src/board_esp.py\"]\n",
592 )
593 .unwrap();
594 assert_eq!(
595 config.sim.scripts,
596 ["lib/util.py", "board.py = src/board_esp.py"]
597 );
598 }
599
600 #[test]
601 fn a_test_may_have_one_expectation_or_many() {
602 let one: TestSpec = toml::from_str("name = \"a\"\nexpect = \"hi\"").unwrap();
603 assert_eq!(one.expect(), vec!["hi"]);
604 let many: TestSpec = toml::from_str("name = \"a\"\nexpect = [\"hi\", \"there\"]").unwrap();
605 assert_eq!(many.expect(), vec!["hi", "there"]);
606 }
607
608 #[test]
609 fn a_decode_command_line_names_its_channels() {
610 let uart: DecodeSection = "uart:rx=tx,baud=115200".parse().unwrap();
611 assert_eq!(uart.kind, "uart");
612 assert_eq!(uart.rx.as_deref(), Some("tx"));
613 assert_eq!(uart.baud, Some(115200));
614 assert_eq!(uart.label(), "uart tx");
615
616 let i2c: DecodeSection = "i2c:sda=sda,scl=scl,name=bus".parse().unwrap();
617 assert_eq!(i2c.label(), "bus");
618
619 let spi: DecodeSection = "spi:sck=sck,mosi=mosi,miso=miso,cs=cs,mode=3"
620 .parse()
621 .unwrap();
622 assert_eq!(spi.mode, Some(3));
623 assert_eq!(spi.miso.as_deref(), Some("miso"));
624 }
625
626 #[test]
627 fn a_decode_command_line_refuses_a_kind_without_its_channels() {
628 assert!("uart".parse::<DecodeSection>().is_err());
629 assert!("uart:tx".parse::<DecodeSection>().is_err());
630 assert!("uart:rx=tx,rate=9600".parse::<DecodeSection>().is_err());
631 assert!("i2c:sda=a".parse::<DecodeSection>().is_err());
632 assert!("spi:sck=c,mosi=d".parse::<DecodeSection>().is_err());
633 assert!("can:rx=tx".parse::<DecodeSection>().is_err());
634 assert!("uart:rx=tx,baud=0".parse::<DecodeSection>().is_err());
635 assert!(
636 "spi:sck=c,mosi=d,cs=e,mode=4"
637 .parse::<DecodeSection>()
638 .is_err()
639 );
640 }
641
642 #[test]
643 fn a_decode_table_reads_the_same_fields() {
644 let config: Config = toml::from_str(
645 "[[decode]]\nkind = \"i2c\"\nsda = \"sda\"\nscl = \"scl\"\nname = \"oled\"\n",
646 )
647 .unwrap();
648 assert_eq!(config.decodes.len(), 1);
649 assert_eq!(config.decodes[0].label(), "oled");
650 config.decodes[0].validate().unwrap();
651 }
652}