rigless 0.3.0

Virtual hardware-in-the-loop runtime: run unmodified firmware on an emulated MCU with every peripheral, chip model and unit of virtual time in Rust, and a CPU core of its own that translates the firmware's instructions to host code
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! What a flight controller board senses of the vehicle it flies in and what it drives on it, the
//! same on every such board, so one plant flies any of them.
//!
//! A board's [`Edge`](crate::edge::Edge) takes [`Signals`] as what the world does to its transducers,
//! and hands each chip its share on the chip's own axes. Its outputs are [`Outputs`], each an
//! [`Actuator`], the pulse on a pin and what the pulse commands on a [`Curve`], and a board's output
//! type says which they are through [`Actuate`]. [`SIGNAL_FIELDS`] and [`Outputs::FIELDS`] are how
//! both cross the link. What differs between boards, which chips there are, how each is mounted and
//! what can go wrong with it, stays the board's own.

use crate::chip::nmea::Position;
use crate::edge::{Field, Pulse};
use crate::link::{Wire, WireError};
use crate::time::VirtualNanos;

/// How the thing on an output reads a pulse: the width it takes as no command, and the one it takes as
/// the whole of it. [`Curve::command`] is where between the two a pulse falls.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Curve {
    /// The width that commands nothing. Anything narrower commands the same.
    pub zero: VirtualNanos,
    /// The width that commands everything. Anything wider commands the same.
    pub full: VirtualNanos,
}

/// The whole of a command, in the thousandths [`Curve::command`] answers in.
pub const FULL: u32 = 1000;

impl Curve {
    /// What `pulse` commands on this curve, in thousandths of the whole, held between nothing and all.
    #[must_use]
    pub fn command(self, pulse: Pulse) -> u32 {
        let span = self.full.0.saturating_sub(self.zero.0).max(1);
        let above = pulse.width.0.saturating_sub(self.zero.0).min(span);
        u32::try_from(above * u64::from(FULL) / span).expect("at most the whole")
    }
}

/// One of the board's outputs as it stands: the name the board's description gives it, the pulse on its
/// pin, and what that pulse commands on the speed controllers' curve.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Actuator {
    /// The output, named as the board's description names it.
    pub name: &'static str,
    /// The pulse on the pin, or `None` while the pin is not driven or carries no pulse.
    pub pulse: Option<Pulse>,
    /// The command in thousandths of the whole, for a pulse on the curve.
    pub command: Option<u32>,
}

impl Actuator {
    /// The output `name` carrying `pulse`, read on `curve`.
    #[must_use]
    pub fn on(name: &'static str, pulse: Option<Pulse>, curve: Curve) -> Self {
        Self {
            name,
            pulse,
            command: pulse.map(|pulse| curve.command(pulse)),
        }
    }

    const fn idle(name: &'static str) -> Self {
        Self {
            name,
            pulse: None,
            command: None,
        }
    }
}

/// What a board's outputs are, in the order its description numbers them, for a plant that drives a
/// vehicle off them.
pub trait Actuate {
    /// Every output, first to last.
    fn actuators(&self) -> &[Actuator];
}

/// What the world does to a flight controller's transducers, on the body axes, `x` forward, `y` right and
/// `z` down, in the units the chips take. Where the board is and how it moves are in the world's
/// frame, north, east and down, which is the one the receiver reports in. The default is a world
/// that does nothing at all.
#[derive(
    Debug, Clone, Copy, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize,
)]
pub struct Signals {
    /// The angular rate about each body axis, in thousandths of a degree per second.
    pub angular_rate: [i32; 3],
    /// The specific force along each body axis, in millionths of a gravity.
    pub specific_force: [i32; 3],
    /// The magnetic field along each body axis, in nanotesla.
    pub magnetic_field: [i32; 3],
    /// The static pressure, in pascals.
    pub pressure: u32,
    /// The temperature the board sits at, in hundredths of a degree Celsius.
    pub temperature: i32,
    /// The voltage of the pack the board is powered from, in millivolts.
    pub battery_voltage: u32,
    /// The current the pack is delivering, in milliamps, and negative while it charges.
    pub battery_current: i32,
    /// Where the board is.
    pub position: Position,
    /// How fast the board moves, north, east and down, in millimeters a second.
    pub velocity: [i32; 3],
}

/// The world a vehicle sits in before anything moves it: a gravity's reaction up the body's `z`,
/// which points down, and the field of a mid-latitude northern site, north and down. The air is sea
/// level at twenty degrees. The board is at the geographic center of the contiguous United States,
/// five hundred meters up, on a full four-cell pack.
pub const AT_REST: Signals = Signals {
    angular_rate: [0; 3],
    specific_force: [0, 0, -1_000_000],
    magnetic_field: [22_000, 0, 42_000],
    pressure: 101_325,
    temperature: 2_000,
    battery_voltage: 16_800,
    battery_current: 0,
    position: Position {
        latitude: 398_283_000,
        longitude: -985_795_000,
        altitude: 500_000,
    },
    velocity: [0; 3],
};

crate::wire!(Signals {
    angular_rate,
    specific_force,
    magnetic_field,
    pressure,
    temperature,
    battery_voltage,
    battery_current,
    position,
    velocity
});

/// The signals' fields in the order their bytes cross the link, which a flight board declares as its
/// [`Edge::FIELDS`](crate::edge::Edge::FIELDS).
pub const SIGNAL_FIELDS: &[Field] = &[
    Field::new("angular_rate.x", "mdeg/s", 4, true),
    Field::new("angular_rate.y", "mdeg/s", 4, true),
    Field::new("angular_rate.z", "mdeg/s", 4, true),
    Field::new("specific_force.x", "1e-6 g", 4, true),
    Field::new("specific_force.y", "1e-6 g", 4, true),
    Field::new("specific_force.z", "1e-6 g", 4, true),
    Field::new("magnetic_field.x", "nT", 4, true),
    Field::new("magnetic_field.y", "nT", 4, true),
    Field::new("magnetic_field.z", "nT", 4, true),
    Field::new("pressure", "Pa", 4, false),
    Field::new("temperature", "0.01 degC", 4, true),
    Field::new("battery_voltage", "mV", 4, false),
    Field::new("battery_current", "mA", 4, true),
    Field::new("position.latitude", "1e-7 deg", 4, true),
    Field::new("position.longitude", "1e-7 deg", 4, true),
    Field::new("position.altitude", "mm", 4, true),
    Field::new("velocity.north", "mm/s", 4, true),
    Field::new("velocity.east", "mm/s", 4, true),
    Field::new("velocity.down", "mm/s", 4, true),
];

// ceiling: the most outputs a board here has; upgrade when a board has more, which won't compile.
const MOST_OUTPUTS: usize = 13;
const FIELDS_PER_OUTPUT: usize = 3;
const NAMES: [&str; MOST_OUTPUTS] = [
    "PWM1", "PWM2", "PWM3", "PWM4", "PWM5", "PWM6", "PWM7", "PWM8", "PWM9", "PWM10", "PWM11",
    "PWM12", "PWM13",
];
static OUTPUT_FIELDS: [Field; FIELDS_PER_OUTPUT * MOST_OUTPUTS] = [
    Field::new("PWM1.width", "ns", 8, false),
    Field::new("PWM1.period", "ns", 8, false),
    Field::new("PWM1.command", "1e-3", 4, false),
    Field::new("PWM2.width", "ns", 8, false),
    Field::new("PWM2.period", "ns", 8, false),
    Field::new("PWM2.command", "1e-3", 4, false),
    Field::new("PWM3.width", "ns", 8, false),
    Field::new("PWM3.period", "ns", 8, false),
    Field::new("PWM3.command", "1e-3", 4, false),
    Field::new("PWM4.width", "ns", 8, false),
    Field::new("PWM4.period", "ns", 8, false),
    Field::new("PWM4.command", "1e-3", 4, false),
    Field::new("PWM5.width", "ns", 8, false),
    Field::new("PWM5.period", "ns", 8, false),
    Field::new("PWM5.command", "1e-3", 4, false),
    Field::new("PWM6.width", "ns", 8, false),
    Field::new("PWM6.period", "ns", 8, false),
    Field::new("PWM6.command", "1e-3", 4, false),
    Field::new("PWM7.width", "ns", 8, false),
    Field::new("PWM7.period", "ns", 8, false),
    Field::new("PWM7.command", "1e-3", 4, false),
    Field::new("PWM8.width", "ns", 8, false),
    Field::new("PWM8.period", "ns", 8, false),
    Field::new("PWM8.command", "1e-3", 4, false),
    Field::new("PWM9.width", "ns", 8, false),
    Field::new("PWM9.period", "ns", 8, false),
    Field::new("PWM9.command", "1e-3", 4, false),
    Field::new("PWM10.width", "ns", 8, false),
    Field::new("PWM10.period", "ns", 8, false),
    Field::new("PWM10.command", "1e-3", 4, false),
    Field::new("PWM11.width", "ns", 8, false),
    Field::new("PWM11.period", "ns", 8, false),
    Field::new("PWM11.command", "1e-3", 4, false),
    Field::new("PWM12.width", "ns", 8, false),
    Field::new("PWM12.period", "ns", 8, false),
    Field::new("PWM12.command", "1e-3", 4, false),
    Field::new("PWM13.width", "ns", 8, false),
    Field::new("PWM13.period", "ns", 8, false),
    Field::new("PWM13.command", "1e-3", 4, false),
];

/// What a flight board's firmware drives: its `N` outputs, in the order its description numbers
/// them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Outputs<const N: usize>(pub [Actuator; N]);

impl<const N: usize> Outputs<N> {
    /// Every output with nothing on its pin, which is how the board is built.
    pub const IDLE: Self = {
        let mut actuators = [Actuator::idle(""); N];
        let mut index = 0;
        while index < N {
            actuators[index] = Actuator::idle(NAMES[index]);
            index += 1;
        }
        Self(actuators)
    };

    /// The outputs' fields as a flight board declares them in
    /// [`Edge::OUTPUT_FIELDS`](crate::edge::Edge::OUTPUT_FIELDS): each output's pulse width and
    /// period in nanoseconds, zero while nothing drives it, then its command in thousandths of the
    /// whole, zero with no pulse.
    pub const FIELDS: &'static [Field] = OUTPUT_FIELDS.split_at(FIELDS_PER_OUTPUT * N).0;
}

impl<const N: usize> Actuate for Outputs<N> {
    fn actuators(&self) -> &[Actuator] {
        &self.0
    }
}

impl<const N: usize> Wire for Outputs<N> {
    fn encode(&self, out: &mut Vec<u8>) {
        for actuator in &self.0 {
            let (width, period) = actuator
                .pulse
                .map_or((0, 0), |pulse| (pulse.width.0, pulse.period.0));
            width.encode(out);
            period.encode(out);
            actuator.command.unwrap_or(0).encode(out);
        }
    }

    /// An output with no period carries no pulse and no command.
    fn decode(bytes: &mut &[u8]) -> Result<Self, WireError> {
        let mut outputs = Self::IDLE;
        for actuator in &mut outputs.0 {
            let width: VirtualNanos = Wire::decode(bytes)?;
            let period: VirtualNanos = Wire::decode(bytes)?;
            let command: u32 = Wire::decode(bytes)?;
            actuator.pulse = (period.0 != 0).then_some(Pulse { width, period });
            actuator.command = actuator.pulse.map(|_| command);
        }
        Ok(outputs)
    }
}

/// What every flight board's edge holds to, each called by the board's own test of the same name.
#[cfg(test)]
// Public so a build with no flight board doesn't call it dead.
pub mod conformance {
    use super::{AT_REST, Outputs, Signals};
    use crate::chip::nmea::Position;
    use crate::chip::uart::Peer;
    use crate::edge::{Condition, Coupled, Edge};
    use crate::link::{Wire, values_of};
    use crate::time::VirtualNanos;

    /// A condition on three axes whose biases count down from `bias` and whose noises are its size
    /// in thousands plus the axis.
    pub fn wrong(stuck: bool, bias: i32) -> Condition<3> {
        Condition {
            stuck,
            bias: [bias, bias - 1, bias - 2],
            noise: [1, 2, 3].map(|axis| bias.unsigned_abs() * 1_000 + axis),
        }
    }

    /// That `B`'s fields walk signals whose every signed field is negative and every unsigned one is
    /// past an `i32`.
    pub fn the_declared_fields_walk_the_encoded_signals_one_by_one<B>()
    where
        B: Edge<Signals = Signals>,
    {
        let signals = Signals {
            angular_rate: [-1, -2, -3],
            specific_force: [-4, -5, -6],
            magnetic_field: [-7, -8, -9],
            pressure: 3_000_000_000,
            temperature: -11,
            battery_voltage: 3_000_000_001,
            battery_current: -13,
            position: Position {
                latitude: -14,
                longitude: -15,
                altitude: -16,
            },
            velocity: [-17, -18, -19],
        };
        let mut bytes = Vec::new();
        signals.encode(&mut bytes);
        assert_eq!(
            values_of(B::FIELDS, &bytes).unwrap(),
            [
                -1,
                -2,
                -3,
                -4,
                -5,
                -6,
                -7,
                -8,
                -9,
                3_000_000_000,
                -11,
                3_000_000_001,
                -13,
                -14,
                -15,
                -16,
                -17,
                -18,
                -19
            ],
            "every signed field negative and every unsigned one past an i32, so a wrong sign shows"
        );
    }

    /// That `B`'s conditions cross as zeros as it's built, and `conditions` as `expected`.
    pub fn the_declared_conditions_walk_the_encoded_conditions_one_by_one_and_rest_at_zero<B>(
        conditions: &B::Conditions,
        expected: &[i64],
    ) where
        B: Edge,
        B::Conditions: Wire + Default,
    {
        let mut bytes = Vec::new();
        B::Conditions::default().encode(&mut bytes);
        assert!(
            values_of(B::CONDITIONS, &bytes)
                .unwrap()
                .iter()
                .all(|&value| value == 0),
            "the board as built crosses as zeros"
        );
        let mut bytes = Vec::new();
        conditions.encode(&mut bytes);
        assert_eq!(
            values_of(B::CONDITIONS, &bytes).unwrap(),
            expected,
            "every flag, bias, noise and rate where its field says, each bias negative and one rate \
             past an i32 so a wrong sign shows"
        );
    }

    /// That `board` passes the check a session makes before anything runs.
    pub fn the_edge_passes_the_links_own_check<B: Coupled>(board: &mut B) {
        assert_eq!(board.check(), Ok(()));
    }

    /// That `board` is built sensing the world at rest and driving nothing.
    pub fn the_board_is_built_at_rest<B, const N: usize>(board: &mut B)
    where
        B: Edge<Signals = Signals, Outputs = Outputs<N>>,
    {
        assert_eq!(B::REST, AT_REST);
        assert_eq!(board.drive(), Outputs::IDLE, "nothing drives a pin yet");
    }

    /// That every chip `board` lists has a condition that silences it and a place, and a place past
    /// the list is none.
    pub fn each_chip_listed_has_a_silence_and_a_place<B: Edge>(board: &mut B) {
        for (index, chip) in B::CHIPS.iter().enumerate() {
            let silence = format!("{chip}.silent");
            assert!(
                B::CONDITIONS
                    .iter()
                    .any(|condition| condition.name == silence),
                "{chip}"
            );
            assert!(<B as Edge>::place(board, index).is_some(), "{chip}");
        }
        assert!(<B as Edge>::place(board, B::CHIPS.len()).is_none());
    }

    /// That what `receiver` reaches on `board` reports where the board was told it is.
    pub fn the_receiver_on_the_gps_port_reports_where_the_board_is<B>(
        board: &mut B,
        receiver: impl FnOnce(&mut B) -> &mut dyn Peer,
    ) where
        B: Edge<Signals = Signals>,
    {
        board.sense(&Signals {
            position: Position {
                latitude: 515_074_000,
                longitude: -1_278_000,
                altitude: 11_000,
            },
            velocity: [10_000, 0, 0],
            ..AT_REST
        });
        let receiver = receiver(board);
        let epoch: Vec<u8> = std::iter::from_fn(|| receiver.transmit(VirtualNanos(0)))
            .map(|word| u8::try_from(word).expect("a byte"))
            .collect();
        let epoch = String::from_utf8(epoch).unwrap();
        assert!(
            epoch.starts_with("$GPGGA,000000.00,5130.44400,N,00007.66800,W,1,10,0.90,11.000,M,"),
            "{epoch}"
        );
        assert!(
            epoch.contains("$GPRMC,000000.00,A,5130.44400,N,00007.66800,W,19.43,0.00,"),
            "ten meters a second north is 19.43 knots on course zero: {epoch}"
        );
    }
}