Skip to main content

litz_core/
lib.rs

1//! Foundation types shared by every Litz crate.
2//!
3//! Litz is a firmware simulator split along three seams:
4//!
5//! * [`Bus`] — what the CPU sees: an address space, peripherals hang off it.
6//! * [`Mcu`] — a chip: CPU core plus on-chip peripherals, stepped by time.
7//! * [`Part`] — anything on the schematic: LED, button, sensor, display. It only
8//!   ever sees pin levels, never the MCU's internals.
9//!
10//! Keeping those three apart is what lets `litz-esp` and `litz-avr` share the
11//! same parts bin, and what lets the same core compile for a host CLI and for
12//! `wasm32-unknown-unknown`.
13//!
14//! Time is a `u64` count of nanoseconds ([`Tick`]). Every peripheral declares
15//! its own clock period in ticks; a domain whose period does not divide one
16//! nanosecond (a 160 MHz core is 6.25 ns per cycle) carries a fractional
17//! remainder, which is exactly what a hardware clock divider does. No floating
18//! point anywhere in the schedule, so two runs of one firmware produce the
19//! same trace on every host.
20#![no_std]
21#![forbid(unsafe_code)]
22
23extern crate alloc;
24
25/// Nanoseconds since simulation start.
26pub type Tick = u64;
27
28/// Ticks in one second. Time is fixed-point by construction.
29pub const TICKS_PER_SEC: Tick = 1_000_000_000;
30
31/// A digital pin level.
32#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
33pub enum Level {
34    Low,
35    High,
36    /// High-impedance: the pin is not driving, a net must resolve it from
37    /// other drivers or a pull resistor.
38    HighZ,
39}
40
41/// Identifier of a device instance in a [`Board`].
42#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
43pub struct PartId(pub u16);
44
45/// Identifier of one pin of a [`Part`].
46#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
47pub struct PinId(pub u16);
48
49/// The address space a CPU core sees.
50///
51/// Peripherals are not methods on the bus: a bus owns an ordered table of
52/// address ranges and forwards to whichever peripheral claims the range. That
53/// keeps the chip definition declarative and lets a peripheral be moved from
54/// one chip to another without touching the CPU.
55pub trait Bus {
56    fn read8(&mut self, addr: u32) -> u8;
57    fn read16(&mut self, addr: u32) -> u16 {
58        u16::from(self.read8(addr)) | (u16::from(self.read8(addr + 1)) << 8)
59    }
60    fn read32(&mut self, addr: u32) -> u32 {
61        u32::from(self.read16(addr)) | (u32::from(self.read16(addr + 2)) << 16)
62    }
63    fn write8(&mut self, addr: u32, value: u8);
64    fn write16(&mut self, addr: u32, value: u16) {
65        self.write8(addr, value as u8);
66        self.write8(addr + 1, (value >> 8) as u8);
67    }
68    fn write32(&mut self, addr: u32, value: u32) {
69        self.write16(addr, value as u16);
70        self.write16(addr + 2, (value >> 16) as u16);
71    }
72}
73
74/// A microcontroller: a CPU plus the peripherals on its bus.
75///
76/// [`Mcu::step`] advances exactly one instruction (or one hardware event,
77/// whichever comes first in time) and returns the tick at which it next needs
78/// attention. The scheduler runs the MCU whose next tick is smallest.
79pub trait Mcu {
80    fn reset(&mut self, now: Tick);
81
82    /// Execute one step and return the earliest tick at which this MCU must be
83    /// stepped again.
84    fn step(&mut self, now: Tick) -> Tick;
85
86    /// Current level driven by an external pin, if the chip drives it.
87    fn pin_level(&self, pin: u32) -> Level;
88
89    /// A [`Part`] changed the level it drives onto a chip pin.
90    fn set_pin_level(&mut self, pin: u32, level: Level, now: Tick);
91}
92
93/// How hard a node is driven.
94///
95/// Two levels is the whole electrical model. A push-pull chip pin is `Strong`;
96/// a supply rail is `Strong`; a resistor passing a level through is `Weak`.
97/// Resolution is "strong beats weak, two strongs that disagree are a short",
98/// which covers series resistors, pull-ups and buttons without an analog
99/// solver.
100#[derive(Clone, Copy, Debug, PartialEq, Eq)]
101pub enum Strength {
102    Strong,
103    Weak,
104}
105
106/// What a pin is doing to its net right now.
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108pub struct Drive {
109    pub level: Level,
110    pub strength: Strength,
111}
112
113impl Drive {
114    /// Not driving. `strength` is meaningless when floating; `Weak` is used so
115    /// comparisons stay cheap.
116    pub const HIGH_Z: Drive = Drive {
117        level: Level::HighZ,
118        strength: Strength::Weak,
119    };
120
121    pub const fn strong(level: Level) -> Self {
122        Self {
123            level,
124            strength: Strength::Strong,
125        }
126    }
127
128    pub const fn weak(level: Level) -> Self {
129        Self {
130            level,
131            strength: Strength::Weak,
132        }
133    }
134
135    pub fn is_driving(self) -> bool {
136        self.level != Level::HighZ
137    }
138}
139
140/// A schematic component. Parts never read MCU registers; they react to pin
141/// levels and to time, which is the same contract a real part has.
142///
143/// Pin ids are indices into the part's own pin table, assigned once when the
144/// board is flattened, so a driver never has to match strings at run time.
145pub trait Part {
146    /// What this pin drives onto its net. `HIGH_Z` when the part only listens.
147    fn drive(&self, pin: PinId) -> Drive;
148
149    /// Called for every level change on a net this part is attached to.
150    fn set_pin(&mut self, pin: PinId, level: Level, now: Tick);
151
152    /// Earliest tick at which this part wants [`Part::advance`] called.
153    fn next_event(&self) -> Option<Tick> {
154        None
155    }
156
157    fn advance(&mut self, _now: Tick) {}
158
159    /// What a UI or a test can read back without knowing the part's type.
160    fn state(&self) -> PartState {
161        PartState::None
162    }
163
164    /// Host interaction: a person pressed this part. Returns whether the part
165    /// has such an input at all, so a UI can tell a button from an LED.
166    fn press(&mut self, _pressed: bool) -> bool {
167        false
168    }
169
170    /// Host interaction: a person moved a continuous control, in permille
171    /// (0 through 1000). Returns whether the part has such a control.
172    fn set_control(&mut self, _value: u16) -> bool {
173        false
174    }
175
176    /// Host interaction by name, the way a test or a scenario says it: a
177    /// button's `pressed`, a sensor's `temperature`, a joystick's `x`. The
178    /// value stays text because one name can be a percentage, a boolean or a
179    /// physical unit; the part decides how to read it. Returns whether the
180    /// part has that control.
181    fn set_named_control(&mut self, _name: &str, _value: &str) -> bool {
182        false
183    }
184
185    /// The analog voltage in volts this pin holds, for parts that source one
186    /// (a potentiometer wiper, a sensor output). Digital parts return `None`
187    /// on every pin; a net with an analog source is still resolved as a
188    /// digital level for everything else on it.
189    fn analog(&self, _pin: PinId) -> Option<f32> {
190        None
191    }
192
193    /// The output current at which a regulated source stops holding its set
194    /// voltage and delivers this much instead, in amperes. `None` for a part
195    /// that does not limit: a battery, a rail, a plain source.
196    fn current_limit(&self) -> Option<f32> {
197        None
198    }
199}
200
201/// The externally observable state of a part.
202#[derive(Clone, Copy, Debug, PartialEq, Eq)]
203pub enum PartState {
204    Led {
205        lit: bool,
206    },
207    Button {
208        pressed: bool,
209    },
210    /// A two-position switch and which way it is thrown.
211    Switch {
212        on: bool,
213    },
214    /// A seven-segment display: one bit per segment, `a`..`g` then `dp`, least
215    /// significant bit first.
216    Segments {
217        mask: u8,
218    },
219    /// A buzzer or speaker: whether it is being driven, and the rate measured
220    /// from the edges its pins actually saw.
221    Tone {
222        sounding: bool,
223        hz: u32,
224    },
225    /// A servo: the angle the incoming pulse train asks for.
226    Servo {
227        degrees: u16,
228    },
229    /// A continuous control such as a potentiometer, in permille of its travel.
230    Knob {
231        permille: u16,
232    },
233    /// A packet radio: frames it has sent and received, and the first
234    /// [`RADIO_LAST_BYTES`] bytes of the most recent payload (transmitted or
235    /// received). `last_len` says how much of `last_bytes` is meaningful.
236    Radio {
237        tx_count: u32,
238        rx_count: u32,
239        last_bytes: [u8; RADIO_LAST_BYTES],
240        last_len: u8,
241    },
242    None,
243}
244
245/// How much of a radio's last payload [`PartState::Radio`] carries. Longer
246/// frames are truncated in the state only; the part still moves every byte.
247pub const RADIO_LAST_BYTES: usize = 32;