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
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
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
// Copyright (c) 2026 Rigless Labs.
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The Matek H743 flight controller: one STM32H743 and what the board fits around it.
//!
//! The board is ArduPilot's `MatekH743` target, and every pin and part here is a line of its board
//! description, `libraries/AP_HAL_ChibiOS/hwdef/MatekH743/hwdef.dat`.
//!
//! **The world's edge.** The board senses [`Signals`], the quantities a flight controller's transducers
//! measure, on the body axes, `x` forward, `y` right and `z` down, and hands each chip its share on the
//! chip's own axes. The firmware's driver for both inertial units takes their axes as they come and
//! applies the description's rotation, `ROTATION_YAW_180` for the ICM-42688-P and `ROTATION_YAW_270`
//! for the ICM-42605, so each unit is handed the body's axes turned back by its own. The board fits no
//! compass, and its description probes every I2C bus for an external one. A QMC5883L on the external
//! bus, `I2C1`, is the compass a GPS module brings. The firmware's driver reverses its `x` and `z` and
//! turns an external one `ROTATION_YAW_90`, then applies `ROTATION_ROLL_180`, the default it gives an
//! external QMC5883L, so the compass is handed the body's axes turned back by all three. The GPS
//! receiver sits on `serial3`, and the battery's two senses follow what the pack does. The board's
//! [`Outputs`] are the description's `PWM(1)` to `PWM(13)`, each read as the pulse on its pin and what
//! that pulse commands on the speed controllers' curve. The board senses the world at rest when it is
//! built.

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

use crate::chip::dps310::{Dps310, Sdo};
use crate::chip::icm42605::Icm42605;
use crate::chip::icm42688p::Icm42688p;
use crate::chip::qmc5883l::Qmc5883l;
use crate::chip::{Placed, nmea, uart};
use crate::cpu::armv7m::registers::{mask, set};
use crate::device::Level;
use crate::edge::{Condition, Coupled, Edge, Field, Pulse, Sensed, flag};
use crate::link::wire;
use crate::machine::armv7m;
use crate::machine::flight::{self, AT_REST, Actuator, Curve, SIGNAL_FIELDS, Signals};
use crate::machine::{Board, HostWire, Target};
use crate::snapshot::store;
use crate::soc::stm32h743::Stm32h743;
use crate::soc::stm32h743::peripherals::adc::Channel as AnalogChannel;
use crate::soc::stm32h743::peripherals::gpio::Pin;
use crate::soc::stm32h743::peripherals::spi::Select;
use crate::soc::stm32h743::peripherals::tim::Channel;
use crate::soc::{Access, Error, FieldSpec};
use crate::time::VirtualNanos;

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

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

/// The core clock the board's crystal and PLL give the MCU, the 400 MHz of DS12110 rev 11 table 2 at
/// the voltage scale ArduPilot's clock setup selects.
const CLOCK_HZ: NonZeroU64 = NonZeroU64::new(400_000_000).expect("a running clock");
/// The reference clock of the core's timer is the core clock over eight, RM0433 rev 9 section 19.1.1
/// and figure 49.
const REFCLK_DIVIDER: NonZeroU32 = NonZeroU32::new(8).expect("a divider divides");
/// The MCU implements four priority bits, RM0433 rev 9 section 19.1.
const PRIORITY_BITS: u8 = 4;
/// The core is a Cortex-M7, DS12110 rev 11 section 3.1.
const VARIANT: armv7m::Variant = armv7m::Variant::M7;
/// The core has a double-precision FPU, DS12110 rev 11 section 3.1.
const FPU: armv7m::Fpu = armv7m::Fpu::FpV5Dp;
/// The MPU has sixteen regions, DS12110 rev 11 section 3.2.
const MPU_REGIONS: armv7m::MpuRegions = armv7m::MpuRegions::Sixteen;
/// The BOOT pin is held low on the board, so the core boots from `BOOT_ADD0`, which ST programs to
/// the start of the main flash, RM0433 rev 9 section 2.6 and table 9.
const BOOT: &str = "flash";
/// The board's crystal, `OSCILLATOR_HZ 8000000` in its board description. It fits no low-speed one.
const HSE_HZ: u64 = 8_000_000;
/// The rail the board's regulator gives the MCU.
const SUPPLY_MV: u32 = 3300;
/// The first IMU, `SPIDEV icm42688 SPI1 DEVID1 IMU1_CS`, behind `PC15 IMU1_CS`, selected low.
const IMU1_ON: usize = 0;
const IMU1_CS: Select = Select {
    port: "GPIOC",
    pin: Pin::new(15).expect("a port has sixteen pins"),
    active: Level::Low,
};
/// The second IMU, `SPIDEV icm42605 SPI4 DEVID1 IMU3_CS`, behind `PC13 IMU3_CS`, selected low.
const IMU2_ON: usize = 3;
const IMU2_CS: Select = Select {
    port: "GPIOC",
    pin: Pin::new(13).expect("a port has sixteen pins"),
    active: Level::Low,
};
/// The barometer, `BARO DPS310 I2C:0:0x76`, on the first bus of `I2C_ORDER I2C2 I2C1`.
const BARO_ON: usize = 1;
/// The external compass, on the second bus of `I2C_ORDER`, `I2C1`, the one the board brings out for a
/// GPS module. A QMC5883L answers at `0x0D`, the address the firmware probes for it.
const COMPASS_ON: usize = 0;
/// Where each chip stands among its interface's peers, in the order `fit` hangs them.
const ICM42688P_PEER: usize = 0;
const ICM42605_PEER: usize = 0;
const DPS310_PEER: usize = 0;
const QMC5883L_PEER: usize = 0;
/// `serial3` of the description's `SERIAL_ORDER` is `USART2`, "USART2 (GPS1)": the receiver hangs
/// there.
const GPS: usize = 1;
/// The battery's voltage sense, `PC0 BATT_VOLTAGE_SENS ADC1`, on channel 10, and its current sense,
/// `PC1 BATT_CURRENT_SENS ADC1`, on channel 11. The pins reach all three converters. The board divides
/// the pack by `HAL_BATT_VOLT_SCALE 11.0` and gives `HAL_BATT_CURR_SCALE 40.0` amperes a volt.
const BATTERY_VOLTAGE: AnalogChannel = analog(10);
const BATTERY_CURRENT: AnalogChannel = analog(11);
const PACK_PER_SENSED: u32 = 11;
const MILLIAMPS_PER_MILLIVOLT: u32 = 40;
/// `PWM(1)` and `PWM(2)`: `PB0 TIM8_CH2N` and `PB1 TIM8_CH3N`, the complementary outputs of the second
/// advanced-control timer.
const MOTOR_TIMER: usize = 1;
const MOTOR_OUTPUTS: [(&str, Channel); 2] = [("PWM1", channel(2)), ("PWM2", channel(3))];
/// `PWM(3)` to `PWM(6)`: `PA0` to `PA3`, `TIM5_CH1` to `TIM5_CH4`, the fourth general-purpose timer.
const TIM5: usize = 3;
const TIM5_OUTPUTS: [(&str, Channel); 4] = [
    ("PWM3", channel(1)),
    ("PWM4", channel(2)),
    ("PWM5", channel(3)),
    ("PWM6", channel(4)),
];
/// `PWM(7)` to `PWM(10)`: `PD12` to `PD15`, `TIM4_CH1` to `TIM4_CH4`, the third general-purpose timer.
const TIM4: usize = 2;
const TIM4_OUTPUTS: [(&str, Channel); 4] = [
    ("PWM7", channel(1)),
    ("PWM8", channel(2)),
    ("PWM9", channel(3)),
    ("PWM10", channel(4)),
];
/// `PWM(11)` and `PWM(12)`: `PE5 TIM15_CH1` and `PE6 TIM15_CH2`.
const TIM15_OUTPUTS: [(&str, Channel); 2] = [("PWM11", channel(1)), ("PWM12", channel(2))];
/// `PWM(13)`: `PA8 TIM1_CH1`, the first advanced-control timer, the description's LED output.
const LED_TIMER: usize = 0;
const LED_OUTPUT: (&str, Channel) = ("PWM13", channel(1));
/// 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),
};
/// The names each chip's noise on each quantity crosses the link as, which key its draws too.
const ICM42688P_RATE_NOISE: [&str; 3] = [
    "icm42688p.rate.noise.x",
    "icm42688p.rate.noise.y",
    "icm42688p.rate.noise.z",
];
const ICM42688P_ACCELERATION_NOISE: [&str; 3] = [
    "icm42688p.acceleration.noise.x",
    "icm42688p.acceleration.noise.y",
    "icm42688p.acceleration.noise.z",
];
const ICM42605_RATE_NOISE: [&str; 3] = [
    "icm42605.rate.noise.x",
    "icm42605.rate.noise.y",
    "icm42605.rate.noise.z",
];
const ICM42605_ACCELERATION_NOISE: [&str; 3] = [
    "icm42605.acceleration.noise.x",
    "icm42605.acceleration.noise.y",
    "icm42605.acceleration.noise.z",
];
const QMC5883L_FIELD_NOISE: [&str; 3] = [
    "qmc5883l.field.noise.x",
    "qmc5883l.field.noise.y",
    "qmc5883l.field.noise.z",
];
const DPS310_PRESSURE_NOISE: [&str; 1] = ["dps310.pressure.noise"];
/// The names the GPS port's two error rates cross the link as, which key its draws too.
const GPS_NOISE_ERRORS: &str = "gps.noise_errors";
const GPS_FRAMING_ERRORS: &str = "gps.framing_errors";

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

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

/// The body's axes as a unit mounted `ROTATION_YAW_180` reads them: the firmware turns `x` and `y`
/// over, `AP_Math/vector3.cpp`, so the unit is handed them turned over already.
fn turned_yaw_180([x, y, z]: [i32; 3]) -> [i32; 3] {
    [x.saturating_neg(), y.saturating_neg(), z]
}

/// The body's axes as a unit mounted `ROTATION_YAW_270` reads them: the firmware takes the unit's
/// `y` as the body's `x` and its `x` reversed as the body's `y`, so the unit is handed `-y` and `x`.
fn turned_yaw_270([x, y, z]: [i32; 3]) -> [i32; 3] {
    [y.saturating_neg(), x, z]
}

/// The body's axes as the external compass reads them. The firmware's driver takes the chip's `-x`, `y`
/// and `-z`, `AP_Compass_QMC5883L.cpp`, turns them `ROTATION_YAW_90` because the compass is external,
/// then applies the external default `ROTATION_ROLL_180`, `AP_Math/vector3.cpp`. The three together
/// take the chip's `x` as the body's `y` and its `y` reversed as the body's `x`, so the chip is handed
/// `y` and `-x`.
fn turned_for_the_compass([x, y, z]: [i32; 3]) -> [i32; 3] {
    [y, x.saturating_neg(), z]
}

/// One of the board's outputs read off its timer.
fn actuator(name: &'static str, pulse: Option<Pulse>) -> Actuator {
    Actuator::on(name, pulse, SPEED_CONTROLLER)
}

/// What the firmware drives on the board: the description's `PWM(1)` to `PWM(13)`, in that order.
pub type Outputs = flight::Outputs<13>;

/// What can be wrong with the board's own chips, apart from what the world does to them: one that's
/// stopped answering, what one senses wrong of each quantity on the body's axes while the chip beside
/// it senses the truth, and a GPS line that garbles what it carries. The default is the board as built.
#[derive(
    Debug, Clone, Copy, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize,
)]
#[expect(
    clippy::struct_excessive_bools,
    reason = "each is a different chip's silence, one byte on the wire, and no two make a state"
)]
pub struct Conditions {
    /// The ICM-42688-P, the firmware's first inertial unit.
    pub icm42688p_silent: bool,
    /// What it senses of the angular rate.
    pub icm42688p_rate: Condition<3>,
    /// What it senses of the specific force.
    pub icm42688p_acceleration: Condition<3>,
    /// The ICM-42605, the second.
    pub icm42605_silent: bool,
    /// What it senses of the angular rate.
    pub icm42605_rate: Condition<3>,
    /// What it senses of the specific force.
    pub icm42605_acceleration: Condition<3>,
    /// The DPS310 barometer.
    pub dps310_silent: bool,
    /// What it senses of the pressure.
    pub dps310_pressure: Condition<1>,
    /// The external QMC5883L compass.
    pub qmc5883l_silent: bool,
    /// What it senses of the field.
    pub qmc5883l_field: Condition<3>,
    /// The GPS receiver on its port.
    pub gps_silent: bool,
    /// Words in a million arriving from it with noise on them.
    pub gps_noise_errors: u32,
    /// Words in a million arriving from it with a framing error.
    pub gps_framing_errors: u32,
}

/// What each chip was last handed of each quantity a condition reaches, on the body's axes.
#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
struct Handed {
    icm42688p_rate: Sensed<i32, 3>,
    icm42688p_acceleration: Sensed<i32, 3>,
    icm42605_rate: Sensed<i32, 3>,
    icm42605_acceleration: Sensed<i32, 3>,
    qmc5883l_field: Sensed<i32, 3>,
    dps310_pressure: Sensed<u32, 1>,
}
/// The telemetry port, ArduPilot's `SERIAL1`: `UART7` by the board description's `SERIAL_ORDER`, the
/// seventh of [`usart::INSTANCES`](crate::soc::stm32h743::peripherals::usart::INSTANCES).
const TELEMETRY: usize = 6;
/// The wire a ground station sits on, at the port it listens on.
const TELEMETRY_WIRE: HostWire = HostWire {
    name: "serial1",
    port: 5760,
};
/// Where the core finds its vector table at reset: `BOOT_ADD0` as ST programs it, RM0433 rev 9 table 9.
/// Address zero is the ITCM, so nothing aliases the flash there.
const VECTOR_TABLE: u32 = 0x0800_0000;
/// The core is a Cortex-M7 r1p1, ES0392 rev 15 section 2.1, so `CPUID` is Arm's implementer code,
/// variant 1, the M7's part number and revision 1, laid out as PM0253 rev 6 table 52 gives them.
const CPUID: u32 = 0x411F_C271;
/// The 16 Kbyte instruction and data caches of DS12110 rev 11 section 3.1: `CLIDR` and `CTR` as PM0253
/// rev 6 table 77 gives them, and each cache's `CCSIDR` from table 81, the data cache's first since
/// `CSSELR` selects it with zero.
const CACHES: armv7m::Caches = armv7m::Caches {
    clidr: 0x0900_0003,
    ctr: 0x8303_C003,
    ccsidr: &[0xF00F_E019, 0xF01F_E009],
};
// The fields of the access control registers, PM0253 rev 6 tables 105 to 108: `ITCMCR` and `DTCMCR`,
// `AHBPCR`, `CACR` and `AHBSCR`.
const TCM_EN: FieldSpec = FieldSpec::new("EN", 0, 1, Access::ReadWrite);
const TCM_RMW: FieldSpec = FieldSpec::new("RMW", 1, 1, Access::ReadWrite);
const TCM_RETEN: FieldSpec = FieldSpec::new("RETEN", 2, 1, Access::ReadWrite);
const TCM_SZ: FieldSpec = FieldSpec::new("SZ", 3, 4, Access::ReadOnly);
const AHBP_EN: FieldSpec = FieldSpec::new("EN", 0, 1, Access::ReadWrite);
const CACR_SIWT: FieldSpec = FieldSpec::new("SIWT", 0, 1, Access::ReadWrite);
const CACR_ECCEN: FieldSpec = FieldSpec::new("ECCEN", 1, 1, Access::ReadWrite);
const CACR_FORCEWT: FieldSpec = FieldSpec::new("FORCEWT", 2, 1, Access::ReadWrite);
const AHBS_CTL: FieldSpec = FieldSpec::new("CTL", 0, 2, Access::ReadWrite);
const AHBS_TPRI: FieldSpec = FieldSpec::new("TPRI", 2, 9, Access::ReadWrite);
const AHBS_INITCOUNT: FieldSpec = FieldSpec::new("INITCOUNT", 11, 5, Access::ReadWrite);
/// The 64 Kbyte ITCM and the 128 Kbyte DTCM of RM0433 rev 9 section 2.4, as table 105 encodes their
/// sizes.
const ITCM_64K: u32 = 0b0111;
const DTCM_128K: u32 = 0b1000;
const TCM_WRITABLE: u32 = mask(&TCM_EN) | mask(&TCM_RMW) | mask(&TCM_RETEN);
/// The access control registers of PM0253 rev 6 table 104, with the bits tables 105 to 109 make
/// writable. Every one resets to zero but the TCMs' read-only sizes and `AHBSCR`'s `INITCOUNT`,
/// whose reset value table 108 gives as `0b01`. `CACR` resets to zero, the value table 107 gives a
/// core with cache ECC, and `ABFSR` never records a fault since the runtime has no asynchronous
/// ones.
const ACCESS_CONTROL: [armv7m::ImplementationRegister; 6] = [
    register(0xF90, set(&TCM_SZ, 0, ITCM_64K), TCM_WRITABLE),
    register(0xF94, set(&TCM_SZ, 0, DTCM_128K), TCM_WRITABLE),
    register(0xF98, 0, mask(&AHBP_EN)),
    register(
        0xF9C,
        0,
        mask(&CACR_SIWT) | mask(&CACR_ECCEN) | mask(&CACR_FORCEWT),
    ),
    register(
        0xFA0,
        set(&AHBS_INITCOUNT, 0, 0b01),
        mask(&AHBS_CTL) | mask(&AHBS_TPRI) | mask(&AHBS_INITCOUNT),
    ),
    register(0xFA8, 0, 0),
];

const fn register(offset: u64, reset: u32, writable: u32) -> armv7m::ImplementationRegister {
    armv7m::ImplementationRegister {
        offset,
        reset,
        writable,
    }
}

/// The Matek H743: the MCU, and what the board fits around it.
#[derive(Debug)]
pub struct MatekH743 {
    /// The STM32H743.
    pub mcu: Stm32h743,
    conditions: Conditions,
    handed: Handed,
    /// What the board last sensed, so a condition that changes on its own reaches the chips at once.
    sensed: Signals,
}

impl MatekH743 {
    /// The board as it is built: the MCU out of reset, then what this board fits attached to it,
    /// sensing the world at rest.
    pub fn new() -> Result<Self, Error> {
        let mut board = Self {
            mcu: Stm32h743::new()?,
            conditions: Conditions::default(),
            handed: Handed::default(),
            sensed: AT_REST,
        };
        board.fit();
        board.sense(&AT_REST);
        Ok(board)
    }

    /// What the board puts on the part's pins. Every line here is a line of its board description, but
    /// for the compass, which is the one a GPS module brings.
    fn fit(&mut self) {
        self.mcu.rcc.attach_crystals(HSE_HZ, 0);
        self.mcu.set_supply(SUPPLY_MV);
        self.mcu.set_analog_supply(SUPPLY_MV);
        for converter in &mut self.mcu.adc {
            converter.set_reference(SUPPLY_MV);
        }
        self.mcu.spi[IMU1_ON].attach_selected(Icm42688p::new(), IMU1_CS);
        self.mcu.spi[IMU2_ON].attach_selected(Icm42605::new(), IMU2_CS);
        self.mcu.i2c[BARO_ON].attach(Dps310::new(Sdo::Low));
        self.mcu.i2c[COMPASS_ON].attach(Qmc5883l::new());
        self.mcu.usart[GPS].attach(nmea::Receiver::new());
    }

    /// The board's core as its target makes it: the part's Cortex-M7, with the interrupt lines and
    /// the windows of the processor's own bus its MCU has.
    #[must_use]
    pub fn config(&self) -> armv7m::Config {
        let core = armv7m::Core {
            variant: VARIANT,
            clock_hz: CLOCK_HZ,
            interrupt_lines: NonZeroU32::new(u32::from(
                crate::mcu::Operate::cpu(&self.mcu).interrupt_lines,
            ))
            .expect("an MCU with interrupts"),
            priority_bits: PRIORITY_BITS,
            refclk_divider: REFCLK_DIVIDER,
            instructions_per_second: armv7m::INSTRUCTIONS_PER_SECOND,
            boot: BOOT,
        };
        let mut config = armv7m::Config::new(
            core,
            &crate::cpu::armv7m::windows(crate::mcu::Mcu::bus(&self.mcu)),
        );
        config.fpu = FPU;
        config.mpu_regions = MPU_REGIONS;
        config.cpuid = CPUID;
        config.caches = Some(CACHES);
        // CCR.BP always reads as one on this core, PM0253 rev 6 section 4.3.7.
        config.branch_prediction = armv7m::BranchPrediction::Always;
        config.implementation_registers = ACCESS_CONTROL.to_vec();
        config.vector_table = Some(VECTOR_TABLE);
        config
    }
}

store!(MatekH743 {
    values: [conditions, handed, sensed],
    parts: [mcu],
    built: [],
});

impl Board for MatekH743 {
    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 core = self.config().spec();
        vec![Target::new(MCU, &mut self.mcu, core)]
    }

    fn edge(&mut self) -> Option<&mut dyn Coupled> {
        Some(self)
    }

    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
    }

    fn host_mut(&mut self, name: &str) -> Option<&mut dyn uart::Peer> {
        if name == TELEMETRY_WIRE.name {
            self.mcu.usart[TELEMETRY].peer_mut()
        } else {
            None
        }
    }
}

impl Edge for MatekH743 {
    type Signals = Signals;

    type Outputs = Outputs;

    type Conditions = Conditions;

    const OUTPUT_FIELDS: &'static [Field] = Outputs::FIELDS;

    const FIELDS: &'static [Field] = SIGNAL_FIELDS;

    /// A silence is a flag. A stuck quantity is a flag, and its bias and its noise's standard
    /// deviation are in the signal's own unit, on the body's axes. A serial port's errors are words in
    /// a million.
    const CONDITIONS: &'static [Field] = &[
        Field::new("icm42688p.silent", "flag", 1, false),
        Field::new("icm42688p.rate.stuck", "flag", 1, false),
        Field::new("icm42688p.rate.bias.x", "mdeg/s", 4, true),
        Field::new("icm42688p.rate.bias.y", "mdeg/s", 4, true),
        Field::new("icm42688p.rate.bias.z", "mdeg/s", 4, true),
        Field::new(ICM42688P_RATE_NOISE[0], "mdeg/s", 4, false),
        Field::new(ICM42688P_RATE_NOISE[1], "mdeg/s", 4, false),
        Field::new(ICM42688P_RATE_NOISE[2], "mdeg/s", 4, false),
        Field::new("icm42688p.acceleration.stuck", "flag", 1, false),
        Field::new("icm42688p.acceleration.bias.x", "1e-6 g", 4, true),
        Field::new("icm42688p.acceleration.bias.y", "1e-6 g", 4, true),
        Field::new("icm42688p.acceleration.bias.z", "1e-6 g", 4, true),
        Field::new(ICM42688P_ACCELERATION_NOISE[0], "1e-6 g", 4, false),
        Field::new(ICM42688P_ACCELERATION_NOISE[1], "1e-6 g", 4, false),
        Field::new(ICM42688P_ACCELERATION_NOISE[2], "1e-6 g", 4, false),
        Field::new("icm42605.silent", "flag", 1, false),
        Field::new("icm42605.rate.stuck", "flag", 1, false),
        Field::new("icm42605.rate.bias.x", "mdeg/s", 4, true),
        Field::new("icm42605.rate.bias.y", "mdeg/s", 4, true),
        Field::new("icm42605.rate.bias.z", "mdeg/s", 4, true),
        Field::new(ICM42605_RATE_NOISE[0], "mdeg/s", 4, false),
        Field::new(ICM42605_RATE_NOISE[1], "mdeg/s", 4, false),
        Field::new(ICM42605_RATE_NOISE[2], "mdeg/s", 4, false),
        Field::new("icm42605.acceleration.stuck", "flag", 1, false),
        Field::new("icm42605.acceleration.bias.x", "1e-6 g", 4, true),
        Field::new("icm42605.acceleration.bias.y", "1e-6 g", 4, true),
        Field::new("icm42605.acceleration.bias.z", "1e-6 g", 4, true),
        Field::new(ICM42605_ACCELERATION_NOISE[0], "1e-6 g", 4, false),
        Field::new(ICM42605_ACCELERATION_NOISE[1], "1e-6 g", 4, false),
        Field::new(ICM42605_ACCELERATION_NOISE[2], "1e-6 g", 4, false),
        Field::new("dps310.silent", "flag", 1, false),
        Field::new("dps310.pressure.stuck", "flag", 1, false),
        Field::new("dps310.pressure.bias", "Pa", 4, true),
        Field::new(DPS310_PRESSURE_NOISE[0], "Pa", 4, false),
        Field::new("qmc5883l.silent", "flag", 1, false),
        Field::new("qmc5883l.field.stuck", "flag", 1, false),
        Field::new("qmc5883l.field.bias.x", "nT", 4, true),
        Field::new("qmc5883l.field.bias.y", "nT", 4, true),
        Field::new("qmc5883l.field.bias.z", "nT", 4, true),
        Field::new(QMC5883L_FIELD_NOISE[0], "nT", 4, false),
        Field::new(QMC5883L_FIELD_NOISE[1], "nT", 4, false),
        Field::new(QMC5883L_FIELD_NOISE[2], "nT", 4, false),
        Field::new("gps.silent", "flag", 1, false),
        Field::new(GPS_NOISE_ERRORS, "1e-6", 4, false),
        Field::new(GPS_FRAMING_ERRORS, "1e-6", 4, false),
    ];

    const REST: Signals = AT_REST;

    /// Every chip a trigger or a one-shot fault can name, by the name its conditions start with. The
    /// part's I2C buses open and count no transaction for a trigger, so the barometer and the compass
    /// are silenced and conditioned but never named here.
    const CHIPS: &'static [&'static str] = &["icm42688p", "icm42605", "gps"];

    /// Each chip by its name in [`Edge::CHIPS`], so the list's order is the one place it's kept.
    fn place(&mut self, chip: usize) -> Option<&mut dyn Placed> {
        match *Self::CHIPS.get(chip)? {
            "icm42688p" => self.mcu.spi[IMU1_ON].place_mut(ICM42688P_PEER),
            "icm42605" => self.mcu.spi[IMU2_ON].place_mut(ICM42605_PEER),
            "gps" => self.mcu.usart[GPS].place_mut(),
            _ => None,
        }
    }

    /// Each chip takes the body's axes turned back by its mounting, and senses through its own
    /// conditions, so one unit can read wrong while the other reads the truth. The barometer and the
    /// receiver have no axes, and the battery's senses are the pack through the board's dividers.
    fn sense(&mut self, signals: &Signals) {
        self.sensed = *signals;
        let (conditions, handed) = (&self.conditions, &mut self.handed);
        let unit: &mut Icm42688p = self.mcu.spi[IMU1_ON]
            .chip_mut(ICM42688P_PEER)
            .expect("fit hangs it");
        let [x, y, z] = turned_yaw_180(
            handed
                .icm42688p_rate
                .hand(signals.angular_rate, &conditions.icm42688p_rate),
        );
        unit.set_rate(x, y, z);
        let [x, y, z] = turned_yaw_180(
            handed
                .icm42688p_acceleration
                .hand(signals.specific_force, &conditions.icm42688p_acceleration),
        );
        unit.set_acceleration(x, y, z);
        unit.set_temperature(signals.temperature);
        let unit: &mut Icm42605 = self.mcu.spi[IMU2_ON]
            .chip_mut(ICM42605_PEER)
            .expect("fit hangs it");
        let [x, y, z] = turned_yaw_270(
            handed
                .icm42605_rate
                .hand(signals.angular_rate, &conditions.icm42605_rate),
        );
        unit.set_rate(x, y, z);
        let [x, y, z] = turned_yaw_270(
            handed
                .icm42605_acceleration
                .hand(signals.specific_force, &conditions.icm42605_acceleration),
        );
        unit.set_acceleration(x, y, z);
        unit.set_temperature(signals.temperature);
        let compass: &mut Qmc5883l = self.mcu.i2c[COMPASS_ON]
            .chip_mut(QMC5883L_PEER)
            .expect("fit hangs it");
        let [x, y, z] = turned_for_the_compass(
            handed
                .qmc5883l_field
                .hand(signals.magnetic_field, &conditions.qmc5883l_field),
        );
        compass.set_field(x, y, z);
        compass.set_temperature(signals.temperature);
        let barometer: &mut Dps310 = self.mcu.i2c[BARO_ON]
            .chip_mut(DPS310_PEER)
            .expect("fit hangs it");
        let [pressure] = handed
            .dps310_pressure
            .hand([signals.pressure], &conditions.dps310_pressure);
        barometer.set_pressure(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 current = u32::try_from(signals.battery_current).unwrap_or(0) / MILLIAMPS_PER_MILLIVOLT;
        for converter in &mut self.mcu.adc {
            converter.set_input(BATTERY_VOLTAGE, signals.battery_voltage / PACK_PER_SENSED);
            converter.set_input(BATTERY_CURRENT, current);
        }
    }

    /// Each silence goes on the chip's place on its bus, the GPS port garbles at its rates, and each
    /// chip senses what the board last sensed again through its own conditions.
    fn condition(&mut self, conditions: &Conditions) {
        self.conditions = *conditions;
        let fitted = self.mcu.spi[IMU1_ON].silence(ICM42688P_PEER, conditions.icm42688p_silent)
            & self.mcu.spi[IMU2_ON].silence(ICM42605_PEER, conditions.icm42605_silent)
            & self.mcu.i2c[BARO_ON].silence(DPS310_PEER, conditions.dps310_silent)
            & self.mcu.i2c[COMPASS_ON].silence(QMC5883L_PEER, conditions.qmc5883l_silent)
            & self.mcu.usart[GPS].silence(conditions.gps_silent);
        assert!(fitted, "fit hangs every chip a condition names");
        let errors = self.mcu.usart[GPS].errors_mut();
        errors.noise = uart::Rate {
            name: GPS_NOISE_ERRORS,
            per_million: conditions.gps_noise_errors,
        };
        errors.framing = uart::Rate {
            name: GPS_FRAMING_ERRORS,
            per_million: conditions.gps_framing_errors,
        };
        let sensed = self.sensed;
        self.sense(&sensed);
    }

    /// Each noisy quantity draws its noise for the step, and the board senses again when any moved.
    /// The GPS port's errors draw under the same seed as each word arrives.
    fn draw(&mut self, seed: u64, index: u64) {
        self.mcu.usart[GPS].errors_mut().seed = seed;
        let (conditions, handed) = (&self.conditions, &mut self.handed);
        let moved = [
            handed.icm42688p_rate.draw(
                &conditions.icm42688p_rate,
                &ICM42688P_RATE_NOISE,
                seed,
                index,
            ),
            handed.icm42688p_acceleration.draw(
                &conditions.icm42688p_acceleration,
                &ICM42688P_ACCELERATION_NOISE,
                seed,
                index,
            ),
            handed
                .icm42605_rate
                .draw(&conditions.icm42605_rate, &ICM42605_RATE_NOISE, seed, index),
            handed.icm42605_acceleration.draw(
                &conditions.icm42605_acceleration,
                &ICM42605_ACCELERATION_NOISE,
                seed,
                index,
            ),
            handed.qmc5883l_field.draw(
                &conditions.qmc5883l_field,
                &QMC5883L_FIELD_NOISE,
                seed,
                index,
            ),
            handed.dps310_pressure.draw(
                &conditions.dps310_pressure,
                &DPS310_PRESSURE_NOISE,
                seed,
                index,
            ),
        ];
        if moved.contains(&true) {
            let sensed = self.sensed;
            self.sense(&sensed);
        }
    }

    fn drive(&mut self) -> Outputs {
        let (motors, registers) = self.mcu.advanced_timer(MOTOR_TIMER);
        let [one, two] = MOTOR_OUTPUTS
            .map(|(name, channel)| actuator(name, motors.complementary_pulse(channel, registers)));
        let (tim5, registers) = self.mcu.timer(TIM5);
        let [three, four, five, six] =
            TIM5_OUTPUTS.map(|(name, channel)| actuator(name, tim5.pulse(channel, registers)));
        let (tim4, registers) = self.mcu.timer(TIM4);
        let [seven, eight, nine, ten] =
            TIM4_OUTPUTS.map(|(name, channel)| actuator(name, tim4.pulse(channel, registers)));
        let (tim15, registers) = self.mcu.timer_15();
        let [eleven, twelve] =
            TIM15_OUTPUTS.map(|(name, channel)| actuator(name, tim15.pulse(channel, registers)));
        let (led, registers) = self.mcu.advanced_timer(LED_TIMER);
        let thirteen = actuator(LED_OUTPUT.0, led.pulse(LED_OUTPUT.1, registers));
        flight::Outputs([
            one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen,
        ])
    }
}

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

wire!(Conditions {
    icm42688p_silent with flag,
    icm42688p_rate,
    icm42688p_acceleration,
    icm42605_silent with flag,
    icm42605_rate,
    icm42605_acceleration,
    dps310_silent with flag,
    dps310_pressure,
    qmc5883l_silent with flag,
    qmc5883l_field,
    gps_silent with flag,
    gps_noise_errors,
    gps_framing_errors,
});

#[cfg(test)]
mod tests {
    use super::*;
    use crate::chip::{Timeline, i2c, spi};
    use crate::edge::normal;
    use crate::link::serve::deliver;
    use crate::link::{Advance, Held, Set, Wire, values_of};
    use crate::machine::flight::conformance::{self, wrong};
    use crate::mcu::{Operate, Single};
    use crate::soc::stm32h743::generated::{RCC, TIM1, TIM4, TIM5, TIM8, TIM15};
    use crate::soc::stm32h743::generated::{rcc, tim1, tim2, tim15};
    use crate::soc::stm32h743::peripherals::rcc::TimerBus;
    use crate::soc::stm32h743::peripherals::spi::{Kind, Spi};
    use crate::soc::stm32h743::peripherals::usart;
    use crate::soc::{Layout, Peripheral, Width};

    const MILLISECOND: u64 = 1_000_000;
    const MICROSECOND: u64 = 1_000;

    /// DS-000347 rev 1.6 and the ICM-42605 sheet: the read flag, the power register, both sensors in
    /// low noise, and the first register of the sense burst, temperature then force then rate.
    const READ: u8 = 0x80;
    const PWR_MGMT0: u8 = 0x4E;
    const BOTH_ON: u8 = 0x0F;
    const TEMP_DATA1: u8 = 0x1D;
    /// The QMC5883L's first data register, its temperature register, its control register 1 and
    /// the fields of that register that put it in continuous mode at 8 G and 200 Hz, QST's datasheet
    /// version 1.0 tables 13 and 18, and its address, section 5.4.
    const OUT_X_L: u8 = 0x00;
    const TOUT_L: u8 = 0x07;
    const CONTROL1: u8 = 0x09;
    const CONTINUOUS: u8 = 0x01;
    const ODR_200: u8 = 0x0C;
    const RNG_8G: u8 = 0x10;
    const COMPASS_ADDRESS: u8 = 0x0D;
    /// The DPS310's measurement control, the two one-shot commands, and the address `SDO` low gives.
    const MEAS_CFG: u8 = 0x08;
    const PRESSURE_ONCE: u8 = 0x01;
    const TEMPERATURE_ONCE: u8 = 0x02;
    const BARO_ADDRESS: u8 = 0x76;
    const PWM_MODE_1: u64 = 0b110;
    const PWM_PERIOD_COUNTS: u64 = 20_000;

    /// A body that turns about, accelerates along and senses a field on three different axes by three
    /// different amounts, so a swap or a sign error on any axis of any quantity shows.
    const BODY: Signals = Signals {
        angular_rate: [30_000, -50_000, 70_000],
        specific_force: [1_250_000, -2_500_000, 750_000],
        magnetic_field: [30_000, -20_000, 45_000],
        pressure: 95_000,
        ..AT_REST
    };

    /// `Vector3<T>::rotate` of `AP_Math/vector3.cpp` for `ROTATION_YAW_90`, `x = -y, y = x`, which is
    /// what the firmware applies to what an external compass reports.
    fn ardupilot_yaw_90([x, y, z]: [i32; 3]) -> [i32; 3] {
        [-y, x, z]
    }

    /// The same function's `ROTATION_ROLL_180`, `y = -y, z = -z`, the default rotation of an external
    /// QMC5883L.
    fn ardupilot_roll_180([x, y, z]: [i32; 3]) -> [i32; 3] {
        [x, -y, -z]
    }

    /// `AP_Compass_QMC5883L::timer` step for step: the chip's words with `x` and `z` negated, turned
    /// `ROTATION_YAW_90` because the compass is external, then the backend's `ROTATION_ROLL_180`.
    fn ardupilot_qmc5883l_driver([x, y, z]: [i32; 3]) -> [i32; 3] {
        ardupilot_roll_180(ardupilot_yaw_90([-x, y, -z]))
    }

    /// The same function's `ROTATION_YAW_180`, `x = -x, y = -y`.
    fn ardupilot_yaw_180([x, y, z]: [i32; 3]) -> [i32; 3] {
        [-x, -y, z]
    }

    /// The same function's `ROTATION_YAW_270`, `x = y, y = -x`.
    fn ardupilot_yaw_270([x, y, z]: [i32; 3]) -> [i32; 3] {
        [y, -x, z]
    }

    /// The body's axes as a unit mounted `ROTATION_YAW_180` is handed them.
    fn behind_yaw_180([x, y, z]: [i32; 3]) -> [i32; 3] {
        [-x, -y, z]
    }

    /// The body's axes as a unit mounted `ROTATION_YAW_270` is handed them.
    fn behind_yaw_270([x, y, z]: [i32; 3]) -> [i32; 3] {
        [-y, x, z]
    }

    /// The body's axes as the external compass is handed them: the chip's `x` is the body's `y` and
    /// its `y` is the body's `x` reversed.
    fn behind_the_compass([x, y, z]: [i32; 3]) -> [i32; 3] {
        [y, -x, z]
    }

    /// Counts of a quantity at `counts_per_million` counts for a million of its unit, to the nearest.
    fn counts(value: i32, counts_per_million: i64) -> i32 {
        i32::try_from(crate::chip::round(
            i64::from(value) * counts_per_million,
            1_000_000,
        ))
        .expect("a count fits")
    }

    /// The three counts of `body` at `counts_per_million`.
    fn counts_of(body: [i32; 3], counts_per_million: i64) -> [i32; 3] {
        body.map(|value| counts(value, counts_per_million))
    }

    fn near(found: [i32; 3], expected: [i32; 3], what: &str) {
        for axis in 0..3 {
            assert!(
                found[axis].abs_diff(expected[axis]) <= 1,
                "{what}: {found:?} against {expected:?}"
            );
        }
    }

    /// The accelerometer's 2048 counts a gravity at the reset range, 16 g, and the gyroscope's 16.384
    /// counts for a degree a second at the reset range, 2000 dps, as counts for a million of the
    /// board's unit.
    const ACCEL_COUNTS_PER_MILLION: i64 = 2048;
    const RATE_COUNTS_PER_MILLION: i64 = 16_384;
    /// The QMC5883L's 3000 counts a gauss at 8 G, as counts for a million nanotesla, with a gauss
    /// 100 000 nT.
    const FIELD_COUNTS_PER_MILLION: i64 = 3_000 * 10;

    fn words(bytes: &[u8], big_endian: bool) -> Vec<i32> {
        bytes
            .chunks(2)
            .map(|pair| {
                i32::from(if big_endian {
                    i16::from_be_bytes([pair[0], pair[1]])
                } else {
                    i16::from_le_bytes([pair[0], pair[1]])
                })
            })
            .collect()
    }

    fn triple(words: &[i32]) -> [i32; 3] {
        [words[0], words[1], words[2]]
    }

    /// A bus on its own that hands a chip the context a controller hands it.
    fn bus() -> Single<Spi> {
        Single::new(
            crate::soc::stm32h743::builder(),
            "SPI1",
            Spi::new(Kind::FULL),
        )
        .expect("the bus builds")
    }

    fn spi_cycle(
        bus: &mut Single<Spi>,
        at: u64,
        chip: &mut dyn spi::Peer,
        bytes: &[u8],
    ) -> Vec<u8> {
        bus.drive(VirtualNanos(at), |_, _, context| {
            let context = &mut Timeline::new(context);
            chip.select(context);
            let answers = bytes
                .iter()
                .map(|&byte| u8::try_from(chip.transfer(u32::from(byte), 8, context)).unwrap())
                .collect();
            chip.deselect(context);
            answers
        })
    }

    fn i2c_write(
        bus: &mut Single<Spi>,
        at: u64,
        chip: &mut dyn i2c::Peer,
        address: u8,
        bytes: &[u8],
    ) {
        bus.drive(VirtualNanos(at), |_, _, context| {
            let context = &mut Timeline::new(context);
            assert!(
                chip.start(address, false, context),
                "{address:#04x} acknowledges"
            );
            for &byte in bytes {
                assert!(chip.write(byte, context));
            }
            chip.stop(context);
        });
    }

    fn i2c_read(
        bus: &mut Single<Spi>,
        at: u64,
        chip: &mut dyn i2c::Peer,
        (address, register): (u8, u8),
        count: usize,
    ) -> Vec<u8> {
        bus.drive(VirtualNanos(at), |_, _, context| {
            let context = &mut Timeline::new(context);
            assert!(
                chip.start(address, false, context),
                "{address:#04x} acknowledges"
            );
            assert!(chip.write(register, context));
            assert!(chip.start(address, true, context));
            let bytes = (0..count)
                .map(|index| chip.read(index + 1 == count, context))
                .collect();
            chip.stop(context);
            bytes
        })
    }

    /// An inertial unit woken into low noise and read once, as a driver reads it: the temperature
    /// word, the three force words and the three rate words, big-endian as the part resets.
    fn inertial_words(unit: &mut dyn spi::Peer) -> Vec<i32> {
        let mut bus = bus();
        spi_cycle(&mut bus, MILLISECOND, unit, &[PWR_MGMT0, BOTH_ON]);
        let mut frame = vec![TEMP_DATA1 | READ];
        frame.extend([0; 14]);
        let bytes = spi_cycle(&mut bus, 6 * MILLISECOND, unit, &frame);
        words(&bytes[1..], true)
    }

    /// A compass put into continuous measurement at 8 G and 200 Hz and read once: the three field
    /// words and the temperature word, little-endian.
    fn compass_words(compass: &mut dyn i2c::Peer) -> Vec<i32> {
        let mut bus = bus();
        i2c_write(
            &mut bus,
            MILLISECOND,
            compass,
            COMPASS_ADDRESS,
            &[CONTROL1, RNG_8G | ODR_200 | CONTINUOUS],
        );
        let mut bytes = i2c_read(
            &mut bus,
            30 * MILLISECOND,
            compass,
            (COMPASS_ADDRESS, OUT_X_L),
            6,
        );
        bytes.extend(i2c_read(
            &mut bus,
            31 * MILLISECOND,
            compass,
            (COMPASS_ADDRESS, TOUT_L),
            2,
        ));
        words(&bytes, false)
    }

    /// A barometer past its start-up that measures a pressure once and a temperature once, and the
    /// six result bytes of both.
    fn barometer_bytes(barometer: &mut dyn i2c::Peer) -> Vec<u8> {
        let mut bus = bus();
        i2c_write(
            &mut bus,
            50 * MILLISECOND,
            barometer,
            BARO_ADDRESS,
            &[MEAS_CFG, PRESSURE_ONCE],
        );
        let mut bytes = i2c_read(
            &mut bus,
            100 * MILLISECOND,
            barometer,
            (BARO_ADDRESS, 0x00),
            3,
        );
        i2c_write(
            &mut bus,
            110 * MILLISECOND,
            barometer,
            BARO_ADDRESS,
            &[MEAS_CFG, TEMPERATURE_ONCE],
        );
        bytes.extend(i2c_read(
            &mut bus,
            160 * MILLISECOND,
            barometer,
            (BARO_ADDRESS, 0x03),
            3,
        ));
        bytes
    }

    /// What every chip on the board answers to a driver's reads.
    #[derive(Debug, PartialEq)]
    struct Frames {
        icm42688p: Vec<i32>,
        icm42605: Vec<i32>,
        compass: Vec<i32>,
        barometer: Vec<u8>,
    }

    impl Frames {
        /// Fails unless every chip answered with a sample, so two frames that agree can't both be a
        /// chip that never measured.
        fn sampled(self) -> Self {
            for unit in [&self.icm42688p, &self.icm42605] {
                assert!(
                    unit[1..7].iter().all(|&word| word != i32::from(i16::MIN)),
                    "{unit:?}"
                );
            }
            assert!(self.compass[0..3].iter().any(|&word| word != 0), "{self:?}");
            assert!(self.barometer.iter().any(|&byte| byte != 0), "{self:?}");
            self
        }
    }

    fn frames(board: &mut MatekH743) -> Frames {
        Frames {
            icm42688p: inertial_words(
                board.mcu.spi[IMU1_ON]
                    .chip_mut::<Icm42688p>(ICM42688P_PEER)
                    .unwrap(),
            ),
            icm42605: inertial_words(
                board.mcu.spi[IMU2_ON]
                    .chip_mut::<Icm42605>(ICM42605_PEER)
                    .unwrap(),
            ),
            compass: compass_words(
                board.mcu.i2c[COMPASS_ON]
                    .chip_mut::<Qmc5883l>(QMC5883L_PEER)
                    .unwrap(),
            ),
            barometer: barometer_bytes(
                board.mcu.i2c[BARO_ON]
                    .chip_mut::<Dps310>(DPS310_PEER)
                    .unwrap(),
            ),
        }
        .sampled()
    }

    /// What each chip is handed by hand: the rate and the force of both units, the field, the
    /// pressure, and the temperature, all on the chips' own axes.
    struct ByHand {
        icm42688p: ([i32; 3], [i32; 3]),
        icm42605: ([i32; 3], [i32; 3]),
        field: [i32; 3],
        pressure: u32,
        temperature: i32,
    }

    /// Chips of each kind given `handed` by hand, read the way the board's are.
    fn reference_frames(handed: &ByHand) -> Frames {
        let mut icm42688p = Icm42688p::new();
        icm42688p.set_rate(
            handed.icm42688p.0[0],
            handed.icm42688p.0[1],
            handed.icm42688p.0[2],
        );
        icm42688p.set_acceleration(
            handed.icm42688p.1[0],
            handed.icm42688p.1[1],
            handed.icm42688p.1[2],
        );
        icm42688p.set_temperature(handed.temperature);
        let mut icm42605 = Icm42605::new();
        icm42605.set_rate(
            handed.icm42605.0[0],
            handed.icm42605.0[1],
            handed.icm42605.0[2],
        );
        icm42605.set_acceleration(
            handed.icm42605.1[0],
            handed.icm42605.1[1],
            handed.icm42605.1[2],
        );
        icm42605.set_temperature(handed.temperature);
        let mut compass = Qmc5883l::new();
        compass.set_field(handed.field[0], handed.field[1], handed.field[2]);
        compass.set_temperature(handed.temperature);
        let mut barometer = Dps310::new(Sdo::Low);
        barometer.set_pressure(handed.pressure);
        barometer.set_temperature(handed.temperature);
        Frames {
            icm42688p: inertial_words(&mut icm42688p),
            icm42605: inertial_words(&mut icm42605),
            compass: compass_words(&mut compass),
            barometer: barometer_bytes(&mut barometer),
        }
        .sampled()
    }

    /// `signals` as the board hands them to its chips with nothing wrong with any.
    fn handed_clean(signals: &Signals) -> ByHand {
        ByHand {
            icm42688p: (
                behind_yaw_180(signals.angular_rate),
                behind_yaw_180(signals.specific_force),
            ),
            icm42605: (
                behind_yaw_270(signals.angular_rate),
                behind_yaw_270(signals.specific_force),
            ),
            field: behind_the_compass(signals.magnetic_field),
            pressure: signals.pressure,
            temperature: signals.temperature,
        }
    }

    fn put(board: &mut MatekH743, peripheral: &Peripheral, register: impl Layout, value: u64) {
        board
            .mcu
            .write(
                VirtualNanos(0),
                peripheral.base + u64::from(register.spec().offset),
                Width::W32,
                value,
            )
            .unwrap();
    }

    #[test]
    fn the_board_runs_one_cortex_m7_with_double_precision_and_sixteen_mpu_regions() {
        let board = MatekH743::new().unwrap();
        let config = board.config();
        assert_eq!(config.core.variant, armv7m::Variant::M7);
        assert_eq!(config.fpu, armv7m::Fpu::FpV5Dp);
        assert_eq!(config.mpu_regions, armv7m::MpuRegions::Sixteen);
    }

    #[test]
    fn the_declared_fields_walk_the_encoded_signals_one_by_one() {
        conformance::the_declared_fields_walk_the_encoded_signals_one_by_one::<MatekH743>();
    }

    #[test]
    fn the_declared_conditions_walk_the_encoded_conditions_one_by_one_and_rest_at_zero() {
        let conditions = Conditions {
            icm42688p_silent: true,
            icm42688p_rate: wrong(true, -1),
            icm42688p_acceleration: wrong(false, -4),
            icm42605_silent: false,
            icm42605_rate: wrong(true, -7),
            icm42605_acceleration: wrong(false, -10),
            dps310_silent: true,
            dps310_pressure: Condition {
                stuck: false,
                bias: [-13],
                noise: [13_001],
            },
            qmc5883l_silent: false,
            qmc5883l_field: wrong(true, -16),
            gps_silent: true,
            gps_noise_errors: 3_000_000_000,
            gps_framing_errors: 7,
        };
        conformance::the_declared_conditions_walk_the_encoded_conditions_one_by_one_and_rest_at_zero::<
            MatekH743,
        >(
            &conditions,
            &[
                1,
                1,
                -1,
                -2,
                -3,
                1_001,
                1_002,
                1_003,
                0,
                -4,
                -5,
                -6,
                4_001,
                4_002,
                4_003,
                0,
                1,
                -7,
                -8,
                -9,
                7_001,
                7_002,
                7_003,
                0,
                -10,
                -11,
                -12,
                10_001,
                10_002,
                10_003,
                1,
                0,
                -13,
                13_001,
                0,
                1,
                -16,
                -17,
                -18,
                16_001,
                16_002,
                16_003,
                1,
                3_000_000_000,
                7,
            ],
        );
    }

    #[test]
    fn the_edge_passes_the_links_own_check() {
        conformance::the_edge_passes_the_links_own_check(&mut MatekH743::new().unwrap());
    }

    /// The firmware reads `ROTATION_YAW_180` for the first unit, and applying that rotation to what
    /// the chip reports gives the body's axes back.
    #[test]
    fn the_icm42688p_is_handed_the_body_axes_turned_back_by_yaw_180() {
        let mut board = MatekH743::new().unwrap();
        board.sense(&BODY);
        let found = frames(&mut board).icm42688p;
        let mut by_hand = Icm42688p::new();
        by_hand.set_rate(-30_000, 50_000, 70_000);
        by_hand.set_acceleration(-1_250_000, 2_500_000, 750_000);
        by_hand.set_temperature(BODY.temperature);
        assert_eq!(found, inertial_words(&mut by_hand));
        near(
            ardupilot_yaw_180(triple(&found[1..4])),
            counts_of(BODY.specific_force, ACCEL_COUNTS_PER_MILLION),
            "the force after the firmware's rotation",
        );
        near(
            ardupilot_yaw_180(triple(&found[4..7])),
            counts_of(BODY.angular_rate, RATE_COUNTS_PER_MILLION),
            "the rate after the firmware's rotation",
        );
    }

    /// The firmware reads `ROTATION_YAW_270` for the second unit.
    #[test]
    fn the_icm42605_is_handed_the_body_axes_turned_back_by_yaw_270() {
        let mut board = MatekH743::new().unwrap();
        board.sense(&BODY);
        let found = frames(&mut board).icm42605;
        let mut by_hand = Icm42605::new();
        by_hand.set_rate(50_000, 30_000, 70_000);
        by_hand.set_acceleration(2_500_000, 1_250_000, 750_000);
        by_hand.set_temperature(BODY.temperature);
        assert_eq!(found, inertial_words(&mut by_hand));
        near(
            ardupilot_yaw_270(triple(&found[1..4])),
            counts_of(BODY.specific_force, ACCEL_COUNTS_PER_MILLION),
            "the force after the firmware's rotation",
        );
        near(
            ardupilot_yaw_270(triple(&found[4..7])),
            counts_of(BODY.angular_rate, RATE_COUNTS_PER_MILLION),
            "the rate after the firmware's rotation",
        );
    }

    /// The compass is handed `[y, -x, z]` of the body's field, which the driver's own arithmetic
    /// turns back into the body's field.
    #[test]
    fn the_qmc5883l_is_handed_the_body_axes_the_firmware_recovers() {
        let mut board = MatekH743::new().unwrap();
        board.sense(&BODY);
        let found = frames(&mut board).compass;
        let mut by_hand = Qmc5883l::new();
        by_hand.set_field(-20_000, -30_000, 45_000);
        by_hand.set_temperature(BODY.temperature);
        assert_eq!(found, compass_words(&mut by_hand));
        near(
            ardupilot_qmc5883l_driver(triple(&found[0..3])),
            counts_of(BODY.magnetic_field, FIELD_COUNTS_PER_MILLION),
            "the field after the firmware's driver",
        );
    }

    /// A different bias on each quantity a condition reaches lands on the chip it names and not on
    /// the chip of the same kind beside it, at once on what the board last sensed, and a stuck
    /// quantity keeps what it had with no bias while its sibling follows the next sense.
    #[test]
    fn each_chip_senses_through_its_own_conditions() {
        let biased = |bias: i32| Condition {
            bias: [bias, 2 * bias, 3 * bias],
            ..Condition::default()
        };
        let plus = |[x, y, z]: [i32; 3], bias: i32| [x + bias, y + 2 * bias, z + 3 * bias];
        let before = Signals {
            angular_rate: [20_000, -30_000, 40_000],
            specific_force: [500_000, -600_000, -700_000],
            magnetic_field: [30_000, -20_000, 45_000],
            pressure: 95_000,
            ..AT_REST
        };
        let after = Signals {
            specific_force: [100_000, 200_000, -900_000],
            ..before
        };
        for resensed in [false, true] {
            let mut board = MatekH743::new().unwrap();
            board.sense(&before);
            board.condition(&Conditions {
                icm42688p_rate: biased(1_000),
                icm42605_acceleration: Condition {
                    stuck: true,
                    ..biased(10_000)
                },
                qmc5883l_field: biased(4_000),
                dps310_pressure: Condition {
                    bias: [-500],
                    ..Condition::default()
                },
                ..Conditions::default()
            });
            let now = if resensed {
                board.sense(&after);
                &after
            } else {
                &before
            };
            let expected = ByHand {
                icm42688p: (
                    behind_yaw_180(plus(before.angular_rate, 1_000)),
                    behind_yaw_180(now.specific_force),
                ),
                icm42605: (
                    behind_yaw_270(before.angular_rate),
                    behind_yaw_270(before.specific_force),
                ),
                field: behind_the_compass(plus(before.magnetic_field, 4_000)),
                pressure: 94_500,
                temperature: before.temperature,
            };
            assert_eq!(
                frames(&mut board),
                reference_frames(&expected),
                "after another sense: {resensed}"
            );
        }
    }

    /// Noise lands on the chip and the axis it names, on that chip's own axis, and on no other chip.
    /// It is drawn for the `Advance` the link counts and the next `Advance` moves it with no input
    /// changed.
    #[test]
    fn each_chips_noise_is_its_own_and_moves_with_each_advance() {
        const SEED: u64 = 7;
        let noisy = [
            (ICM42688P_RATE_NOISE[0], 2_000),
            (ICM42605_ACCELERATION_NOISE[0], 30_000),
            (QMC5883L_FIELD_NOISE[0], 5_000),
            (DPS310_PRESSURE_NOISE[0], 50),
        ];
        for advances in 1..=2_u64 {
            let mut board = MatekH743::new().unwrap();
            let mut held = Held::at_rest(&board, SEED).unwrap();
            for advance in 0..advances {
                let mut quiet = Advance::new(VirtualNanos(0));
                if advance == 0 {
                    quiet.conditions = noisy
                        .iter()
                        .map(|&(name, deviation)| Set {
                            index: u16::try_from(
                                <MatekH743 as Edge>::CONDITIONS
                                    .iter()
                                    .position(|field| field.name == name)
                                    .unwrap(),
                            )
                            .unwrap(),
                            value: deviation,
                        })
                        .collect();
                }
                deliver(&mut board, &mut held, &[], &quiet, VirtualNanos(0)).unwrap();
            }
            let drawn = |(name, deviation): (&str, i64)| {
                let deviation = u32::try_from(deviation).unwrap();
                i32::try_from(normal(SEED, name, advances - 1, deviation)).unwrap()
            };
            assert_ne!(drawn(noisy[3]), 0, "the pressure's noise is there to see");
            assert_ne!(drawn(noisy[2]), 0, "the field's noise is there to see");
            let [x, y, z] = AT_REST.angular_rate;
            let rate = [x + drawn(noisy[0]), y, z];
            let [x, y, z] = AT_REST.specific_force;
            let force = [x + drawn(noisy[1]), y, z];
            let [x, y, z] = AT_REST.magnetic_field;
            let field = [x + drawn(noisy[2]), y, z];
            let expected = ByHand {
                icm42688p: (behind_yaw_180(rate), behind_yaw_180(AT_REST.specific_force)),
                icm42605: (behind_yaw_270(AT_REST.angular_rate), behind_yaw_270(force)),
                field: behind_the_compass(field),
                pressure: AT_REST.pressure.saturating_add_signed(drawn(noisy[3])),
                temperature: AT_REST.temperature,
            };
            assert_eq!(
                frames(&mut board),
                reference_frames(&expected),
                "after {advances} advances"
            );
        }
    }

    /// A board just built is a level vehicle at rest, and its chips start there.
    #[test]
    fn the_board_is_built_at_rest() {
        let mut board = MatekH743::new().unwrap();
        let found = frames(&mut board);
        assert_eq!(found, reference_frames(&handed_clean(&AT_REST)));
        for unit in [&found.icm42688p, &found.icm42605] {
            assert_eq!(
                unit[1..],
                [0, 0, -2048, 0, 0, 0],
                "a gravity's reaction against z and no turn"
            );
        }
        near(
            triple(&found.compass[0..3]),
            [0, -660, 1260],
            "22 000 nT north and 42 000 nT down through the mounting",
        );
        conformance::the_board_is_built_at_rest(&mut board);
    }

    /// Every chip a board lists has its own condition to silence it, and a place past the list is
    /// none. The barometer and the compass are silenced and conditioned and never named.
    #[test]
    fn each_chip_listed_has_a_silence_and_a_place() {
        assert_eq!(<MatekH743 as Edge>::CHIPS, ["icm42688p", "icm42605", "gps"]);
        conformance::each_chip_listed_has_a_silence_and_a_place(&mut MatekH743::new().unwrap());
        for silent in ["dps310.silent", "qmc5883l.silent"] {
            assert!(
                <MatekH743 as Edge>::CONDITIONS
                    .iter()
                    .any(|condition| condition.name == silent),
                "{silent} is a condition"
            );
        }
    }

    /// 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() {
        assert_eq!(usart::INSTANCES[GPS], "USART2");
        conformance::the_receiver_on_the_gps_port_reports_where_the_board_is(
            &mut MatekH743::new().unwrap(),
            |board| board.mcu.usart[GPS].peer_mut().expect("fit hangs it"),
        );
    }

    fn pulse_counts(pin: u64) -> u64 {
        1_000 + 50 * pin
    }

    fn pwm(mode: &FieldSpec, preload: &FieldSpec) -> u64 {
        mode.set(0, PWM_MODE_1) | preload.mask()
    }

    /// TIM4 or TIM5 counting microseconds with all four channels as PWM from `first_pin`, started.
    fn run_general(board: &mut MatekH743, timer: &Peripheral, hz: u64, first_pin: u64) {
        put(board, timer, tim2::Register::Psc, hz / 1_000_000 - 1);
        put(board, timer, tim2::Register::Arr, PWM_PERIOD_COUNTS - 1);
        for (register, pin) in [
            (tim2::Register::Ccr1, first_pin),
            (tim2::Register::Ccr2, first_pin + 1),
            (tim2::Register::Ccr3, first_pin + 2),
            (tim2::Register::Ccr4, first_pin + 3),
        ] {
            put(board, timer, register, pulse_counts(pin));
        }
        put(
            board,
            timer,
            tim2::Register::Ccmr1Output,
            pwm(tim2::ccmr1_output::OC1M, tim2::ccmr1_output::OC1PE)
                | pwm(tim2::ccmr1_output::OC2M, tim2::ccmr1_output::OC2PE),
        );
        put(
            board,
            timer,
            tim2::Register::Ccmr2Output,
            pwm(tim2::ccmr2_output::OC3M, tim2::ccmr2_output::OC3PE)
                | pwm(tim2::ccmr2_output::OC4M, tim2::ccmr2_output::OC4PE),
        );
        put(
            board,
            timer,
            tim2::Register::Ccer,
            tim2::ccer::CC1E.mask()
                | tim2::ccer::CC2E.mask()
                | tim2::ccer::CC3E.mask()
                | tim2::ccer::CC4E.mask(),
        );
        put(board, timer, tim2::Register::Egr, tim2::egr::UG.mask());
        put(board, timer, tim2::Register::Cr1, tim2::cr1::CEN.mask());
    }

    /// TIM15 with both channels as PWM on pins 11 and 12 and `MOE` set, started.
    fn run_tim15(board: &mut MatekH743, hz: u64) {
        put(board, &TIM15, tim15::Register::Psc, hz / 1_000_000 - 1);
        put(board, &TIM15, tim15::Register::Arr, PWM_PERIOD_COUNTS - 1);
        put(board, &TIM15, tim15::Register::Ccr1, pulse_counts(11));
        put(board, &TIM15, tim15::Register::Ccr2, pulse_counts(12));
        put(
            board,
            &TIM15,
            tim15::Register::Ccmr1Output,
            pwm(tim15::ccmr1_output::OC1M, tim15::ccmr1_output::OC1PE)
                | pwm(tim15::ccmr1_output::OC2M, tim15::ccmr1_output::OC2PE),
        );
        put(
            board,
            &TIM15,
            tim15::Register::Ccer,
            tim15::ccer::CC1E.mask() | tim15::ccer::CC2E.mask(),
        );
        put(
            board,
            &TIM15,
            tim15::Register::Bdtr,
            tim15::bdtr::MOE.mask(),
        );
        put(board, &TIM15, tim15::Register::Egr, tim15::egr::UG.mask());
        put(board, &TIM15, tim15::Register::Cr1, tim15::cr1::CEN.mask());
    }

    /// TIM1 with channel 1 as PWM on pin 13 and `MOE` set, started.
    fn run_tim1(board: &mut MatekH743, hz: u64) {
        put(board, &TIM1, tim1::Register::Psc, hz / 1_000_000 - 1);
        put(board, &TIM1, tim1::Register::Arr, PWM_PERIOD_COUNTS - 1);
        put(board, &TIM1, tim1::Register::Ccr1, pulse_counts(13));
        put(
            board,
            &TIM1,
            tim1::Register::Ccmr1Output,
            pwm(tim1::ccmr1_output::OC1M, tim1::ccmr1_output::OC1PE),
        );
        put(board, &TIM1, tim1::Register::Ccer, tim1::ccer::CC1E.mask());
        put(board, &TIM1, tim1::Register::Bdtr, tim1::bdtr::MOE.mask());
        put(board, &TIM1, tim1::Register::Egr, tim1::egr::UG.mask());
        put(board, &TIM1, tim1::Register::Cr1, tim1::cr1::CEN.mask());
    }

    /// TIM8 with the complementary outputs of channels 2 and 3 as PWM on pins 1 and 2, started and
    /// leaving `MOE` clear.
    fn run_tim8(board: &mut MatekH743, hz: u64) {
        put(board, &TIM8, tim1::Register::Psc, hz / 1_000_000 - 1);
        put(board, &TIM8, tim1::Register::Arr, PWM_PERIOD_COUNTS - 1);
        put(board, &TIM8, tim1::Register::Ccr2, pulse_counts(1));
        put(board, &TIM8, tim1::Register::Ccr3, pulse_counts(2));
        put(
            board,
            &TIM8,
            tim1::Register::Ccmr1Output,
            pwm(tim1::ccmr1_output::OC2M, tim1::ccmr1_output::OC2PE),
        );
        put(
            board,
            &TIM8,
            tim1::Register::Ccmr2Output,
            pwm(tim1::ccmr2_output::OC3M, tim1::ccmr2_output::OC3PE),
        );
        put(
            board,
            &TIM8,
            tim1::Register::Ccer,
            tim1::ccer::CC2NE.mask() | tim1::ccer::CC3NE.mask(),
        );
        put(board, &TIM8, tim1::Register::Egr, tim1::egr::UG.mask());
        put(board, &TIM8, tim1::Register::Cr1, tim1::cr1::CEN.mask());
    }

    /// The names the outputs' fields carry, in the order the description numbers the pins.
    #[test]
    fn the_output_fields_name_the_thirteen_pins_in_order() {
        let named: Vec<String> = (1..=13)
            .flat_map(|pin| ["width", "period", "command"].map(|part| format!("PWM{pin}.{part}")))
            .collect();
        let fields: Vec<&str> = <MatekH743 as Edge>::OUTPUT_FIELDS
            .iter()
            .map(|field| field.name.as_ref())
            .collect();
        assert_eq!(fields, named);
        assert_eq!(
            Outputs::IDLE.0.map(|actuator| actuator.name),
            [
                "PWM1", "PWM2", "PWM3", "PWM4", "PWM5", "PWM6", "PWM7", "PWM8", "PWM9", "PWM10",
                "PWM11", "PWM12", "PWM13"
            ]
        );
    }

    /// The description's thirteen `PWM` pins, `PWM(1)` to `PWM(13)` of `hwdef.dat` lines 145 to 157,
    /// each read off the timer and the channel it is on, with the command it makes on the speed
    /// controllers' curve. TIM8's two are the complementary outputs `CH2N` and `CH3N`, which
    /// RM0433 rev 9 section 38.3.15 drives only with `MOE` set in `BDTR`, and every pin nothing
    /// drives reads as none.
    #[test]
    fn the_outputs_are_the_description_s_thirteen_pwm_pins_read_off_their_timers() {
        let mut board = MatekH743::new().unwrap();
        assert_eq!(
            board.drive(),
            Outputs::IDLE,
            "nothing drives a pin before the firmware"
        );
        let (clocks, registers) = board.mcu.clocks();
        let apb1 = clocks.timer_clock(registers, TimerBus::Apb1);
        let apb2 = clocks.timer_clock(registers, TimerBus::Apb2);
        assert!(apb1 % 1_000_000 == 0 && apb2 % 1_000_000 == 0);
        put(
            &mut board,
            &RCC,
            rcc::Register::Apb1lenr,
            rcc::apb1lenr::TIM4EN.mask() | rcc::apb1lenr::TIM5EN.mask(),
        );
        put(
            &mut board,
            &RCC,
            rcc::Register::Apb2enr,
            rcc::apb2enr::TIM1EN.mask()
                | rcc::apb2enr::TIM8EN.mask()
                | rcc::apb2enr::TIM15EN.mask(),
        );
        run_general(&mut board, &TIM5, apb1, 3);
        run_general(&mut board, &TIM4, apb1, 7);
        run_tim15(&mut board, apb2);
        run_tim1(&mut board, apb2);
        run_tim8(&mut board, apb2);
        let driving = |pin: u64| Actuator {
            name: Outputs::IDLE.0[usize::try_from(pin).unwrap() - 1].name,
            pulse: Some(Pulse {
                width: VirtualNanos(pulse_counts(pin) * MICROSECOND),
                period: VirtualNanos(PWM_PERIOD_COUNTS * MICROSECOND),
            }),
            command: Some(u32::try_from(50 * pin).unwrap()),
        };
        let mut expected = flight::Outputs(std::array::from_fn(|index| {
            driving(u64::try_from(index).unwrap() + 1)
        }));
        expected.0[0] = Outputs::IDLE.0[0];
        expected.0[1] = Outputs::IDLE.0[1];
        assert_eq!(
            board.drive(),
            expected,
            "TIM8's complementary pins are held low until MOE"
        );
        put(
            &mut board,
            &TIM8,
            tim1::Register::Bdtr,
            tim1::bdtr::MOE.mask(),
        );
        let outputs = board.drive();
        expected.0[0] = driving(1);
        expected.0[1] = driving(2);
        assert_eq!(outputs, expected);
        let mut bytes = Vec::new();
        outputs.encode(&mut bytes);
        let values = values_of(<MatekH743 as Edge>::OUTPUT_FIELDS, &bytes).unwrap();
        let on_the_wire: Vec<i64> = (1..=13)
            .flat_map(|pin| {
                [
                    i64::try_from(pulse_counts(pin) * MICROSECOND).unwrap(),
                    i64::try_from(PWM_PERIOD_COUNTS * MICROSECOND).unwrap(),
                    i64::try_from(50 * pin).unwrap(),
                ]
            })
            .collect();
        assert_eq!(values, on_the_wire);
        assert_eq!(
            Outputs::decode(&mut bytes.as_slice()).unwrap(),
            outputs,
            "an output with no period comes back with no pulse and no command"
        );
    }
}