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}
287
288/// `[sim] wifi = "..."` or `[sim.wifi]` with fields.
289#[derive(Debug, Clone, Deserialize)]
290#[serde(untagged)]
291pub enum WifiSpec {
292    /// One access point, in esp32sim's syntax.
293    Spec(String),
294    /// The full network.
295    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    /// The network's clock, seconds since 1970, for its SNTP answers.
308    #[serde(default)]
309    pub epoch: Option<u64>,
310    /// Further joinable access points beside the first one.
311    #[serde(default, rename = "ap")]
312    pub extra_aps: Vec<AccessPoint>,
313    /// Networks a scan reports but cannot join (`ssid=NAME[,rssi=-70]`).
314    #[serde(default)]
315    pub nearby: Vec<String>,
316    /// What the router answers. Empty means the defaults (HTTP on 80, a TCP
317    /// echo on 7) unless `services = false`.
318    #[serde(default, rename = "service")]
319    pub services: Vec<ServiceSpec>,
320    /// Turn the default services off, leaving a router that refuses every
321    /// connection. Ignored when `[[sim.wifi.service]]` names its own.
322    #[serde(default = "yes", rename = "services")]
323    pub services_default: bool,
324    /// Resolve every name to the router. Off means only `names` resolve.
325    #[serde(default = "yes")]
326    pub resolve_unknown: bool,
327    /// Names the router resolves, as `name = "10.0.2.3"`.
328    #[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/// One `[[sim.wifi.service]]` entry.
346#[derive(Debug, Clone, Deserialize)]
347pub struct ServiceSpec {
348    pub port: u16,
349    /// A fixed reply for a TCP connection.
350    #[serde(default)]
351    pub reply: Option<String>,
352    /// Send every received byte (TCP) or datagram (with `udp`) back.
353    #[serde(default)]
354    pub echo: bool,
355    /// The service is UDP rather than TCP.
356    #[serde(default)]
357    pub udp: bool,
358    /// The port runs an MQTT broker. `reply`, `echo` and `udp` do not apply.
359    #[serde(default)]
360    pub mqtt: bool,
361    /// The port runs a WebSocket echo server.
362    #[serde(default)]
363    pub websocket: bool,
364    /// Put the service behind TLS 1.3 with the simulated CA.
365    #[serde(default)]
366    pub tls: bool,
367    /// Wait for the guest's first byte before replying. On by default, which is
368    /// what an HTTP client expects; turn it off for a banner.
369    #[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    /// When to sample `expect_state`, as simulated time. Absent means "at any
400    /// point before the test ends".
401    #[serde(default)]
402    pub state_at: Option<String>,
403    /// How long the state must keep matching, starting at `state_at` or at the
404    /// moment it first matched.
405    #[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    /// The board the input belongs to, by `diagram.json` instance id. Required
461    /// when the diagram has more than one development board; a project with
462    /// one board leaves it out.
463    #[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    /// Load a project directory's run configuration.
480    pub fn load_project(dir: &Path) -> Result<Self, String> {
481        Self::load(&dir.join("litz.toml"))
482    }
483}
484
485/// `500ms`, `2s`, `10s`, `1m`, or a bare number of seconds.
486pub 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
509/// `4MB`, `2M`, `4096KB`, or a bare byte count.
510pub 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        // A board-level runtime is the same field the runner already reads, so
573        // it has to spell the new variant too.
574        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}