Skip to main content

litz_engine/
config.rs

1//! `litz.toml`: which firmware to run and what to assert.
2
3use 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    /// One entry per development board when the diagram has more than one.
15    /// Each board boots its own firmware; `[sim]` stays the shared defaults
16    /// and, in a project with no `[[board]]`, the single board's settings.
17    #[serde(default, rename = "board")]
18    pub boards: Vec<BoardSection>,
19    /// Points a run records for a scope or a report.
20    #[serde(default, rename = "probe")]
21    pub probes: Vec<ProbeSection>,
22    /// Protocols a run reads off the probed channels.
23    #[serde(default, rename = "decode")]
24    pub decodes: Vec<DecodeSection>,
25}
26
27/// One `[[probe]]`: a point in the circuit to watch.
28#[derive(Debug, Clone, Deserialize)]
29pub struct ProbeSection {
30    /// The name a report and the CSV column use. Defaults to the point text.
31    #[serde(default)]
32    pub name: Option<String>,
33    /// `<board>:<GPIO>` or `<part>:<pin>`, e.g. `esp:GPIO8` or `led1:A`.
34    pub point: String,
35}
36
37/// One `[[decode]]`: a protocol read off channels the project already probes.
38///
39/// The fields a kind does not use are left out; `uart` names `rx`, `i2c` names
40/// `sda` and `scl`, `spi` names `sck`, `mosi` and `cs` (and optionally `miso`).
41/// The command line spells the same thing as `--decode uart:rx=tx,baud=9600`.
42#[derive(Debug, Clone, Default, Deserialize)]
43pub struct DecodeSection {
44    /// `uart`, `i2c` or `spi`.
45    pub kind: String,
46    /// The label a report uses. Defaults to the kind and its first channel.
47    #[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    /// UART bit rate. Absent means the shortest run on the channel is one bit.
64    #[serde(default)]
65    pub baud: Option<u32>,
66    /// SPI mode, 0 through 3: CPOL and CPHA. Defaults to 0.
67    #[serde(default)]
68    pub mode: Option<u8>,
69}
70
71impl DecodeSection {
72    /// Reject a kind with missing or extra channel names before a run starts.
73    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    /// The label a report prints before the decoded bytes.
116    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    /// `uart:rx=tx,baud=115200` — the command line's spelling of a
137    /// `[[decode]]` entry. Channel names are probe names, so they cannot
138    /// contain a comma or an equals sign.
139    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/// One `[[board]]`: the firmware and overrides for the development board whose
195/// instance id is `id` in `diagram.json`.
196#[derive(Debug, Clone, Deserialize)]
197pub struct BoardSection {
198    pub id: String,
199    /// The application image this board boots. Required when `[[board]]` is
200    /// used; a project with one board keeps naming it under `[sim] firmware`.
201    #[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    /// Additional Python modules staged onto the device before the entry
216    /// script runs. Only read when the runtime is a Python one (`micropython`
217    /// or `circuitpython`); paths are relative to the project and keep their
218    /// directory shape on the device.
219    #[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    /// The firmware's ELF, relative to the project. The image runs without it;
250    /// the symbol table is what lets the machine start a Bluetooth controller
251    /// inside the guest, and what names addresses in logs and the debugger.
252    #[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    /// Which runtime the firmware speaks to the console. `native` is a bare
261    /// program; `micropython` and `circuitpython` are the stock firmwares whose
262    /// REPLs accept a pasted script.
263    #[serde(default)]
264    pub runtime: Runtime,
265    /// A Python file pasted into a MicroPython or CircuitPython REPL after
266    /// boot. Only read when the runtime is a Python one; the path is relative
267    /// to the project.
268    #[serde(default)]
269    pub script: Option<String>,
270    /// Modules pasted alongside the entry script, as `path` or
271    /// `name = path`. Each keeps its relative path on the device, so
272    /// `"lib/util.py"` becomes `/lib/util.py` and `import util` works after
273    /// the directory is created.
274    #[serde(default)]
275    pub scripts: Vec<String>,
276    /// Solve the analog network while the firmware runs. The `--analog` flag
277    /// turns it on for one run without editing the file.
278    #[serde(default)]
279    pub analog: bool,
280    /// Simulated Wi-Fi network. A bare string is the esp32sim access-point
281    /// syntax (`ssid=NAME[,psk=PASS]`); a table adds further access points,
282    /// networks a scan should see, and the services the router answers.
283    /// Absent means the radio has no network.
284    #[serde(default)]
285    pub wifi: Option<WifiSpec>,
286    /// A virtual station that joins the guest's own access point (`--wifi-sta`),
287    /// for a firmware in AP mode: `ssid=NAME[,psk=PASS][,mac=..]`. It takes the
288    /// place of `wifi`; a run with both is refused because AP+STA is not
289    /// modelled.
290    #[serde(default)]
291    pub wifi_sta: Option<String>,
292}
293
294/// `[sim] wifi = "..."` or `[sim.wifi]` with fields.
295#[derive(Debug, Clone, Deserialize)]
296#[serde(untagged)]
297pub enum WifiSpec {
298    /// One access point, in esp32sim's syntax.
299    Spec(String),
300    /// The full network.
301    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    /// The network's clock, seconds since 1970, for its SNTP answers.
314    #[serde(default)]
315    pub epoch: Option<u64>,
316    /// Further joinable access points beside the first one.
317    #[serde(default, rename = "ap")]
318    pub extra_aps: Vec<AccessPoint>,
319    /// Networks a scan reports but cannot join (`ssid=NAME[,rssi=-70]`).
320    #[serde(default)]
321    pub nearby: Vec<String>,
322    /// What the router answers. Empty means the defaults (HTTP on 80, a TCP
323    /// echo on 7) unless `services = false`.
324    #[serde(default, rename = "service")]
325    pub services: Vec<ServiceSpec>,
326    /// Turn the default services off, leaving a router that refuses every
327    /// connection. Ignored when `[[sim.wifi.service]]` names its own.
328    #[serde(default = "yes", rename = "services")]
329    pub services_default: bool,
330    /// Resolve every name to the router. Off means only `names` resolve.
331    #[serde(default = "yes")]
332    pub resolve_unknown: bool,
333    /// Names the router resolves, as `name = "10.0.2.3"`.
334    #[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/// One `[[sim.wifi.service]]` entry.
352#[derive(Debug, Clone, Deserialize)]
353pub struct ServiceSpec {
354    pub port: u16,
355    /// A fixed reply for a TCP connection.
356    #[serde(default)]
357    pub reply: Option<String>,
358    /// Send every received byte (TCP) or datagram (with `udp`) back.
359    #[serde(default)]
360    pub echo: bool,
361    /// The service is UDP rather than TCP.
362    #[serde(default)]
363    pub udp: bool,
364    /// The port runs an MQTT broker. `reply`, `echo` and `udp` do not apply.
365    #[serde(default)]
366    pub mqtt: bool,
367    /// The port runs a WebSocket echo server.
368    #[serde(default)]
369    pub websocket: bool,
370    /// Put the service behind TLS 1.3 with the simulated CA.
371    #[serde(default)]
372    pub tls: bool,
373    /// Wait for the guest's first byte before replying. On by default, which is
374    /// what an HTTP client expects; turn it off for a banner.
375    #[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    /// When to sample `expect_state`, as simulated time. Absent means "at any
406    /// point before the test ends".
407    #[serde(default)]
408    pub state_at: Option<String>,
409    /// How long the state must keep matching, starting at `state_at` or at the
410    /// moment it first matched.
411    #[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    /// The board the input belongs to, by `diagram.json` instance id. Required
467    /// when the diagram has more than one development board; a project with
468    /// one board leaves it out.
469    #[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    /// Load a project directory's run configuration.
486    pub fn load_project(dir: &Path) -> Result<Self, String> {
487        Self::load(&dir.join("litz.toml"))
488    }
489}
490
491/// `500ms`, `2s`, `10s`, `1m`, or a bare number of seconds.
492pub 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
515/// `4MB`, `2M`, `4096KB`, or a bare byte count.
516pub 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        // A board-level runtime is the same field the runner already reads, so
579        // it has to spell the new variant too.
580        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}