rigless 0.0.5

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; a fork of QEMU is built in and executes the instructions
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The Pixracer: one whole STM32F427, the two crystals on its oscillator pins, and the rail its
//! regulator sees.
//!
//! The board **has** these things — they are its fields, and `pixracer.mcu.rcc` is a field path, not
//! a lookup. The MCU comes complete from [`Stm32f427::new`]; nothing here decides which of its own
//! peripherals exist, because that is the part's business and a board that chose would make every
//! board a different part.
//!
//! **Where an external IC lives, and why.** A board decides which chips exist and what each hangs off;
//! that decision is here, in `Pixracer::fit`, beside the crystals. The chip itself then lives on the
//! interface it is wired to — `mcu.spi[0].attach(..)` — because that is where the wires are and where
//! a transfer has to reach it synchronously, the same shape QEMU gives an `SSIBus`. Holding it in a
//! board field instead would mean the controller could not reach it during a transfer without shared
//! mutability, which buys a prettier field path and costs the thing the field is for.
//!
//! **The world's edge.** The six outputs are the board description's `PWM(1)` to `PWM(6)`, four on the
//! first advanced-control timer and two on the third general-purpose one, each read as the pulse on its
//! pin and what that pulse commands on the speed controllers' curve. The body axes are the firmware's,
//! `x` forward, `y` right, `z` down. The two inertial units read those axes as their own: the firmware's
//! Invensense driver swaps `x` with `y` and reverses `z` on every sample before it applies the
//! description's `ROTATION_ROLL_180_YAW_90`, and the two turns cancel. The compass die inside the first
//! unit is turned against the package, which the package's own model does. What the board senses is its
//! own [`Signals`]: the quantities its transducers measure, on the body axes and in the chips' units.
//! The board senses the world at rest when it is built, so a firmware boots on a level vehicle rather
//! than on chips lying flat.

use std::num::{NonZeroU32, NonZeroU64};

use crate::chip::fram::Fm25v02;
use crate::chip::icm20608::Icm20608;
use crate::chip::lis3mdl::Lis3mdl;
use crate::chip::mpu9250::Mpu9250;
use crate::chip::ms5611::Ms5611;
use crate::chip::nmea::{self, Position};
use crate::chip::sd::MemoryCard;
use crate::chip::uart;
use crate::device::Level;
use crate::edge::{Actuator, Curve, Edge};
use crate::emulator::InterruptLine;
use crate::machine::armv7m;
use crate::machine::{Board, Crystal, HostWire, Supply, Target};
use crate::soc::Error;
use crate::soc::stm32f427::Stm32f427;
use crate::soc::stm32f427::peripherals::adc::Channel as AnalogChannel;
use crate::soc::stm32f427::peripherals::gpio::Pin;
use crate::soc::stm32f427::peripherals::spi::Select;
use crate::soc::stm32f427::peripherals::tim::Channel;
use crate::time::VirtualNanos;

/// The name `rigless run --machine` matches.
pub const NAME: &str = "pixracer";

/// The one MCU on the board.
pub const MCU: &str = "stm32f427";

/// The core clock the board's crystal and PLL give the MCU, RM0090 rev 22 section 6.2.
const CLOCK_HZ: NonZeroU64 = NonZeroU64::new(168_000_000).expect("a running clock");
/// The reference clock of the core's timer is the core clock over eight, PM0214 rev 10 section 4.5.
const REFCLK_DIVIDER: NonZeroU32 = NonZeroU32::new(8).expect("a divider divides");
/// The MCU implements four priority bits, PM0214 rev 10 section 4.3.
const PRIORITY_BITS: u8 = 4;
/// BOOT0 is tied low on the board, so the main flash answers at the reset vector, RM0090 rev 22 section 2.4.
const BOOT: &str = "flash";
/// Every instruction takes four nanoseconds, the rate the runtime fixes for every target.
const ICOUNT_SHIFT: u32 = 2;
/// The parameter memory hangs on the second serial interface, ArduPilot's `SPIDEV ramtron SPI2`.
const FRAM_ON: usize = 1;
/// Its chip select, `PD10 FRAM_CS` in the same board description, selected low.
const FRAM_CS: Pin = Pin::new(10).expect("a port has sixteen pins");
/// The barometer shares that interface, `SPIDEV ms5611_int SPI2`, behind `PD7 BARO_CS`, selected low.
const BARO_CS: Pin = Pin::new(7).expect("a port has sixteen pins");
/// The two inertial units hang on the first serial interface, `SPIDEV mpu9250 SPI1` and
/// `SPIDEV icm20608 SPI1`.
const IMU_ON: usize = 0;
/// Their chip selects, `PC2 MPU9250_CS` and `PC15 20608_CS`, each selected low.
const IMU_CS: Pin = Pin::new(2).expect("a port has sixteen pins");
const SECOND_IMU_CS: Pin = Pin::new(15).expect("a port has sixteen pins");
/// The magnetometer shares that interface, `SPIDEV lis3mdl SPI1`, behind `PE15 MAG_CS`, selected low.
const MAG_CS: Pin = Pin::new(15).expect("a port has sixteen pins");
/// The card in the slot: eight gibibytes, formatted, the card the board ships with a firmware expecting.
const CARD_BLOCKS: usize = 8 * 1024 * 1024 * 1024 / crate::chip::sd::BLOCK;
/// `serial1` of the board description's `SERIAL_ORDER` is `USART2`, the telemetry port, which is where a
/// ground station talks to the firmware; `rigless run` listens for one on the port that serial has by
/// convention.
const TELEMETRY: usize = 1;
/// `serial3` is `UART4`, "UART4 is GPS" in the description: the receiver hangs there.
const GPS: usize = 6;
const TELEMETRY_WIRE: HostWire = HostWire {
    name: "serial1",
    port: 5760,
};
/// Where each chip stands among its interface's peers, in the order `fit` hangs them.
const MPU9250_PEER: usize = 0;
const ICM20608_PEER: usize = 1;
const LIS3MDL_PEER: usize = 2;
const MS5611_PEER: usize = 1;
/// `PWM(1)` to `PWM(4)`: `PE14 TIM1_CH4`, `PE13 TIM1_CH3`, `PE11 TIM1_CH2` and `PE9 TIM1_CH1` in the board
/// description, on the first advanced-control timer of the part.
const MAIN_TIMER: usize = 0;
const MAIN_OUTPUTS: [(&str, Channel); 4] = [
    ("PWM1", channel(4)),
    ("PWM2", channel(3)),
    ("PWM3", channel(2)),
    ("PWM4", channel(1)),
];
/// `PWM(5)` and `PWM(6)`: `PD13 TIM4_CH2` and `PD14 TIM4_CH3`, on the third general-purpose timer.
const AUXILIARY_TIMER: usize = 2;
const AUXILIARY_OUTPUTS: [(&str, Channel); 2] = [("PWM5", channel(2)), ("PWM6", channel(3))];
/// The pulse the speed controllers on the outputs read as nothing and as everything: the firmware's
/// `MOT_PWM_MIN` and `MOT_PWM_MAX` defaults of 1000 and 2000 microseconds.
const SPEED_CONTROLLER: Curve = Curve {
    zero: VirtualNanos(1_000_000),
    full: VirtualNanos(2_000_000),
};

/// `PA2 BATT_VOLTAGE_SENS ADC1` and `PA3 BATT_CURRENT_SENS ADC1` in the board description, channels 2 and
/// 3 of the first converter, behind the dividers the firmware's `BATT_VOLT_MULT` and `BATT_AMP_PERVLT`
/// defaults undo: 10.1 volts a volt and 17 amperes a volt.
const BATTERY_CONVERTER: usize = 0;
const BATTERY_VOLTAGE: AnalogChannel = analog(2);
const BATTERY_CURRENT: AnalogChannel = analog(3);
const PACK_PER_SENSED: u32 = 101;
const SENSED_PER_PACK: u32 = 10;
const MILLIAMPS_PER_MILLIVOLT: u32 = 17;
/// `PA4 VDD_5V_SENS ADC1 SCALE(2)`: the board's own 5 V rail, halved onto channel 4.
const FIVE_VOLT_SENSE: AnalogChannel = analog(4);
const FIVE_VOLT_RAIL: Supply = Supply(5000);

const fn channel(number: u8) -> Channel {
    match Channel::new(number) {
        Some(channel) => channel,
        None => panic!("a timer has four channels"),
    }
}

/// What the world does to this board'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)]
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; 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 millimetres 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; the field of a mid-latitude northern site, north and down; sea level at twenty degrees;
/// the geographic centre of the contiguous United States, five hundred metres 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],
};

const fn analog(number: u8) -> AnalogChannel {
    match AnalogChannel::new(number) {
        Some(channel) => channel,
        None => panic!("a converter has sixteen pin channels"),
    }
}

/// The Pixracer.
#[derive(Debug)]
pub struct Pixracer {
    /// The microcontroller, whole.
    pub mcu: Stm32f427,
    /// The high-speed crystal the board fits, which is what the PLL multiplies up to the core clock.
    pub hse: Crystal,
    /// The low-speed crystal the board fits for the real-time clock.
    pub lse: Crystal,
    /// The rail the board regulates to, above every detector threshold of DS9405 rev 13 table 22.
    pub rail: Supply,
}

impl Pixracer {
    /// The board as it is built: the MCU out of reset, then what this board fits attached to it.
    pub fn new() -> Result<Self, Error> {
        let mut board = Self {
            mcu: Stm32f427::new()?,
            hse: Crystal(24_000_000),
            lse: Crystal(32_768),
            rail: Supply(3300),
        };
        board.fit();
        board.sense(&AT_REST);
        Ok(board)
    }

    /// What the board puts on the part's pins. Every line here is a wire on the schematic.
    fn fit(&mut self) {
        self.mcu.rcc.attach_crystals(self.hse.0, self.lse.0);
        let rail = self.rail.0;
        let (power, registers) = self.mcu.power();
        power.set_supply(rail, registers);
        // `VREF+` is the rail, table 65: the board brings the pin out to nothing else.
        for converter in &mut self.mcu.adc {
            converter.set_reference(rail);
        }
        self.mcu.adc[BATTERY_CONVERTER].set_input(FIVE_VOLT_SENSE, FIVE_VOLT_RAIL.0 / 2);
        self.mcu.usart[GPS].attach(nmea::Receiver::new());
        self.mcu.spi[FRAM_ON].attach_selected(
            Fm25v02::new(),
            Select {
                port: "GPIOD",
                pin: FRAM_CS,
                active: Level::Low,
            },
        );
        self.mcu.spi[FRAM_ON].attach_selected(
            Ms5611::new(),
            Select {
                port: "GPIOD",
                pin: BARO_CS,
                active: Level::Low,
            },
        );
        self.mcu.spi[IMU_ON].attach_selected(
            Mpu9250::new(),
            Select {
                port: "GPIOC",
                pin: IMU_CS,
                active: Level::Low,
            },
        );
        self.mcu.spi[IMU_ON].attach_selected(
            Icm20608::new(),
            Select {
                port: "GPIOC",
                pin: SECOND_IMU_CS,
                active: Level::Low,
            },
        );
        self.mcu.spi[IMU_ON].attach_selected(
            Lis3mdl::new(),
            Select {
                port: "GPIOE",
                pin: MAG_CS,
                active: Level::Low,
            },
        );
        self.mcu.sdio.attach(MemoryCard::formatted(CARD_BLOCKS));
    }
}

impl Board for Pixracer {
    fn name(&self) -> &'static str {
        NAME
    }

    fn target_names(&self) -> Vec<&'static str> {
        vec![MCU]
    }

    fn mcu(&mut self, target: usize) -> Option<&mut dyn crate::mcu::Mcu> {
        (target == 0).then_some(&mut self.mcu)
    }

    fn targets(&mut self) -> Vec<Target<'_>> {
        let emulator = armv7m::Core {
            model: armv7m::Model::M4,
            clock_hz: CLOCK_HZ,
            interrupt_lines: NonZeroU32::new(u32::from(
                crate::mcu::Mcu::cpu(&self.mcu).interrupt_lines,
            ))
            .expect("an MCU with interrupts"),
            priority_bits: PRIORITY_BITS,
            refclk_divider: REFCLK_DIVIDER,
            icount_shift: ICOUNT_SHIFT,
            boot: BOOT,
        }
        .command(&crate::cpu::armv7m::windows(crate::mcu::Mcu::bus(
            &self.mcu,
        )));
        vec![Target {
            name: MCU,
            mcu: &mut self.mcu,
            emulator,
            interrupt_line: InterruptLine::new,
        }]
    }

    fn actuators(&mut self) -> Vec<Actuator> {
        let (main, registers) = self.mcu.advanced_timer(MAIN_TIMER);
        let mut outputs: Vec<Actuator> = MAIN_OUTPUTS
            .iter()
            .map(|&(name, channel)| {
                Actuator::on(name, main.pulse(channel, registers), SPEED_CONTROLLER)
            })
            .collect();
        let (auxiliary, registers) = self.mcu.timer(AUXILIARY_TIMER);
        outputs.extend(AUXILIARY_OUTPUTS.iter().map(|&(name, channel)| {
            Actuator::on(name, auxiliary.pulse(channel, registers), SPEED_CONTROLLER)
        }));
        outputs
    }

    fn hosts(&self) -> Vec<HostWire> {
        vec![TELEMETRY_WIRE]
    }

    fn attach_host(&mut self, name: &str, peer: Box<dyn uart::Peer>) -> bool {
        if name != TELEMETRY_WIRE.name {
            return false;
        }
        self.mcu.usart[TELEMETRY].attach_boxed(peer);
        true
    }
}

impl Edge for Pixracer {
    type Signals = Signals;

    const OUTPUTS: &'static [&'static str] = &["PWM1", "PWM2", "PWM3", "PWM4", "PWM5", "PWM6"];

    /// Every chip takes the body's axes as its own: the inertial units because the firmware's driver
    /// undoes the description's rotation on the way in, `AP_InertialSensor_Invensense.cpp` lines 613
    /// to 615 against `hwdef.dat`, the magnetometer because the description mounts it `ROTATION_NONE`,
    /// and the barometer because a pressure has none.
    fn sense(&mut self, signals: &Signals) {
        let [rate_x, rate_y, rate_z] = signals.angular_rate;
        let [force_x, force_y, force_z] = signals.specific_force;
        let [field_x, field_y, field_z] = signals.magnetic_field;
        let imus = &mut self.mcu.spi[IMU_ON];
        let unit: &mut Mpu9250 = imus.chip_mut(MPU9250_PEER).expect("fit hangs it");
        unit.set_rate(rate_x, rate_y, rate_z);
        unit.set_acceleration(force_x, force_y, force_z);
        unit.set_temperature(signals.temperature);
        unit.set_field(field_x, field_y, field_z);
        let unit: &mut Icm20608 = imus.chip_mut(ICM20608_PEER).expect("fit hangs it");
        unit.set_rate(rate_x, rate_y, rate_z);
        unit.set_acceleration(force_x, force_y, force_z);
        unit.set_temperature(signals.temperature);
        let compass: &mut Lis3mdl = imus.chip_mut(LIS3MDL_PEER).expect("fit hangs it");
        compass.set_field(field_x, field_y, field_z);
        compass.set_temperature(signals.temperature);
        let barometer: &mut Ms5611 = self.mcu.spi[FRAM_ON]
            .chip_mut(MS5611_PEER)
            .expect("fit hangs it");
        barometer.set_pressure(signals.pressure);
        barometer.set_temperature(signals.temperature);
        let receiver: &mut nmea::Receiver = self.mcu.usart[GPS].chip_mut().expect("fit hangs it");
        receiver.set_position(signals.position);
        receiver.set_velocity(signals.velocity);
        let converter = &mut self.mcu.adc[BATTERY_CONVERTER];
        converter.set_input(
            BATTERY_VOLTAGE,
            signals.battery_voltage * SENSED_PER_PACK / PACK_PER_SENSED,
        );
        converter.set_input(
            BATTERY_CURRENT,
            u32::try_from(signals.battery_current).unwrap_or(0) / MILLIAMPS_PER_MILLIVOLT,
        );
    }
}

/// The board behind the constructor table of [`crate::machine::all`].
pub fn boxed() -> Result<Box<dyn Board>, Error> {
    Ok(Box::new(Pixracer::new()?))
}

/// The board as what a link couples to a plant, for [`crate::machine::coupled`].
pub fn coupled() -> Result<Box<dyn crate::edge::Coupled>, Error> {
    Ok(Box::new(Pixracer::new()?))
}

impl crate::link::Wire for Signals {
    fn encode(&self, out: &mut Vec<u8>) {
        self.angular_rate.encode(out);
        self.specific_force.encode(out);
        self.magnetic_field.encode(out);
        self.pressure.encode(out);
        self.temperature.encode(out);
        self.battery_voltage.encode(out);
        self.battery_current.encode(out);
        self.position.encode(out);
        self.velocity.encode(out);
    }

    fn decode(bytes: &mut &[u8]) -> Result<Self, crate::link::WireError> {
        Ok(Self {
            angular_rate: crate::link::Wire::decode(bytes)?,
            specific_force: crate::link::Wire::decode(bytes)?,
            magnetic_field: crate::link::Wire::decode(bytes)?,
            pressure: crate::link::Wire::decode(bytes)?,
            temperature: crate::link::Wire::decode(bytes)?,
            battery_voltage: crate::link::Wire::decode(bytes)?,
            battery_current: crate::link::Wire::decode(bytes)?,
            position: crate::link::Wire::decode(bytes)?,
            velocity: crate::link::Wire::decode(bytes)?,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::chip::ak8963::{ADDRESS, Ak8963};
    use crate::chip::i2c;
    use crate::chip::spi::Peer;
    use crate::device::DeviceContext;
    use crate::edge::Pulse;
    use crate::mcu::Mcu;
    use crate::soc::stm32f427::generated::rcc::{Register as RccRegister, apb2enr};
    use crate::soc::stm32f427::generated::tim1::{Register as Tim1Register, cr1, egr};
    use crate::soc::stm32f427::generated::{RCC, TIM1};
    use crate::soc::stm32f427::peripherals::rcc::Apb;
    use crate::soc::{Layout, Width};

    const MICROSECOND: u64 = 1_000;
    const MILLISECOND: u64 = 1_000_000;
    /// The invensense read flag, the wake into a running clock, the accelerometer words, and the counts
    /// a gravity gives at the narrowest range.
    const READ: u8 = 0x80;
    const PWR_MGMT_1: u8 = 0x6B;
    const CLOCK_ON: u8 = 0x01;
    const ACCEL_XOUT_H: u8 = 0x3B;
    const COUNTS_PER_GRAVITY: i16 = 16_384;
    /// The magnetometer's burst read, its control registers, continuous conversion, the field words, and
    /// the counts a gauss gives at the narrowest range.
    const BURST: u8 = 0xC0;
    const CTRL_REG1: u8 = 0x20;
    const CTRL_REG3: u8 = 0x22;
    const CONTINUOUS: u8 = 0x00;
    const ODR_80_ULTRAHIGH: u8 = 0x7C;
    const OUT_X_L: u8 = 0x28;
    const COUNTS_PER_GAUSS: i16 = 6842;
    const TEMP_EN: u8 = 0x80;
    const GAUSS_NANOTESLA: i32 = 100_000;
    const ONE_GRAVITY: i32 = 1_000_000;
    /// The compass die's control register, continuous mode 2 at sixteen bits, and its field words.
    const CNTL1: u8 = 0x0A;
    const CONTINUOUS_2_SIXTEEN_BITS: u8 = 0x16;
    const HXL: u8 = 0x03;
    /// The barometer's reset, its two conversions at the widest oversampling, and the read of the result.
    const RESET: u8 = 0x1E;
    const CONVERT_D1: u8 = 0x48;
    const CONVERT_D2: u8 = 0x58;
    const ADC_READ: u8 = 0x00;

    fn read(board: &mut Pixracer, at: u64, base: u64, offset: u32) -> u64 {
        board
            .mcu
            .read(VirtualNanos(at), base + u64::from(offset), Width::W32)
            .unwrap()
    }

    fn write(board: &mut Pixracer, at: u64, base: u64, offset: u32, value: u64) {
        board
            .mcu
            .write(
                VirtualNanos(at),
                base + u64::from(offset),
                Width::W32,
                value,
            )
            .unwrap();
    }

    /// One select cycle with the nth chip of an interface, the answer to each byte in order.
    fn cycle(board: &mut Pixracer, at: u64, interface: usize, nth: usize, bytes: &[u8]) -> Vec<u8> {
        board
            .mcu
            .drive_serial(VirtualNanos(at), interface, |spi, _, context| {
                let peer = spi.peer_mut(nth).expect("fitted");
                peer.select(context);
                let answers = bytes
                    .iter()
                    .map(|&byte| u8::try_from(peer.transfer(u16::from(byte), context)).unwrap())
                    .collect();
                peer.deselect(context);
                answers
            })
    }

    /// One select cycle with the nth chip of an interface, and the same cycle on `reference`, a chip of
    /// the same kind driven by hand at the same instant: what the board's chip answered, and what the
    /// reference did.
    fn alike(
        board: &mut Pixracer,
        at: u64,
        (interface, nth): (usize, usize),
        reference: &mut dyn Peer,
        bytes: &[u8],
    ) -> (Vec<u8>, Vec<u8>) {
        board
            .mcu
            .drive_serial(VirtualNanos(at), interface, |spi, _, context| {
                let answers = |peer: &mut dyn Peer| -> Vec<u8> {
                    peer.select(context);
                    let answers = bytes
                        .iter()
                        .map(|&byte| u8::try_from(peer.transfer(u16::from(byte), context)).unwrap())
                        .collect();
                    peer.deselect(context);
                    answers
                };
                (
                    answers(spi.peer_mut(nth).expect("fitted")),
                    answers(reference),
                )
            })
    }

    /// A register write to a die on a package's own bus, as the package's master frames it.
    fn die_write(die: &mut dyn i2c::Peer, register: u8, byte: u8, context: &DeviceContext<'_>) {
        die.start(ADDRESS, false, context);
        die.write(register, context);
        die.write(byte, context);
        die.stop(context);
    }

    /// A burst read from a die on a package's own bus, as the package's master frames it.
    fn die_read(
        die: &mut dyn i2c::Peer,
        register: u8,
        count: usize,
        context: &DeviceContext<'_>,
    ) -> Vec<u8> {
        die.start(ADDRESS, false, context);
        die.write(register, context);
        die.start(ADDRESS, true, context);
        let bytes = (0..count)
            .map(|index| die.read(index + 1 == count, context))
            .collect();
        die.stop(context);
        bytes
    }

    /// The field words of the compass die inside the board's first inertial unit and of the die inside
    /// `reference`, each put into continuous measurement and read through its package's own bus.
    fn compass_die_fields(board: &mut Pixracer, reference: &mut Mpu9250) -> (Vec<u8>, Vec<u8>) {
        board
            .mcu
            .drive_serial(VirtualNanos(10 * MILLISECOND), IMU_ON, |spi, _, context| {
                for die in [
                    spi.chip_mut::<Mpu9250>(MPU9250_PEER)
                        .expect("fit hangs it")
                        .magnetometer(),
                    reference.magnetometer(),
                ] {
                    die_write(die, CNTL1, CONTINUOUS_2_SIXTEEN_BITS, context);
                }
            });
        board
            .mcu
            .drive_serial(VirtualNanos(30 * MILLISECOND), IMU_ON, |spi, _, context| {
                let on_board: &mut Ak8963 = spi
                    .chip_mut::<Mpu9250>(MPU9250_PEER)
                    .expect("fit hangs it")
                    .magnetometer();
                (
                    die_read(on_board, HXL, 6, context),
                    die_read(reference.magnetometer(), HXL, 6, context),
                )
            })
    }

    fn words(bytes: &[u8], big_endian: bool) -> [i16; 3] {
        let word = |pair: &[u8]| {
            if big_endian {
                i16::from_be_bytes([pair[0], pair[1]])
            } else {
                i16::from_le_bytes([pair[0], pair[1]])
            }
        };
        [word(&bytes[0..2]), word(&bytes[2..4]), word(&bytes[4..6])]
    }

    /// The description's `PWM(1)` is `TIM1_CH4`; a pulse the firmware programs there reads back as that
    /// output with what it commands on the speed controllers' curve, and the outputs nothing drives read
    /// as none.
    #[test]
    fn the_outputs_are_the_description_s_six_pwm_pins_read_off_their_timers() {
        let mut board = Pixracer::new().unwrap();
        let idle: Vec<&str> = board
            .actuators()
            .iter()
            .filter(|actuator| actuator.pulse.is_none())
            .map(|actuator| actuator.name)
            .collect();
        assert_eq!(idle, ["PWM1", "PWM2", "PWM3", "PWM4", "PWM5", "PWM6"]);
        assert_eq!(
            idle,
            <Pixracer as Edge>::OUTPUTS,
            "an output crosses the link as its index in this list, so the two orders are one"
        );
        let timer_hz = {
            let (clocks, registers) = board.mcu.clocks();
            clocks.timer_clock(registers, Apb::Two)
        };
        let tim1 = |register: Tim1Register| register.spec().offset;
        write(
            &mut board,
            0,
            RCC.base,
            RccRegister::Apb2enr.spec().offset,
            apb2enr::TIM1EN.mask(),
        );
        write(
            &mut board,
            0,
            TIM1.base,
            tim1(Tim1Register::Psc),
            timer_hz / 1_000_000 - 1,
        );
        write(&mut board, 0, TIM1.base, tim1(Tim1Register::Arr), 19_999);
        write(&mut board, 0, TIM1.base, tim1(Tim1Register::Ccr4), 1_500);
        write(
            &mut board,
            0,
            TIM1.base,
            tim1(Tim1Register::Ccmr2Output),
            0x6800,
        );
        write(&mut board, 0, TIM1.base, tim1(Tim1Register::Ccer), 0x1000);
        write(&mut board, 0, TIM1.base, tim1(Tim1Register::Bdtr), 0x8000);
        write(
            &mut board,
            0,
            TIM1.base,
            tim1(Tim1Register::Egr),
            egr::UG.mask(),
        );
        write(
            &mut board,
            0,
            TIM1.base,
            tim1(Tim1Register::Cr1),
            cr1::CEN.mask(),
        );
        let actuators = board.actuators();
        assert_eq!(
            actuators[0],
            Actuator {
                name: "PWM1",
                pulse: Some(Pulse {
                    width: VirtualNanos(1_500 * MICROSECOND),
                    period: VirtualNanos(20 * MILLISECOND),
                }),
                command: Some(500),
            }
        );
        assert!(
            actuators[1..]
                .iter()
                .all(|actuator| actuator.pulse.is_none())
        );
    }

    /// The description's `serial1` is the second serial port, and a host hung there is what that port
    /// talks to; a wire the board has not is refused.
    #[test]
    fn the_telemetry_wire_is_the_second_serial_port() {
        let mut board = Pixracer::new().unwrap();
        assert_eq!(board.hosts(), [TELEMETRY_WIRE]);
        assert!(!board.attach_host(
            "serial9",
            Box::new(crate::soc::stm32f427::peripherals::usart::Pattern::default())
        ));
        assert!(!board.mcu.usart[TELEMETRY].attached());
        assert!(board.attach_host(
            "serial1",
            Box::new(crate::soc::stm32f427::peripherals::usart::Pattern::default())
        ));
        assert!(board.mcu.usart[TELEMETRY].attached());
        assert_eq!(
            crate::soc::stm32f427::peripherals::SERIAL_PORTS[TELEMETRY].instance,
            "USART2"
        );
    }

    /// The receiver hangs on the description's GPS port, and the first epoch it writes after the board is
    /// handed a position carries that position.
    #[test]
    fn the_receiver_on_the_gps_port_reports_where_the_board_is() {
        let mut board = Pixracer::new().unwrap();
        assert_eq!(
            crate::soc::stm32f427::peripherals::SERIAL_PORTS[GPS].instance,
            "UART4"
        );
        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 = board.mcu.usart[GPS].peer_mut().expect("fit hangs it");
        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 metres a second north is 19.43 knots on course zero: {epoch}"
        );
    }

    /// 16.8 V over the description's 10.1 is 1663 mV on channel 2, 17 A at 17 A/V is 1000 mV on channel
    /// 3, and the board's own 5 V is 2500 mV on channel 4, each converted against the 3.3 V rail; the
    /// scan reads them in the description's order.
    #[test]
    fn the_battery_reaches_the_first_converter_through_the_descriptions_dividers() {
        use crate::soc::stm32f427::generated::ADC1;
        use crate::soc::stm32f427::generated::adc1::{
            Register as AdcRegister, cr1 as adc_cr1, cr2, sqr1, sqr3, sr,
        };

        let mut board = Pixracer::new().unwrap();
        board.sense(&Signals {
            battery_voltage: 16_800,
            battery_current: 17_000,
            ..AT_REST
        });
        let adc = |register: AdcRegister| register.spec().offset;
        write(
            &mut board,
            0,
            RCC.base,
            RccRegister::Apb2enr.spec().offset,
            apb2enr::ADC1EN.mask(),
        );
        write(
            &mut board,
            0,
            ADC1.base,
            adc(AdcRegister::Sqr3),
            sqr3::SQ3.set(sqr3::SQ2.set(sqr3::SQ1.set(0, 2), 3), 4),
        );
        write(
            &mut board,
            0,
            ADC1.base,
            adc(AdcRegister::Sqr1),
            sqr1::L.set(0, 2),
        );
        write(
            &mut board,
            0,
            ADC1.base,
            adc(AdcRegister::Cr1),
            adc_cr1::SCAN.mask(),
        );
        let running = cr2::ADON.mask() | cr2::EOCS.mask();
        write(&mut board, 0, ADC1.base, adc(AdcRegister::Cr2), running);
        write(
            &mut board,
            0,
            ADC1.base,
            adc(AdcRegister::Cr2),
            running | cr2::SWSTART.mask(),
        );
        // Fifteen cycles a conversion at the reset 8 MHz, 13.5 and 13.13.16.
        let words: Vec<u64> = (1..=3)
            .map(|nth| {
                let now = nth * 1_875;
                board.mcu.advance_to(VirtualNanos(now));
                assert!(sr::EOC.is_set(read(&mut board, now, ADC1.base, adc(AdcRegister::Sr))));
                read(&mut board, now, ADC1.base, adc(AdcRegister::Dr))
            })
            .collect();
        assert_eq!(words, [2063, 1240, 3102]);
    }

    /// A board just built is a level vehicle at rest: each inertial unit reads a gravity's reaction against
    /// its `z`, which the firmware's driver and rotation make a level attitude, and not the datasheet's
    /// chip lying flat.
    #[test]
    fn the_board_is_built_at_rest() {
        let mut board = Pixracer::new().unwrap();
        for unit in [MPU9250_PEER, ICM20608_PEER] {
            cycle(
                &mut board,
                MILLISECOND,
                IMU_ON,
                unit,
                &[PWR_MGMT_1, CLOCK_ON],
            );
            let mut frame = vec![ACCEL_XOUT_H | READ];
            frame.extend([0; 6]);
            let bytes = cycle(&mut board, 5 * MILLISECOND, IMU_ON, unit, &frame);
            assert_eq!(
                words(&bytes[1..], true),
                [0, 0, -COUNTS_PER_GRAVITY],
                "unit {unit}"
            );
        }
        cycle(
            &mut board,
            MILLISECOND,
            IMU_ON,
            LIS3MDL_PEER,
            &[CTRL_REG1, ODR_80_ULTRAHIGH],
        );
        cycle(
            &mut board,
            MILLISECOND,
            IMU_ON,
            LIS3MDL_PEER,
            &[CTRL_REG3, CONTINUOUS],
        );
        let mut frame = vec![OUT_X_L | BURST];
        frame.extend([0; 6]);
        let bytes = cycle(&mut board, 30 * MILLISECOND, IMU_ON, LIS3MDL_PEER, &frame);
        let [north, east, down] = words(&bytes[1..], false);
        assert!(
            north > 0 && east == 0 && down > 0,
            "north and down: {north} {east} {down}"
        );
    }

    /// Every quantity lands on the chip it is wired to, on the body's own axes: each chip on the board
    /// answers the driver's reads byte for byte as a chip of its kind given those quantities by hand
    /// does, the rate, the force and the temperature on both inertial units, the field on the compass
    /// die inside the first and on the magnetometer with its temperature, and the pressure and the
    /// temperature on the barometer.
    #[test]
    fn sensing_hands_each_chip_the_body_s_axes() {
        const RATE: i32 = 100_000;
        let mut board = Pixracer::new().unwrap();
        board.sense(&Signals {
            angular_rate: [RATE, 0, -RATE],
            specific_force: [ONE_GRAVITY, 0, -ONE_GRAVITY],
            magnetic_field: [GAUSS_NANOTESLA, 0, GAUSS_NANOTESLA],
            pressure: 95_000,
            temperature: 3_000,
            ..AT_REST
        });
        let mut mpu9250 = Mpu9250::new();
        mpu9250.set_rate(RATE, 0, -RATE);
        mpu9250.set_acceleration(ONE_GRAVITY, 0, -ONE_GRAVITY);
        mpu9250.set_temperature(3_000);
        mpu9250.set_field(GAUSS_NANOTESLA, 0, GAUSS_NANOTESLA);
        let mut icm20608 = Icm20608::new();
        icm20608.set_rate(RATE, 0, -RATE);
        icm20608.set_acceleration(ONE_GRAVITY, 0, -ONE_GRAVITY);
        icm20608.set_temperature(3_000);
        let mut lis3mdl = Lis3mdl::new();
        lis3mdl.set_field(GAUSS_NANOTESLA, 0, GAUSS_NANOTESLA);
        lis3mdl.set_temperature(3_000);
        let mut ms5611 = Ms5611::new();
        ms5611.set_pressure(95_000);
        ms5611.set_temperature(3_000);

        let mut sample = vec![ACCEL_XOUT_H | READ];
        sample.extend([0; 14]);
        let units: [(usize, &mut dyn Peer); 2] =
            [(MPU9250_PEER, &mut mpu9250), (ICM20608_PEER, &mut icm20608)];
        for (nth, unit) in units {
            alike(
                &mut board,
                MILLISECOND,
                (IMU_ON, nth),
                unit,
                &[PWR_MGMT_1, CLOCK_ON],
            );
            let (on_board, expected) =
                alike(&mut board, 5 * MILLISECOND, (IMU_ON, nth), unit, &sample);
            assert_eq!(on_board, expected, "unit {nth}");
            assert_eq!(
                words(&expected[1..7], true),
                [COUNTS_PER_GRAVITY, 0, -COUNTS_PER_GRAVITY]
            );
            assert_ne!(&expected[7..9], [0, 0], "a temperature");
            assert_ne!(words(&expected[9..15], true), [0; 3], "a rate");
        }

        let (on_board, expected) = compass_die_fields(&mut board, &mut mpu9250);
        assert_eq!(on_board, expected, "the compass die inside the first unit");
        assert_ne!(expected, [0; 6]);

        alike(
            &mut board,
            MILLISECOND,
            (IMU_ON, LIS3MDL_PEER),
            &mut lis3mdl,
            &[CTRL_REG1, TEMP_EN | ODR_80_ULTRAHIGH],
        );
        alike(
            &mut board,
            MILLISECOND,
            (IMU_ON, LIS3MDL_PEER),
            &mut lis3mdl,
            &[CTRL_REG3, CONTINUOUS],
        );
        let mut frame = vec![OUT_X_L | BURST];
        frame.extend([0; 8]);
        let (on_board, expected) = alike(
            &mut board,
            30 * MILLISECOND,
            (IMU_ON, LIS3MDL_PEER),
            &mut lis3mdl,
            &frame,
        );
        assert_eq!(on_board, expected, "the magnetometer");
        assert_eq!(
            words(&expected[1..7], false),
            [COUNTS_PER_GAUSS, 0, COUNTS_PER_GAUSS]
        );
        assert_ne!(&expected[7..9], [0, 0], "the magnetometer's temperature");

        let mut at = 40 * MILLISECOND;
        let mut barometer = |board: &mut Pixracer, bytes: &[u8]| {
            at += 10 * MILLISECOND;
            alike(board, at, (FRAM_ON, MS5611_PEER), &mut ms5611, bytes)
        };
        barometer(&mut board, &[RESET]);
        barometer(&mut board, &[CONVERT_D1]);
        let (pressure, expected) = barometer(&mut board, &[ADC_READ, 0, 0, 0]);
        assert_eq!(pressure, expected, "the barometer's pressure conversion");
        assert_ne!(&expected[1..], [0, 0, 0]);
        barometer(&mut board, &[CONVERT_D2]);
        let (temperature, expected) = barometer(&mut board, &[ADC_READ, 0, 0, 0]);
        assert_eq!(
            temperature, expected,
            "the barometer's temperature conversion"
        );
        assert_ne!(&expected[1..], [0, 0, 0]);
    }

    #[test]
    fn the_board_has_its_mcu_and_reaches_a_model_by_field() {
        let mut board = Pixracer::new().unwrap();
        assert_eq!(board.name(), NAME);
        // No lookup and no downcast: the clock tree is a field of a field, and the crystal the board
        // fits is what it answers with.
        let (clocks, registers) = board.mcu.clocks();
        assert_eq!(
            clocks.sysclk(registers),
            16_000_000,
            "the part wakes on its own oscillator"
        );
        assert_eq!(board.hse, Crystal(24_000_000));
    }

    /// A board decides what hangs off its buses, and the chip answers the controller inside one transfer.
    /// This is the seam a sensor model arrives on; the bench drives the same one with a known pattern.
    #[test]
    fn a_board_can_hang_a_chip_on_one_of_its_interfaces() {
        /// The smallest thing that is a chip rather than a pattern: it answers what it is asked plus one.
        #[derive(Debug, Default)]
        struct Counter(u16);

        impl Peer for Counter {
            fn transfer(&mut self, mosi: u16, _context: &DeviceContext<'_>) -> u16 {
                self.0 = mosi.wrapping_add(1);
                self.0
            }
        }

        let mut board = Pixracer::new().unwrap();
        assert!(
            !board.mcu.spi[3].attached(),
            "a Pixracer fits nothing on its fourth interface"
        );
        board.mcu.spi[3].attach(Counter::default());
        assert!(board.mcu.spi[3].attached());
    }

    #[test]
    fn the_machine_routes_every_cpu_line_and_no_more() {
        let mut board = Pixracer::new().unwrap();
        let lines = board.mcu.cpu().interrupt_lines;
        let targets = board.targets();
        let [target] = &targets[..] else {
            panic!("one MCU on the board");
        };
        assert!((target.interrupt_line)(lines - 1).is_some());
    }

    #[test]
    fn the_machine_takes_its_interrupt_count_from_the_part() {
        let mut board = Pixracer::new().unwrap();
        let lines = board.mcu.cpu().interrupt_lines;
        let targets = board.targets();
        let declared = targets[0]
            .emulator
            .properties
            .iter()
            .find(|property| property.name == "num-irq")
            .expect("the machine is told its interrupt count");
        assert_eq!(
            declared.value,
            lines.to_string(),
            "the count the engine is given is the count the MCU has"
        );
    }
}