rigless 0.1.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
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
// 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, the rail its
//! regulator sees, and the chips `fit` wires to it: the two inertial units and the compass on the
//! first serial interface, the barometer and the parameter memory on the second, the GPS receiver
//! on `UART4`, the card in the slot, and the 5 V sense on the first converter, which carries the
//! battery's two senses as well.
//!
//! The board **has** these things. They're 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's 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's wired to (`mcu.spi[0].attach_selected(..)`), because that's where the
//! wires are and where a transfer has to reach it synchronously.
//! Holding it in a board field instead would mean the controller couldn't 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 board's [`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. Each crosses the link as three
//! fields, its pulse's width and period in nanoseconds and its command in thousandths of the whole. 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::memory_card::MemoryCard;
use crate::chip::mpu9250::Mpu9250;
use crate::chip::ms5611::Ms5611;
use crate::chip::nmea::{self, Position};
use crate::chip::{Placed, uart};
use crate::device::Level;
use crate::edge::{Condition, Coupled, Edge, Field, Pulse, Sensed, flag};
use crate::emulator::InterruptLine;
use crate::machine::armv7m;
use crate::machine::{Board, Crystal, HostWire, Supply, Target};
use crate::snapshot::store;
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;
/// The core is a Cortex-M4, RM0090 rev 22 section 1. The part has the bit-band regions an M4 is
/// given, and an access at an alias reaches the bus at the instruction's own size, PM0214 rev 10
/// section 2.2.5.
const VARIANT: armv7m::Variant = armv7m::Variant::M4;
/// The core is a Cortex-M4 with FPU, RM0090 rev 22 section 1, and the unit is single precision,
/// DS9405 rev 13 section 2, so FPv4-SP.
const FPU: armv7m::Fpu = armv7m::Fpu::FpV4Sp;
/// The part has an MPU, DS9405 rev 13 section 2, and it has eight regions, PM0214 rev 10 sections
/// 4.2 and 4.2.5.
const MPU_REGIONS: armv7m::MpuRegions = armv7m::MpuRegions::Eight;
/// 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";
/// The core retires 250 million instructions a second, four nanoseconds each. That's the rate every
/// target here runs at, rather than the part's 168 MHz, and every recorded run and trace was made at
/// it.
const INSTRUCTIONS_PER_SECOND: NonZeroU64 = NonZeroU64::new(250_000_000).expect("a running core");
/// 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: Select = low("GPIOD", 10);
/// The barometer shares that interface, `SPIDEV ms5611_int SPI2`, behind `PD7 BARO_CS`, selected low.
const BARO_CS: Select = low("GPIOD", 7);
/// 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: Select = low("GPIOC", 2);
const SECOND_IMU_CS: Select = low("GPIOC", 15);
/// The magnetometer shares that interface, `SPIDEV lis3mdl SPI1`, behind `PE15 MAG_CS`, selected low.
const MAG_CS: Select = low("GPIOE", 15);

/// A select on `pin` of `port`, selected low.
const fn low(port: &'static str, pin: u8) -> Select {
    Select {
        port,
        pin: Pin::new(pin).expect("a port has sixteen pins"),
        active: Level::Low,
    }
}
/// 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,
};
/// The names each chip's noise on each quantity crosses the link as, which key its draws too.
const ICM20608_RATE_NOISE: [&str; 3] = [
    "icm20608.rate.noise.x",
    "icm20608.rate.noise.y",
    "icm20608.rate.noise.z",
];
const ICM20608_ACCELERATION_NOISE: [&str; 3] = [
    "icm20608.acceleration.noise.x",
    "icm20608.acceleration.noise.y",
    "icm20608.acceleration.noise.z",
];
const MPU9250_RATE_NOISE: [&str; 3] = [
    "mpu9250.rate.noise.x",
    "mpu9250.rate.noise.y",
    "mpu9250.rate.noise.z",
];
const MPU9250_ACCELERATION_NOISE: [&str; 3] = [
    "mpu9250.acceleration.noise.x",
    "mpu9250.acceleration.noise.y",
    "mpu9250.acceleration.noise.z",
];
const MPU9250_FIELD_NOISE: [&str; 3] = [
    "mpu9250.field.noise.x",
    "mpu9250.field.noise.y",
    "mpu9250.field.noise.z",
];
const LIS3MDL_FIELD_NOISE: [&str; 3] = [
    "lis3mdl.field.noise.x",
    "lis3mdl.field.noise.y",
    "lis3mdl.field.noise.z",
];
const MS5611_PRESSURE_NOISE: [&str; 1] = ["ms5611.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";
/// Where each chip stands among its interface's peers, in the order `fit` hangs them.
const FM25V02_PEER: usize = 0;
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"),
    }
}

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

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

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

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

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

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

/// What the firmware drives on the board: the description's `PWM(1)` to `PWM(6)`, in that order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Outputs(pub [Actuator; 6]);

/// Every output with nothing on its pin, which is how the board is built.
const IDLE: Outputs = Outputs([
    Actuator::idle(MAIN_OUTPUTS[0].0),
    Actuator::idle(MAIN_OUTPUTS[1].0),
    Actuator::idle(MAIN_OUTPUTS[2].0),
    Actuator::idle(MAIN_OUTPUTS[3].0),
    Actuator::idle(AUXILIARY_OUTPUTS[0].0),
    Actuator::idle(AUXILIARY_OUTPUTS[1].0),
]);

/// 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, serde::Serialize, serde::Deserialize,
)]
pub struct Signals {
    /// The angular rate about each body axis, in thousandths of a degree per second.
    pub angular_rate: [i32; 3],
    /// The specific force along each body axis, in millionths of a gravity.
    pub specific_force: [i32; 3],
    /// The magnetic field along each body axis, in nanotesla.
    pub magnetic_field: [i32; 3],
    /// The static pressure, in pascals.
    pub pressure: u32,
    /// The temperature the board sits at, in hundredths of a degree Celsius.
    pub temperature: i32,
    /// The voltage of the pack the board is powered from, in millivolts.
    pub battery_voltage: u32,
    /// The current the pack is delivering, in milliamps, and negative while it charges.
    pub battery_current: i32,
    /// Where the board is.
    pub position: Position,
    /// How fast the board moves, north, east and down, in 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, and the field of a mid-latitude northern site, north and down. The air is sea
/// level at twenty degrees. The board is at the geographic 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],
};

/// 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 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-20608-G, the firmware's first inertial unit.
    pub icm20608_silent: bool,
    /// What it senses of the angular rate.
    pub icm20608_rate: Condition<3>,
    /// What it senses of the specific force.
    pub icm20608_acceleration: Condition<3>,
    /// The MPU-9250, the second, with the compass die inside it.
    pub mpu9250_silent: bool,
    /// What it senses of the angular rate.
    pub mpu9250_rate: Condition<3>,
    /// What it senses of the specific force.
    pub mpu9250_acceleration: Condition<3>,
    /// What its compass die senses of the field.
    pub mpu9250_field: Condition<3>,
    /// The LIS3MDL compass.
    pub lis3mdl_silent: bool,
    /// What it senses of the field.
    pub lis3mdl_field: Condition<3>,
    /// The MS5611 barometer.
    pub ms5611_silent: bool,
    /// What it senses of the pressure.
    pub ms5611_pressure: Condition<1>,
    /// The parameter memory.
    pub fm25v02_silent: bool,
    /// 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,
    /// The card in the slot.
    pub card_silent: bool,
}

/// What each chip was last handed of each quantity a condition reaches.
#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
struct Handed {
    icm20608_rate: Sensed<i32, 3>,
    icm20608_acceleration: Sensed<i32, 3>,
    mpu9250_rate: Sensed<i32, 3>,
    mpu9250_acceleration: Sensed<i32, 3>,
    mpu9250_field: Sensed<i32, 3>,
    lis3mdl_field: Sensed<i32, 3>,
    ms5611_pressure: Sensed<u32, 1>,
}

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,
    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 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),
            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 wire on the schematic.
    fn fit(&mut self) {
        self.mcu.rcc.attach_crystals(self.hse.0, self.lse.0);
        let rail = self.rail.0;
        self.mcu.set_supply(rail);
        // `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(), FRAM_CS);
        self.mcu.spi[FRAM_ON].attach_selected(Ms5611::new(), BARO_CS);
        self.mcu.spi[IMU_ON].attach_selected(Mpu9250::new(), IMU_CS);
        self.mcu.spi[IMU_ON].attach_selected(Icm20608::new(), SECOND_IMU_CS);
        self.mcu.spi[IMU_ON].attach_selected(Lis3mdl::new(), MAG_CS);
        self.mcu.sdio.attach(MemoryCard::formatted(CARD_BLOCKS));
    }
}

store!(Pixracer {
    values: [conditions, handed, sensed],
    parts: [mcu],
    built: [hse, lse, rail],
});

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 core = armv7m::Core {
            variant: VARIANT,
            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,
            instructions_per_second: INSTRUCTIONS_PER_SECOND,
            boot: BOOT,
        }
        .spec_with_parts(
            &crate::cpu::armv7m::windows(crate::mcu::Mcu::bus(&self.mcu)),
            FPU,
            MPU_REGIONS,
        );
        vec![Target {
            name: MCU,
            mcu: &mut self.mcu,
            core,
            interrupt_line: InterruptLine::new,
        }]
    }

    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 Pixracer {
    type Signals = Signals;

    type Outputs = Outputs;

    type Conditions = Conditions;

    /// Each output's pulse width and period in nanoseconds, zero while nothing drives it, then what the
    /// pulse commands in thousandths of the whole, zero with no pulse.
    const OUTPUT_FIELDS: &'static [Field] = &[
        Field::new("PWM1.width", "ns", 8, false),
        Field::new("PWM1.period", "ns", 8, false),
        Field::new("PWM1.command", "1e-3", 4, false),
        Field::new("PWM2.width", "ns", 8, false),
        Field::new("PWM2.period", "ns", 8, false),
        Field::new("PWM2.command", "1e-3", 4, false),
        Field::new("PWM3.width", "ns", 8, false),
        Field::new("PWM3.period", "ns", 8, false),
        Field::new("PWM3.command", "1e-3", 4, false),
        Field::new("PWM4.width", "ns", 8, false),
        Field::new("PWM4.period", "ns", 8, false),
        Field::new("PWM4.command", "1e-3", 4, false),
        Field::new("PWM5.width", "ns", 8, false),
        Field::new("PWM5.period", "ns", 8, false),
        Field::new("PWM5.command", "1e-3", 4, false),
        Field::new("PWM6.width", "ns", 8, false),
        Field::new("PWM6.period", "ns", 8, false),
        Field::new("PWM6.command", "1e-3", 4, false),
    ];

    const FIELDS: &'static [Field] = &[
        Field::new("angular_rate.x", "mdeg/s", 4, true),
        Field::new("angular_rate.y", "mdeg/s", 4, true),
        Field::new("angular_rate.z", "mdeg/s", 4, true),
        Field::new("specific_force.x", "1e-6 g", 4, true),
        Field::new("specific_force.y", "1e-6 g", 4, true),
        Field::new("specific_force.z", "1e-6 g", 4, true),
        Field::new("magnetic_field.x", "nT", 4, true),
        Field::new("magnetic_field.y", "nT", 4, true),
        Field::new("magnetic_field.z", "nT", 4, true),
        Field::new("pressure", "Pa", 4, false),
        Field::new("temperature", "0.01 degC", 4, true),
        Field::new("battery_voltage", "mV", 4, false),
        Field::new("battery_current", "mA", 4, true),
        Field::new("position.latitude", "1e-7 deg", 4, true),
        Field::new("position.longitude", "1e-7 deg", 4, true),
        Field::new("position.altitude", "mm", 4, true),
        Field::new("velocity.north", "mm/s", 4, true),
        Field::new("velocity.east", "mm/s", 4, true),
        Field::new("velocity.down", "mm/s", 4, true),
    ];

    /// 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. Noise under a chip's count mostly vanishes as the chip
    /// converts: the inertial units count 61 mdeg/s and 488 µg at their widest ranges, the compass
    /// die about 180 nT once its adjustment is taken out, and the LIS3MDL about 15 nT at its
    /// narrowest. The barometer is handed whole pascals. A serial port's errors are words in a
    /// million.
    const CONDITIONS: &'static [Field] = &[
        Field::new("icm20608.silent", "flag", 1, false),
        Field::new("icm20608.rate.stuck", "flag", 1, false),
        Field::new("icm20608.rate.bias.x", "mdeg/s", 4, true),
        Field::new("icm20608.rate.bias.y", "mdeg/s", 4, true),
        Field::new("icm20608.rate.bias.z", "mdeg/s", 4, true),
        Field::new(ICM20608_RATE_NOISE[0], "mdeg/s", 4, false),
        Field::new(ICM20608_RATE_NOISE[1], "mdeg/s", 4, false),
        Field::new(ICM20608_RATE_NOISE[2], "mdeg/s", 4, false),
        Field::new("icm20608.acceleration.stuck", "flag", 1, false),
        Field::new("icm20608.acceleration.bias.x", "1e-6 g", 4, true),
        Field::new("icm20608.acceleration.bias.y", "1e-6 g", 4, true),
        Field::new("icm20608.acceleration.bias.z", "1e-6 g", 4, true),
        Field::new(ICM20608_ACCELERATION_NOISE[0], "1e-6 g", 4, false),
        Field::new(ICM20608_ACCELERATION_NOISE[1], "1e-6 g", 4, false),
        Field::new(ICM20608_ACCELERATION_NOISE[2], "1e-6 g", 4, false),
        Field::new("mpu9250.silent", "flag", 1, false),
        Field::new("mpu9250.rate.stuck", "flag", 1, false),
        Field::new("mpu9250.rate.bias.x", "mdeg/s", 4, true),
        Field::new("mpu9250.rate.bias.y", "mdeg/s", 4, true),
        Field::new("mpu9250.rate.bias.z", "mdeg/s", 4, true),
        Field::new(MPU9250_RATE_NOISE[0], "mdeg/s", 4, false),
        Field::new(MPU9250_RATE_NOISE[1], "mdeg/s", 4, false),
        Field::new(MPU9250_RATE_NOISE[2], "mdeg/s", 4, false),
        Field::new("mpu9250.acceleration.stuck", "flag", 1, false),
        Field::new("mpu9250.acceleration.bias.x", "1e-6 g", 4, true),
        Field::new("mpu9250.acceleration.bias.y", "1e-6 g", 4, true),
        Field::new("mpu9250.acceleration.bias.z", "1e-6 g", 4, true),
        Field::new(MPU9250_ACCELERATION_NOISE[0], "1e-6 g", 4, false),
        Field::new(MPU9250_ACCELERATION_NOISE[1], "1e-6 g", 4, false),
        Field::new(MPU9250_ACCELERATION_NOISE[2], "1e-6 g", 4, false),
        Field::new("mpu9250.field.stuck", "flag", 1, false),
        Field::new("mpu9250.field.bias.x", "nT", 4, true),
        Field::new("mpu9250.field.bias.y", "nT", 4, true),
        Field::new("mpu9250.field.bias.z", "nT", 4, true),
        Field::new(MPU9250_FIELD_NOISE[0], "nT", 4, false),
        Field::new(MPU9250_FIELD_NOISE[1], "nT", 4, false),
        Field::new(MPU9250_FIELD_NOISE[2], "nT", 4, false),
        Field::new("lis3mdl.silent", "flag", 1, false),
        Field::new("lis3mdl.field.stuck", "flag", 1, false),
        Field::new("lis3mdl.field.bias.x", "nT", 4, true),
        Field::new("lis3mdl.field.bias.y", "nT", 4, true),
        Field::new("lis3mdl.field.bias.z", "nT", 4, true),
        Field::new(LIS3MDL_FIELD_NOISE[0], "nT", 4, false),
        Field::new(LIS3MDL_FIELD_NOISE[1], "nT", 4, false),
        Field::new(LIS3MDL_FIELD_NOISE[2], "nT", 4, false),
        Field::new("ms5611.silent", "flag", 1, false),
        Field::new("ms5611.pressure.stuck", "flag", 1, false),
        Field::new("ms5611.pressure.bias", "Pa", 4, true),
        Field::new(MS5611_PRESSURE_NOISE[0], "Pa", 4, false),
        Field::new("fm25v02.silent", "flag", 1, 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),
        Field::new("card.silent", "flag", 1, false),
    ];

    const REST: Signals = AT_REST;

    /// Every chip a trigger or a one-shot fault can name, by the name its conditions start with.
    const CHIPS: &'static [&'static str] = &[
        "icm20608", "mpu9250", "lis3mdl", "ms5611", "fm25v02", "gps", "card",
    ];

    /// 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)? {
            "icm20608" => self.mcu.spi[IMU_ON].place_mut(ICM20608_PEER),
            "mpu9250" => self.mcu.spi[IMU_ON].place_mut(MPU9250_PEER),
            "lis3mdl" => self.mcu.spi[IMU_ON].place_mut(LIS3MDL_PEER),
            "ms5611" => self.mcu.spi[FRAM_ON].place_mut(MS5611_PEER),
            "fm25v02" => self.mcu.spi[FRAM_ON].place_mut(FM25V02_PEER),
            "gps" => self.mcu.usart[GPS].place_mut(),
            "card" => self.mcu.sdio.place_mut(),
            _ => None,
        }
    }

    /// 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.
    ///
    /// Each chip senses through its own conditions, so one unit can read wrong while the other reads
    /// the truth.
    fn sense(&mut self, signals: &Signals) {
        self.sensed = *signals;
        let (conditions, handed) = (&self.conditions, &mut self.handed);
        let imus = &mut self.mcu.spi[IMU_ON];
        let unit: &mut Mpu9250 = imus.chip_mut(MPU9250_PEER).expect("fit hangs it");
        let [x, y, z] = handed
            .mpu9250_rate
            .hand(signals.angular_rate, &conditions.mpu9250_rate);
        unit.set_rate(x, y, z);
        let [x, y, z] = handed
            .mpu9250_acceleration
            .hand(signals.specific_force, &conditions.mpu9250_acceleration);
        unit.set_acceleration(x, y, z);
        unit.set_temperature(signals.temperature);
        let [x, y, z] = handed
            .mpu9250_field
            .hand(signals.magnetic_field, &conditions.mpu9250_field);
        unit.set_field(x, y, z);
        let unit: &mut Icm20608 = imus.chip_mut(ICM20608_PEER).expect("fit hangs it");
        let [x, y, z] = handed
            .icm20608_rate
            .hand(signals.angular_rate, &conditions.icm20608_rate);
        unit.set_rate(x, y, z);
        let [x, y, z] = handed
            .icm20608_acceleration
            .hand(signals.specific_force, &conditions.icm20608_acceleration);
        unit.set_acceleration(x, y, z);
        unit.set_temperature(signals.temperature);
        let compass: &mut Lis3mdl = imus.chip_mut(LIS3MDL_PEER).expect("fit hangs it");
        let [x, y, z] = handed
            .lis3mdl_field
            .hand(signals.magnetic_field, &conditions.lis3mdl_field);
        compass.set_field(x, y, z);
        compass.set_temperature(signals.temperature);
        let barometer: &mut Ms5611 = self.mcu.spi[FRAM_ON]
            .chip_mut(MS5611_PEER)
            .expect("fit hangs it");
        let [pressure] = handed
            .ms5611_pressure
            .hand([signals.pressure], &conditions.ms5611_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 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,
        );
    }

    /// 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 imus = &mut self.mcu.spi[IMU_ON];
        let mut fitted = imus.silence(ICM20608_PEER, conditions.icm20608_silent)
            & imus.silence(MPU9250_PEER, conditions.mpu9250_silent)
            & imus.silence(LIS3MDL_PEER, conditions.lis3mdl_silent);
        let bus = &mut self.mcu.spi[FRAM_ON];
        fitted &= bus.silence(FM25V02_PEER, conditions.fm25v02_silent)
            & bus.silence(MS5611_PEER, conditions.ms5611_silent);
        fitted &= self.mcu.usart[GPS].silence(conditions.gps_silent)
            & self.mcu.sdio.silence(conditions.card_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
                .icm20608_rate
                .draw(&conditions.icm20608_rate, &ICM20608_RATE_NOISE, seed, index),
            handed.icm20608_acceleration.draw(
                &conditions.icm20608_acceleration,
                &ICM20608_ACCELERATION_NOISE,
                seed,
                index,
            ),
            handed
                .mpu9250_rate
                .draw(&conditions.mpu9250_rate, &MPU9250_RATE_NOISE, seed, index),
            handed.mpu9250_acceleration.draw(
                &conditions.mpu9250_acceleration,
                &MPU9250_ACCELERATION_NOISE,
                seed,
                index,
            ),
            handed
                .mpu9250_field
                .draw(&conditions.mpu9250_field, &MPU9250_FIELD_NOISE, seed, index),
            handed
                .lis3mdl_field
                .draw(&conditions.lis3mdl_field, &LIS3MDL_FIELD_NOISE, seed, index),
            handed.ms5611_pressure.draw(
                &conditions.ms5611_pressure,
                &MS5611_PRESSURE_NOISE,
                seed,
                index,
            ),
        ];
        if moved.contains(&true) {
            let sensed = self.sensed;
            self.sense(&sensed);
        }
    }

    fn drive(&mut self) -> Outputs {
        let (main, registers) = self.mcu.advanced_timer(MAIN_TIMER);
        let [one, two, three, four] = MAIN_OUTPUTS.map(|(name, channel)| {
            Actuator::on(name, main.pulse(channel, registers), SPEED_CONTROLLER)
        });
        let (auxiliary, registers) = self.mcu.timer(AUXILIARY_TIMER);
        let [five, six] = AUXILIARY_OUTPUTS.map(|(name, channel)| {
            Actuator::on(name, auxiliary.pulse(channel, registers), SPEED_CONTROLLER)
        });
        Outputs([one, two, three, four, five, six])
    }
}

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

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

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

impl crate::link::Wire for Conditions {
    fn encode(&self, out: &mut Vec<u8>) {
        self.icm20608_silent.encode(out);
        self.icm20608_rate.encode(out);
        self.icm20608_acceleration.encode(out);
        self.mpu9250_silent.encode(out);
        self.mpu9250_rate.encode(out);
        self.mpu9250_acceleration.encode(out);
        self.mpu9250_field.encode(out);
        self.lis3mdl_silent.encode(out);
        self.lis3mdl_field.encode(out);
        self.ms5611_silent.encode(out);
        self.ms5611_pressure.encode(out);
        self.fm25v02_silent.encode(out);
        self.gps_silent.encode(out);
        self.gps_noise_errors.encode(out);
        self.gps_framing_errors.encode(out);
        self.card_silent.encode(out);
    }

    fn decode(bytes: &mut &[u8]) -> Result<Self, crate::link::WireError> {
        Ok(Self {
            icm20608_silent: flag(bytes)?,
            icm20608_rate: crate::link::Wire::decode(bytes)?,
            icm20608_acceleration: crate::link::Wire::decode(bytes)?,
            mpu9250_silent: flag(bytes)?,
            mpu9250_rate: crate::link::Wire::decode(bytes)?,
            mpu9250_acceleration: crate::link::Wire::decode(bytes)?,
            mpu9250_field: crate::link::Wire::decode(bytes)?,
            lis3mdl_silent: flag(bytes)?,
            lis3mdl_field: crate::link::Wire::decode(bytes)?,
            ms5611_silent: flag(bytes)?,
            ms5611_pressure: crate::link::Wire::decode(bytes)?,
            fm25v02_silent: flag(bytes)?,
            gps_silent: flag(bytes)?,
            gps_noise_errors: crate::link::Wire::decode(bytes)?,
            gps_framing_errors: crate::link::Wire::decode(bytes)?,
            card_silent: flag(bytes)?,
        })
    }
}

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::normal;
    use crate::link::{
        Advance, Held, LinkError, Set, Wire, attach_engine_ports, deliver, sent, values_of,
    };
    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])]
    }

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

    #[test]
    fn the_declared_conditions_walk_the_encoded_conditions_one_by_one_and_rest_at_zero() {
        let mut bytes = Vec::new();
        Conditions::default().encode(&mut bytes);
        assert!(
            values_of(<Pixracer as Edge>::CONDITIONS, &bytes)
                .unwrap()
                .iter()
                .all(|&value| value == 0),
            "the board as built crosses as zeros"
        );
        let wrong = |stuck, bias: i32| Condition {
            stuck,
            bias: [bias, bias - 1, bias - 2],
            noise: [1, 2, 3].map(|axis| bias.unsigned_abs() * 1_000 + axis),
        };
        let conditions = Conditions {
            icm20608_silent: true,
            icm20608_rate: wrong(true, -1),
            icm20608_acceleration: wrong(false, -4),
            mpu9250_silent: true,
            mpu9250_rate: wrong(true, -7),
            mpu9250_acceleration: wrong(false, -10),
            mpu9250_field: wrong(true, -13),
            lis3mdl_silent: false,
            lis3mdl_field: wrong(true, -16),
            ms5611_silent: true,
            ms5611_pressure: Condition {
                stuck: false,
                bias: [-19],
                noise: [19_001],
            },
            fm25v02_silent: true,
            gps_silent: false,
            gps_noise_errors: 3_000_000_000,
            gps_framing_errors: 7,
            card_silent: true,
        };
        let mut bytes = Vec::new();
        conditions.encode(&mut bytes);
        assert_eq!(
            values_of(<Pixracer as Edge>::CONDITIONS, &bytes).unwrap(),
            [
                1,
                1,
                -1,
                -2,
                -3,
                1_001,
                1_002,
                1_003,
                0,
                -4,
                -5,
                -6,
                4_001,
                4_002,
                4_003,
                1,
                1,
                -7,
                -8,
                -9,
                7_001,
                7_002,
                7_003,
                0,
                -10,
                -11,
                -12,
                10_001,
                10_002,
                10_003,
                1,
                -13,
                -14,
                -15,
                13_001,
                13_002,
                13_003,
                0,
                1,
                -16,
                -17,
                -18,
                16_001,
                16_002,
                16_003,
                1,
                0,
                -19,
                19_001,
                1,
                0,
                3_000_000_000,
                7,
                1
            ],
            "every flag, bias, noise and rate where its field says, each bias negative and one rate \
             past an i32 so a wrong sign shows"
        );
    }

    /// Each chip senses through its own conditions: a different bias on each of the seven quantities a
    /// condition reaches lands on the chip it names and no other, at once on what the board last sensed,
    /// and a stuck unit keeps what it had with no bias on it.
    #[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 mut board = Pixracer::new().unwrap();
        let signals = Signals {
            angular_rate: [100_000, 0, -100_000],
            specific_force: [0, 0, -2 * ONE_GRAVITY],
            magnetic_field: [GAUSS_NANOTESLA, 0, GAUSS_NANOTESLA],
            pressure: 95_000,
            ..AT_REST
        };
        board.sense(&signals);
        board.condition(&Conditions {
            icm20608_rate: biased(1_000),
            icm20608_acceleration: biased(10_000),
            mpu9250_rate: biased(2_000),
            mpu9250_acceleration: Condition {
                stuck: true,
                ..biased(20_000)
            },
            mpu9250_field: biased(3_000),
            lis3mdl_field: biased(4_000),
            ms5611_pressure: Condition {
                bias: [-500],
                ..Condition::default()
            },
            ..Conditions::default()
        });

        let mut mpu9250 = Mpu9250::new();
        let [x, y, z] = plus(signals.angular_rate, 2_000);
        mpu9250.set_rate(x, y, z);
        let [x, y, z] = signals.specific_force;
        mpu9250.set_acceleration(x, y, z);
        let [x, y, z] = plus(signals.magnetic_field, 3_000);
        mpu9250.set_field(x, y, z);
        mpu9250.set_temperature(signals.temperature);
        let mut icm20608 = Icm20608::new();
        let [x, y, z] = plus(signals.angular_rate, 1_000);
        icm20608.set_rate(x, y, z);
        let [x, y, z] = plus(signals.specific_force, 10_000);
        icm20608.set_acceleration(x, y, z);
        icm20608.set_temperature(signals.temperature);
        let mut lis3mdl = Lis3mdl::new();
        let [x, y, z] = plus(signals.magnetic_field, 4_000);
        lis3mdl.set_field(x, y, z);
        lis3mdl.set_temperature(signals.temperature);
        let mut ms5611 = Ms5611::new();
        ms5611.set_pressure(94_500);
        ms5611.set_temperature(signals.temperature);
        answers_as(&mut board, mpu9250, icm20608, lis3mdl, ms5611);
    }

    /// Noise lands on the chip and the axis it names and no other, drawn for the `Advance` the link
    /// counts, and the next `Advance` moves it with no input changed. Every chip it doesn't name reads
    /// the truth.
    #[test]
    fn each_chips_noise_is_its_own_and_moves_with_each_advance() {
        const SEED: u64 = 7;
        let noisy = [
            (MPU9250_RATE_NOISE[0], 2_000),
            (ICM20608_ACCELERATION_NOISE[2], 30_000),
            (LIS3MDL_FIELD_NOISE[1], 5_000),
            (MS5611_PRESSURE_NOISE[0], 50),
        ];
        for advances in 1..=2_u64 {
            let mut board = Pixracer::new().unwrap();
            let mut held = Held::at_rest(&board, SEED).unwrap();
            for advance in 0..advances {
                let conditions = if advance == 0 {
                    noisy
                        .iter()
                        .map(|&(name, deviation)| Set {
                            index: u16::try_from(
                                <Pixracer as Edge>::CONDITIONS
                                    .iter()
                                    .position(|field| field.name == name)
                                    .unwrap(),
                            )
                            .unwrap(),
                            value: deviation,
                        })
                        .collect()
                } else {
                    Vec::new()
                };
                let quiet = Advance {
                    until: VirtualNanos(0),
                    inputs: Vec::new(),
                    ports: Vec::new(),
                    conditions,
                    armed: Vec::new(),
                };
                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()
            };
            let mut mpu9250 = Mpu9250::new();
            let [x, y, z] = AT_REST.angular_rate;
            mpu9250.set_rate(x + drawn(noisy[0]), y, z);
            let [x, y, z] = AT_REST.specific_force;
            mpu9250.set_acceleration(x, y, z);
            let [x, y, z] = AT_REST.magnetic_field;
            mpu9250.set_field(x, y, z);
            mpu9250.set_temperature(AT_REST.temperature);
            let mut icm20608 = Icm20608::new();
            let [x, y, z] = AT_REST.angular_rate;
            icm20608.set_rate(x, y, z);
            let [x, y, z] = AT_REST.specific_force;
            icm20608.set_acceleration(x, y, z + drawn(noisy[1]));
            icm20608.set_temperature(AT_REST.temperature);
            let mut lis3mdl = Lis3mdl::new();
            let [x, y, z] = AT_REST.magnetic_field;
            lis3mdl.set_field(x, y + drawn(noisy[2]), z);
            lis3mdl.set_temperature(AT_REST.temperature);
            let mut ms5611 = Ms5611::new();
            ms5611.set_pressure(AT_REST.pressure.saturating_add_signed(drawn(noisy[3])));
            ms5611.set_temperature(AT_REST.temperature);
            assert_ne!(drawn(noisy[3]), 0, "the pressure's noise is there to see");
            answers_as(&mut board, mpu9250, icm20608, lis3mdl, ms5611);
        }
    }

    /// A garbled GPS port raises a framing error with every word the receiver sends when every word
    /// errs, through the part as a firmware reads it, and a part reset keeps it, since a condition is
    /// the board's. At half the words, which ones err is the seed's the board hands the port.
    #[test]
    fn a_garbled_gps_port_frames_its_words_wrong_by_the_seed_and_a_part_reset_keeps_it() {
        use crate::device::ResetCause;
        use crate::soc::stm32f427::generated::UART4;
        use crate::soc::stm32f427::generated::rcc::apb1enr;
        use crate::soc::stm32f427::generated::uart4::{
            Register as UartRegister, cr1 as uart_cr1, sr as uart_sr,
        };

        let framed_wrong = |per_million: u32, seed: u64, reset: bool| {
            let mut board = Pixracer::new().unwrap();
            board.condition(&Conditions {
                gps_framing_errors: per_million,
                ..Conditions::default()
            });
            Edge::draw(&mut board, seed, 0);
            if reset {
                board.mcu.reset(ResetCause::Core);
            }
            let rcc = |register: RccRegister| register.spec().offset;
            write(
                &mut board,
                0,
                RCC.base,
                rcc(RccRegister::Apb1enr),
                apb1enr::UART4EN.mask(),
            );
            let uart = |register: UartRegister| register.spec().offset;
            write(&mut board, 0, UART4.base, uart(UartRegister::Brr), 0x10);
            write(
                &mut board,
                0,
                UART4.base,
                uart(UartRegister::Cr1),
                uart_cr1::UE.mask() | uart_cr1::RE.mask(),
            );
            let mut framed = Vec::new();
            for millisecond in 1..=1_000 {
                let now = millisecond * MILLISECOND;
                board.mcu.poll(VirtualNanos(now));
                board.mcu.advance_to(VirtualNanos(now));
                let status = read(&mut board, now, UART4.base, uart(UartRegister::Sr));
                if uart_sr::RXNE.is_set(status) {
                    read(&mut board, now, UART4.base, uart(UartRegister::Dr));
                    framed.push(uart_sr::FE.is_set(status));
                }
            }
            assert!(!framed.is_empty(), "the receiver reports where it is");
            framed
        };
        for reset in [false, true] {
            let framed = framed_wrong(uart::Rate::EVERY_WORD, 3, reset);
            assert!(
                framed.iter().all(|&wrong| wrong),
                "after a part reset: {reset}"
            );
        }
        let half = uart::Rate::EVERY_WORD / 2;
        let three = framed_wrong(half, 3, false);
        assert!(three.contains(&true) && three.contains(&false));
        assert_eq!(three, framed_wrong(half, 3, false));
        assert_ne!(
            three,
            framed_wrong(half, 4, false),
            "another seed, another pattern"
        );
    }

    /// The time one byte takes at the reset baud, `PCLK / 2` from the reset 16 MHz bus, with room.
    const BYTE: u64 = 2 * MICROSECOND;

    /// Which interface a chip is on, and its select.
    type Wiring = (usize, Select);

    /// Where the part maps the nth serial interface, from its own table of them.
    fn base(interface: usize) -> u64 {
        use crate::soc::stm32f427::generated::PERIPHERALS;
        use crate::soc::stm32f427::peripherals::SERIAL_INTERFACES;

        PERIPHERALS
            .iter()
            .find(|peripheral| peripheral.name == SERIAL_INTERFACES[interface])
            .expect("the part has every serial interface")
            .base
    }

    /// One select cycle with a chip through its interface, as a firmware runs one: its select reaches
    /// the interface as the port's request, and each byte crosses `DR`.
    fn through(
        board: &mut Pixracer,
        at: &mut u64,
        (interface, select): Wiring,
        bytes: &[u8],
    ) -> Vec<u8> {
        use crate::device::{Device, RequestChange};
        use crate::soc::stm32f427::generated::spi1::Register as SpiRegister;

        let data = SpiRegister::Dr.spec().offset;
        let drive = |board: &mut Pixracer, at: u64, level| {
            board
                .mcu
                .drive_serial(VirtualNanos(at), interface, |spi, registers, context| {
                    let change = RequestChange {
                        instance: select.port,
                        request: select.pin.index(),
                        level,
                    };
                    spi.on_request(change, registers, context);
                });
        };
        drive(board, *at, select.active);
        let answers = bytes
            .iter()
            .map(|&byte| {
                write(board, *at, base(interface), data, u64::from(byte));
                *at += BYTE;
                board.mcu.advance_to(VirtualNanos(*at));
                u8::try_from(read(board, *at, base(interface), data) & 0xFF).unwrap()
            })
            .collect();
        drive(board, *at, !select.active);
        answers
    }

    /// A board with both serial interfaces clocked and enabled as masters, the barometer reset and its
    /// calibration reloaded, and the instant it stands at.
    fn with_its_buses_up() -> (Pixracer, u64) {
        use crate::soc::stm32f427::generated::rcc::apb1enr;
        use crate::soc::stm32f427::generated::spi1::{Register as SpiRegister, cr1 as spi_cr1};

        let mut board = Pixracer::new().unwrap();
        let rcc = |register: RccRegister| register.spec().offset;
        write(
            &mut board,
            0,
            RCC.base,
            rcc(RccRegister::Apb2enr),
            apb2enr::SPI1EN.mask(),
        );
        write(
            &mut board,
            0,
            RCC.base,
            rcc(RccRegister::Apb1enr),
            apb1enr::SPI2EN.mask(),
        );
        let master =
            spi_cr1::MSTR.mask() | spi_cr1::SSM.mask() | spi_cr1::SSI.mask() | spi_cr1::SPE.mask();
        for interface in [IMU_ON, FRAM_ON] {
            write(
                &mut board,
                0,
                base(interface),
                SpiRegister::Cr1.spec().offset,
                master,
            );
        }
        let mut at = MICROSECOND;
        through(&mut board, &mut at, (FRAM_ON, BARO_CS), &[RESET]);
        (board, at + 3 * MILLISECOND)
    }

    const WHO_AM_I: u8 = 0x75 | READ;
    const LIS3MDL_WHO_AM_I: u8 = 0x0F | READ;
    const FRAM_RDID: u8 = 0x9F;
    const PROM_C1: u8 = 0xA2;

    /// Each chip on a serial interface, by its name in `CHIPS`, with its wiring and a command that has
    /// it say who it is.
    const SELECTED: [(&str, Wiring, &[u8]); 5] = [
        ("icm20608", (IMU_ON, SECOND_IMU_CS), &[WHO_AM_I, 0]),
        ("mpu9250", (IMU_ON, IMU_CS), &[WHO_AM_I, 0]),
        ("lis3mdl", (IMU_ON, MAG_CS), &[LIS3MDL_WHO_AM_I, 0]),
        ("fm25v02", (FRAM_ON, FRAM_CS), &[FRAM_RDID, 0]),
        ("ms5611", (FRAM_ON, BARO_CS), &[PROM_C1, 0, 0]),
    ];

    /// Every chip a board lists has its own condition to silence it, and a place past the list is none.
    #[test]
    fn each_chip_listed_has_a_silence_and_a_place() {
        let mut board = Pixracer::new().unwrap();
        for (index, chip) in <Pixracer as Edge>::CHIPS.iter().enumerate() {
            let silence = format!("{chip}.silent");
            assert!(
                <Pixracer as Edge>::CONDITIONS
                    .iter()
                    .any(|condition| condition.name == silence),
                "{chip}"
            );
            assert!(Edge::place(&mut board, index).is_some(), "{chip}");
        }
        assert!(Edge::place(&mut board, <Pixracer as Edge>::CHIPS.len()).is_none());
    }

    /// Each chip's place is its own. A select cycle is one transaction with the chip selected and none
    /// with the chips beside it, a drop loses that chip's next cycle whole so it reads as silent, and a
    /// flip changes the first word it answers and nothing after.
    #[test]
    fn each_chips_place_counts_its_own_cycles_and_takes_its_own_faults() {
        let index = |name: &str| {
            <Pixracer as Edge>::CHIPS
                .iter()
                .position(|chip| *chip == name)
                .unwrap()
        };
        let (mut board, mut at) = with_its_buses_up();
        let clean: Vec<Vec<u8>> = SELECTED
            .iter()
            .map(|&(_, wiring, identity)| through(&mut board, &mut at, wiring, identity))
            .collect();
        for (slot, &(faulted, wiring, identity)) in SELECTED.iter().enumerate() {
            let (mut board, mut at) = with_its_buses_up();
            let before: Vec<u64> = SELECTED
                .iter()
                .map(|&(name, _, _)| Edge::place(&mut board, index(name)).unwrap().ended())
                .collect();
            Edge::place(&mut board, index(faulted)).unwrap().drop_next();
            for (&(name, wiring, identity), clean) in SELECTED.iter().zip(&clean) {
                let answers = through(&mut board, &mut at, wiring, identity);
                if name == faulted {
                    assert!(answers.iter().all(|&byte| byte == 0), "{name}: {answers:?}");
                } else {
                    assert_eq!(&answers, clean, "{name} beside {faulted}");
                }
            }
            for (&(name, _, _), before) in SELECTED.iter().zip(before) {
                let ended = Edge::place(&mut board, index(name)).unwrap().ended();
                assert_eq!(ended, before + 1, "{name}, with {faulted} dropped");
            }
            Edge::place(&mut board, index(faulted)).unwrap().flip(0x81);
            let answers = through(&mut board, &mut at, wiring, identity);
            let clean = &clean[slot];
            assert_eq!(answers[0], clean[0] ^ 0x81, "{faulted}");
            assert_eq!(answers[1..], clean[1..], "{faulted}");
        }
    }

    /// Each silence reaches its own chip and no other. Through its interface, a silent chip reads as an
    /// empty place, zero, and every chip beside it answers who it is as it did.
    #[test]
    fn each_silence_reaches_its_own_chip() {
        type Silence = fn(&mut Conditions);
        let chips: [(&str, Silence, Wiring, &[u8]); 5] = [
            (
                "the ICM-20608",
                |conditions| conditions.icm20608_silent = true,
                (IMU_ON, SECOND_IMU_CS),
                &[WHO_AM_I, 0],
            ),
            (
                "the MPU-9250",
                |conditions| conditions.mpu9250_silent = true,
                (IMU_ON, IMU_CS),
                &[WHO_AM_I, 0],
            ),
            (
                "the LIS3MDL",
                |conditions| conditions.lis3mdl_silent = true,
                (IMU_ON, MAG_CS),
                &[LIS3MDL_WHO_AM_I, 0],
            ),
            (
                "the FM25V02",
                |conditions| conditions.fm25v02_silent = true,
                (FRAM_ON, FRAM_CS),
                &[FRAM_RDID, 0],
            ),
            (
                "the MS5611",
                |conditions| conditions.ms5611_silent = true,
                (FRAM_ON, BARO_CS),
                &[PROM_C1, 0, 0],
            ),
        ];
        for (silenced, silence, _, _) in chips {
            let (mut board, mut at) = with_its_buses_up();
            let mut conditions = Conditions::default();
            silence(&mut conditions);
            board.condition(&conditions);
            for (name, _, chip, identity) in chips {
                let answers = through(&mut board, &mut at, chip, identity);
                if name == silenced {
                    assert!(
                        answers.iter().all(|&byte| byte == 0),
                        "{name} is silent: {answers:?}"
                    );
                } else {
                    assert!(
                        answers[1..].iter().any(|&byte| byte != 0),
                        "{name} answers beside {silenced}: {answers:?}"
                    );
                }
            }
        }
    }

    /// The receiver goes quiet and the card stops answering, each through the part as a firmware reads
    /// it: `UART4` takes no byte, and a command to the card times out. A part reset changes neither.
    #[test]
    fn a_silent_receiver_sends_nothing_and_a_silent_card_answers_nothing() {
        use crate::device::ResetCause;
        use crate::soc::stm32f427::generated::rcc::apb1enr;
        use crate::soc::stm32f427::generated::sdio::{Register as SdioRegister, cmd, power, sta};
        use crate::soc::stm32f427::generated::uart4::{
            Register as UartRegister, cr1 as uart_cr1, sr as uart_sr,
        };
        use crate::soc::stm32f427::generated::{SDIO, UART4};

        const APP_CMD: u64 = 55;
        let heard = |silent: bool, reset: bool| {
            let mut board = Pixracer::new().unwrap();
            board.condition(&Conditions {
                gps_silent: silent,
                card_silent: silent,
                ..Conditions::default()
            });
            if reset {
                board.mcu.reset(ResetCause::Core);
            }
            let rcc = |register: RccRegister| register.spec().offset;
            write(
                &mut board,
                0,
                RCC.base,
                rcc(RccRegister::Apb1enr),
                apb1enr::UART4EN.mask(),
            );
            write(
                &mut board,
                0,
                RCC.base,
                rcc(RccRegister::Apb2enr),
                apb2enr::SDIOEN.mask(),
            );
            let uart = |register: UartRegister| register.spec().offset;
            write(&mut board, 0, UART4.base, uart(UartRegister::Brr), 0x10);
            write(
                &mut board,
                0,
                UART4.base,
                uart(UartRegister::Cr1),
                uart_cr1::UE.mask() | uart_cr1::RE.mask(),
            );
            let mut bytes = 0;
            for millisecond in 1..=1_000 {
                let now = millisecond * MILLISECOND;
                board.mcu.poll(VirtualNanos(now));
                board.mcu.advance_to(VirtualNanos(now));
                if uart_sr::RXNE.is_set(read(&mut board, now, UART4.base, uart(UartRegister::Sr))) {
                    read(&mut board, now, UART4.base, uart(UartRegister::Dr));
                    bytes += 1;
                }
            }
            let sdio = |register: SdioRegister| register.spec().offset;
            let now = 1_001 * MILLISECOND;
            write(
                &mut board,
                now,
                SDIO.base,
                sdio(SdioRegister::Power),
                power::PWRCTRL.set(0, 0b11),
            );
            write(
                &mut board,
                now,
                SDIO.base,
                sdio(SdioRegister::Cmd),
                cmd::CPSMEN.mask() | cmd::WAITRESP.set(0, 0b01) | cmd::CMDINDEX.set(0, APP_CMD),
            );
            let status = read(&mut board, now, SDIO.base, sdio(SdioRegister::Sta));
            (
                bytes,
                sta::CMDREND.is_set(status),
                sta::CTIMEOUT.is_set(status),
            )
        };
        let (bytes, answered, timed_out) = heard(false, false);
        assert!(bytes > 0, "the receiver reports where it is");
        assert!(answered && !timed_out, "the card answers");
        assert_eq!(
            heard(true, false),
            (0, false, true),
            "and silent, neither does"
        );
        assert_eq!(
            heard(true, true),
            (0, false, true),
            "nor after a part reset, since a condition is the board's"
        );
    }

    /// An `Advance` that changes a condition and nothing else reaches the board: the barometer goes
    /// silent with no input changed.
    #[test]
    fn an_advance_carrying_only_a_condition_reaches_the_board() {
        const PROM_C1: u8 = 0xA2;
        let (mut board, mut at) = with_its_buses_up();
        let mut held = Held::at_rest(&board, 0).unwrap();
        let silent = <Pixracer as Edge>::CONDITIONS
            .iter()
            .position(|field| field.name == "ms5611.silent")
            .unwrap();
        deliver(
            &mut board,
            &mut held,
            &[],
            &Advance {
                until: VirtualNanos(at),
                inputs: Vec::new(),
                ports: Vec::new(),
                conditions: vec![Set {
                    index: u16::try_from(silent).unwrap(),
                    value: 1,
                }],
                armed: Vec::new(),
            },
            VirtualNanos(at),
        )
        .unwrap();
        let answers = through(&mut board, &mut at, (FRAM_ON, BARO_CS), &[PROM_C1, 0, 0]);
        assert_eq!(answers, [0; 3], "an empty place");
    }

    #[test]
    fn an_advance_sets_an_input_the_board_senses_whole_and_queues_a_ports_bytes() {
        let mut board = Pixracer::new().unwrap();
        assert_eq!(
            attach_engine_ports(&mut board).unwrap(),
            [TELEMETRY_WIRE.name]
        );
        let mut held = Held::at_rest(&board, 0).unwrap();
        let pressure = <Pixracer as Edge>::FIELDS
            .iter()
            .position(|field| field.name == "pressure")
            .unwrap();
        deliver(
            &mut board,
            &mut held,
            &[TELEMETRY_WIRE.name],
            &Advance {
                until: VirtualNanos(0),
                inputs: vec![Set {
                    index: u16::try_from(pressure).unwrap(),
                    value: 90_000,
                }],
                ports: vec![b"x".to_vec()],
                conditions: Vec::new(),
                armed: Vec::new(),
            },
            VirtualNanos(0),
        )
        .unwrap();
        let mut ms5611 = Ms5611::new();
        ms5611.set_pressure(90_000);
        ms5611.set_temperature(AT_REST.temperature);
        let mut at = 10 * 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 (on_board, expected) = barometer(&mut board, &[ADC_READ, 0, 0, 0]);
        assert_eq!(
            on_board, expected,
            "the barometer converts the pressure set"
        );
        let port = board.host_mut(TELEMETRY_WIRE.name).unwrap();
        assert_eq!(port.transmit(VirtualNanos(0)), Some(u16::from(b'x')));
    }

    #[test]
    fn an_advance_for_another_boards_ports_or_inputs_is_refused_by_name() {
        let mut board = Pixracer::new().unwrap();
        attach_engine_ports(&mut board).unwrap();
        let mut held = Held::at_rest(&board, 0).unwrap();
        let too_many_ports = Advance {
            until: VirtualNanos(0),
            inputs: Vec::new(),
            ports: vec![Vec::new(), Vec::new()],
            conditions: Vec::new(),
            armed: Vec::new(),
        };
        assert!(matches!(
            deliver(
                &mut board,
                &mut held,
                &[TELEMETRY_WIRE.name],
                &too_many_ports,
                VirtualNanos(0),
            ),
            Err(LinkError::Misfit(_))
        ));
        let no_such_input = Advance {
            until: VirtualNanos(0),
            inputs: vec![Set {
                index: 99,
                value: 0,
            }],
            ports: vec![Vec::new()],
            conditions: Vec::new(),
            armed: Vec::new(),
        };
        assert!(matches!(
            deliver(
                &mut board,
                &mut held,
                &[TELEMETRY_WIRE.name],
                &no_such_input,
                VirtualNanos(0),
            ),
            Err(LinkError::Misfit(_))
        ));
    }

    /// What the engine delivers on `serial1` reaches the firmware through `USART2`, and what the firmware
    /// sends there comes back for the next `Reached`, each byte once: 30.3.2 and 30.3.3 with the link
    /// on the far end of the wire.
    #[test]
    fn the_engine_s_port_on_serial1_carries_a_byte_each_way() {
        use crate::soc::stm32f427::generated::USART2;
        use crate::soc::stm32f427::generated::rcc::apb1enr;
        use crate::soc::stm32f427::generated::usart6::{
            Register as UsartRegister, cr1 as usart_cr1, sr as usart_sr,
        };

        let mut board = Pixracer::new().unwrap();
        let ports = attach_engine_ports(&mut board).unwrap();
        let usart = |register: UsartRegister| register.spec().offset;
        write(
            &mut board,
            0,
            RCC.base,
            RccRegister::Apb1enr.spec().offset,
            apb1enr::USART2EN.mask(),
        );
        // A megabaud on the reset 16 MHz bus, so a ten-bit frame is ten microseconds.
        write(&mut board, 0, USART2.base, usart(UsartRegister::Brr), 0x10);
        write(
            &mut board,
            0,
            USART2.base,
            usart(UsartRegister::Cr1),
            usart_cr1::UE.mask() | usart_cr1::TE.mask() | usart_cr1::RE.mask(),
        );
        let mut held = Held::at_rest(&board, 0).unwrap();
        let advance = Advance {
            until: VirtualNanos(MILLISECOND),
            inputs: Vec::new(),
            ports: vec![b"k".to_vec()],
            conditions: Vec::new(),
            armed: Vec::new(),
        };
        deliver(&mut board, &mut held, &ports, &advance, VirtualNanos(0)).unwrap();
        board.mcu.poll(VirtualNanos(0));
        let frame = 10 * MICROSECOND;
        board.mcu.advance_to(VirtualNanos(frame));
        let status = read(&mut board, frame, USART2.base, usart(UsartRegister::Sr));
        assert!(usart_sr::RXNE.is_set(status), "the engine's byte arrived");
        assert_eq!(
            read(&mut board, frame, USART2.base, usart(UsartRegister::Dr)),
            u64::from(b'k')
        );
        write(
            &mut board,
            frame,
            USART2.base,
            usart(UsartRegister::Dr),
            u64::from(b'q'),
        );
        board.mcu.advance_to(VirtualNanos(3 * frame));
        assert_eq!(sent(&mut board, &ports).unwrap(), [b"q".to_vec()]);
        assert_eq!(
            sent(&mut board, &ports).unwrap(),
            [Vec::<u8>::new()],
            "each byte is told once"
        );
    }

    /// 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();
        assert_eq!(
            board.drive(),
            IDLE,
            "nothing drives a pin before the firmware"
        );
        let named: Vec<String> = IDLE
            .0
            .iter()
            .flat_map(|actuator| {
                ["width", "period", "command"].map(|part| format!("{}.{part}", actuator.name))
            })
            .collect();
        let fields: Vec<&str> = <Pixracer as Edge>::OUTPUT_FIELDS
            .iter()
            .map(|field| field.name.as_ref())
            .collect();
        assert_eq!(
            fields, named,
            "the fields name the outputs in the order they cross"
        );
        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 outputs = board.drive();
        assert_eq!(
            outputs.0[0],
            Actuator {
                name: "PWM1",
                pulse: Some(Pulse {
                    width: VirtualNanos(1_500 * MICROSECOND),
                    period: VirtualNanos(20 * MILLISECOND),
                }),
                command: Some(500),
            }
        );
        assert!(
            outputs.0[1..]
                .iter()
                .all(|actuator| actuator.pulse.is_none())
        );
        let mut bytes = Vec::new();
        outputs.encode(&mut bytes);
        let values = values_of(<Pixracer as Edge>::OUTPUT_FIELDS, &bytes).unwrap();
        assert_eq!(values[..6], [1_500_000, 20_000_000, 500, 0, 0, 0]);
        assert_eq!(
            Outputs::decode(&mut bytes.as_slice()).unwrap(),
            outputs,
            "an output with no period comes back with no pulse and no command"
        );
    }

    const SERVO: Curve = Curve {
        zero: VirtualNanos(1_000_000),
        full: VirtualNanos(2_000_000),
    };

    fn width(nanos: u64) -> Pulse {
        Pulse {
            width: VirtualNanos(nanos),
            period: VirtualNanos(20_000_000),
        }
    }

    #[test]
    fn a_command_is_where_the_width_falls_between_the_ends_and_never_past_them() {
        assert_eq!(SERVO.command(width(1_000_000)), 0);
        assert_eq!(SERVO.command(width(1_250_000)), 250);
        assert_eq!(SERVO.command(width(2_000_000)), FULL);
        assert_eq!(SERVO.command(width(0)), 0, "narrower than nothing");
        assert_eq!(
            SERVO.command(width(3_000_000)),
            FULL,
            "wider than everything"
        );
    }

    #[test]
    fn an_output_without_a_pulse_commands_nothing() {
        let off = Actuator::on("OUT", None, SERVO);
        assert_eq!(off.command, None);
        let on = Actuator::on("OUT", Some(width(1_500_000)), SERVO);
        assert_eq!(on.command, Some(500));
    }

    /// The description's `serial1` is the second serial port, and a host hung there is what that
    /// port talks to. A wire the board doesn't have 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}"
        );
    }

    /// What a chip of each kind given its quantities by hand answered to the driver's reads, which the
    /// board's own chip answered byte for byte: each unit's sample, the MPU-9250's first, the compass
    /// die's field, the magnetometer's frame, and the barometer's pressure and temperature conversions.
    struct Answered {
        units: [Vec<u8>; 2],
        die: Vec<u8>,
        magnetometer: Vec<u8>,
        pressure: Vec<u8>,
        temperature: Vec<u8>,
    }

    /// Every read the driver makes of the board's chips, held against `mpu9250`, `icm20608`, `lis3mdl`
    /// and `ms5611`, each given its quantities by hand.
    fn answers_as(
        board: &mut Pixracer,
        mut mpu9250: Mpu9250,
        mut icm20608: Icm20608,
        mut lis3mdl: Lis3mdl,
        mut ms5611: Ms5611,
    ) -> Answered {
        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)];
        let units = units.map(|(nth, unit)| {
            alike(
                board,
                MILLISECOND,
                (IMU_ON, nth),
                unit,
                &[PWR_MGMT_1, CLOCK_ON],
            );
            let (on_board, expected) = alike(board, 5 * MILLISECOND, (IMU_ON, nth), unit, &sample);
            assert_eq!(on_board, expected, "unit {nth}");
            expected
        });

        let (on_board, die) = compass_die_fields(board, &mut mpu9250);
        assert_eq!(on_board, die, "the compass die inside the first unit");

        alike(
            board,
            MILLISECOND,
            (IMU_ON, LIS3MDL_PEER),
            &mut lis3mdl,
            &[CTRL_REG1, TEMP_EN | ODR_80_ULTRAHIGH],
        );
        alike(
            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, magnetometer) = alike(
            board,
            30 * MILLISECOND,
            (IMU_ON, LIS3MDL_PEER),
            &mut lis3mdl,
            &frame,
        );
        assert_eq!(on_board, magnetometer, "the magnetometer");

        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(board, &[RESET]);
        barometer(board, &[CONVERT_D1]);
        let (on_board, pressure) = barometer(board, &[ADC_READ, 0, 0, 0]);
        assert_eq!(on_board, pressure, "the barometer's pressure conversion");
        barometer(board, &[CONVERT_D2]);
        let (on_board, temperature) = barometer(board, &[ADC_READ, 0, 0, 0]);
        assert_eq!(
            on_board, temperature,
            "the barometer's temperature conversion"
        );
        Answered {
            units,
            die,
            magnetometer,
            pressure,
            temperature,
        }
    }

    /// 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 answered = answers_as(&mut board, mpu9250, icm20608, lis3mdl, ms5611);
        for expected in &answered.units {
            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");
        }
        assert_ne!(answered.die, [0; 6]);
        assert_eq!(
            words(&answered.magnetometer[1..7], false),
            [COUNTS_PER_GAUSS, 0, COUNTS_PER_GAUSS]
        );
        assert_ne!(
            &answered.magnetometer[7..9],
            [0, 0],
            "the magnetometer's temperature"
        );
        assert_ne!(&answered.pressure[1..], [0, 0, 0]);
        assert_ne!(&answered.temperature[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, and 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 crate::snapshot::Store for Counter {}

        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]
            .core
            .properties
            .iter()
            .find(|property| property.name == armv7m::INTERRUPT_LINES)
            .expect("the machine is told its interrupt count");
        assert_eq!(
            declared.value,
            lines.to_string(),
            "the count the core is given is the count the MCU has"
        );
    }
}