alpha_g_detector 0.5.1

A Rust library to handle the raw output of the ALPHA-g detectors
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
use std::fmt;
use thiserror::Error;

// Only imported for documentation. If you notice that this is no longer the
// case, please open an issue/PR.
#[allow(unused_imports)]
use crate::padwing::map::TpcPwbPosition;

/// Pad and PWB map.
///
/// There are a total of 64 Padwing boards (8 columns and 8 rows). Each PWB
/// has 4 columns and 72 rows of pads, for a total of 32 columns and 576 rows.
pub mod map;

/// Sampling rate (samples per second) of the channels that receive the radial
/// Time Projection Chamber cathode pad signals.
pub const PWB_RATE: f64 = 62.5e6;
/// Maximum value at which the PWB waveforms saturate.
pub const PWB_MAX: i16 = 2047;
/// Minimum value at which the PWB waveforms saturate.
pub const PWB_MIN: i16 = -2048;

/// The error type returned when parsing a [`BoardId`] fails.
#[derive(Error, Debug)]
#[error("unknown parsing from board name `{input}` to BoardId")]
pub struct ParseBoardIdError {
    input: String,
}

/// The error type returned when conversion from mac address to [`BoardId`]
/// fails.
#[derive(Error, Debug)]
#[error("unknown conversion from mac address `{input:?}` to BoardId")]
pub struct TryBoardIdFromMacAddressError {
    input: [u8; 6],
}

/// The error type returned when conversion from unsigned integer to [`BoardId`]
/// fails.
#[derive(Error, Debug)]
#[error("unknown conversion from unsigned `{input}` to BoardId")]
pub struct TryBoardIdFromUnsignedError {
    input: u32,
}

// Known PadWing board names, mac addresses, and device IDs
// Just add new boards to this list
// ("name", [mac address], device_id)
// "name" is 2 ASCII characters that also appear in the data bank name
// Note: The device ID is just the first 4 bytes of the MAC address as
// little endian u32. Maybe remove the last u32 in the future, and just get it
// from the MAC address.
const PADWING_BOARDS: [(&str, [u8; 6], u32); 71] = [
    ("00", [236, 40, 255, 135, 84, 2], 2281646316),
    ("01", [236, 40, 250, 162, 84, 2], 2734303468),
    ("02", [236, 40, 136, 108, 84, 2], 1820862700),
    ("03", [236, 40, 226, 49, 84, 2], 836905196),
    ("04", [236, 41, 12, 121, 84, 2], 2030840300),
    ("05", [236, 40, 211, 69, 84, 2], 1171466476),
    ("06", [236, 40, 218, 6, 84, 2], 114960620),
    ("07", [236, 40, 116, 164, 84, 2], 2759076076),
    ("08", [236, 40, 253, 139, 84, 2], 2348624108),
    ("10", [236, 40, 248, 75, 84, 2], 1274554604),
    ("11", [236, 40, 197, 187, 84, 2], 3150260460),
    ("12", [236, 41, 34, 206, 84, 2], 3458345452),
    ("13", [236, 40, 159, 252, 84, 2], 4238289132),
    ("14", [236, 41, 44, 52, 84, 2], 875309548),
    ("15", [236, 40, 219, 60, 84, 2], 1020995820),
    ("17", [236, 40, 153, 39, 84, 2], 664348908),
    ("18", [236, 40, 228, 87, 84, 2], 1474570476),
    ("19", [236, 40, 116, 173, 84, 2], 2910071020),
    ("20", [236, 40, 219, 80, 84, 2], 1356540140),
    ("21", [236, 40, 221, 26, 84, 2], 450701548),
    ("22", [236, 40, 113, 70, 84, 2], 1181821164),
    ("23", [236, 41, 39, 253, 84, 2], 4247202284),
    ("24", [236, 40, 226, 191, 84, 2], 3219269868),
    ("25", [236, 40, 212, 176, 84, 2], 2966694124),
    ("26", [236, 40, 188, 31, 84, 2], 532424940),
    ("27", [236, 40, 252, 239, 84, 2], 4026280172),
    ("29", [236, 40, 108, 189, 84, 2], 3177982188),
    ("33", [236, 40, 255, 150, 84, 2], 2533304556),
    ("34", [236, 40, 226, 52, 84, 2], 887236844),
    ("35", [236, 40, 137, 30, 84, 2], 512305388),
    ("36", [236, 40, 165, 153, 84, 2], 2577737964),
    ("37", [236, 41, 43, 61, 84, 2], 1026238956),
    ("39", [236, 41, 43, 253, 84, 2], 4247464428),
    ("40", [236, 40, 198, 81, 84, 2], 1371941100),
    ("41", [236, 40, 187, 198, 84, 2], 3334154476),
    ("42", [236, 41, 41, 188, 84, 2], 3156814316),
    ("44", [236, 40, 218, 198, 84, 2], 3336186092),
    ("45", [236, 41, 24, 143, 84, 2], 2400725484),
    ("46", [236, 40, 160, 64, 84, 2], 1084238060),
    ("49", [236, 40, 156, 87, 84, 2], 1469851884),
    ("52", [236, 41, 24, 28, 84, 2], 471345644),
    ("53", [236, 40, 183, 208, 84, 2], 3501664492),
    ("54", [236, 40, 113, 62, 84, 2], 1047603436),
    ("55", [236, 40, 255, 172, 84, 2], 2902403308),
    ("56", [236, 40, 135, 152, 84, 2], 2558994668),
    ("57", [236, 40, 128, 45, 84, 2], 763373804),
    ("58", [236, 41, 42, 70, 84, 2], 1177168364),
    ("60", [236, 40, 243, 36, 84, 2], 619915500),
    ("63", [236, 40, 108, 234, 84, 2], 3932956908),
    ("64", [236, 40, 110, 20, 84, 2], 342763756),
    ("65", [236, 40, 215, 15, 84, 2], 265758956),
    ("66", [236, 40, 197, 199, 84, 2], 3351587052),
    ("67", [236, 40, 183, 38, 84, 2], 649537772),
    ("68", [236, 40, 211, 91, 84, 2], 1540565228),
    ("69", [236, 40, 224, 249, 84, 2], 4192217324),
    ("70", [236, 40, 248, 99, 84, 2], 1677207788),
    ("71", [236, 40, 129, 16, 84, 2], 276900076),
    ("72", [236, 40, 241, 249, 84, 2], 4193331436),
    ("73", [236, 40, 113, 64, 84, 2], 1081157868),
    ("74", [236, 40, 252, 14, 84, 2], 251406572),
    ("75", [236, 41, 39, 26, 84, 2], 438774252),
    ("76", [236, 40, 244, 136, 84, 2], 2297702636),
    ("77", [236, 41, 17, 29, 84, 2], 487664108),
    ("78", [236, 41, 37, 14, 84, 2], 237316588),
    ("81", [236, 40, 137, 152, 84, 2], 2559125740),
    ("84", [236, 40, 135, 104, 84, 2], 1753688300),
    ("85", [236, 40, 216, 183, 84, 2], 3084396780),
    ("87", [236, 40, 244, 138, 84, 2], 2331257068),
    ("89", [57, 232, 246, 41, 216, 2], 704047161),
    ("90", [57, 232, 209, 204, 216, 2], 3436308537),
    ("91", [236, 40, 190, 114, 84, 2], 1925064940),
];

/// Identity of a physical PadWing board.
///
/// It is important to notice that a [`BoardId`] is different to a
/// [`TpcPwbPosition`]. The former identifies a physical PadWing board, while
/// the latter is a fixed position that maps a location in the rTPC. The mapping
/// between [`BoardId`] and [`TpcPwbPosition`] depends on the run number e.g. we
/// switch an old board for a new board.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct BoardId {
    name: &'static str,
    mac_address: [u8; 6],
    device_id: u32,
}
impl TryFrom<&str> for BoardId {
    type Error = ParseBoardIdError;

    fn try_from(name: &str) -> Result<Self, Self::Error> {
        for triplet in PADWING_BOARDS {
            if name == triplet.0 {
                return Ok(BoardId {
                    name: triplet.0,
                    mac_address: triplet.1,
                    device_id: triplet.2,
                });
            }
        }
        Err(ParseBoardIdError {
            input: name.to_string(),
        })
    }
}
impl TryFrom<[u8; 6]> for BoardId {
    type Error = TryBoardIdFromMacAddressError;

    fn try_from(mac: [u8; 6]) -> Result<Self, Self::Error> {
        for triplet in PADWING_BOARDS {
            if mac == triplet.1 {
                return Ok(BoardId {
                    name: triplet.0,
                    mac_address: triplet.1,
                    device_id: triplet.2,
                });
            }
        }
        Err(TryBoardIdFromMacAddressError { input: mac })
    }
}
impl TryFrom<u32> for BoardId {
    type Error = TryBoardIdFromUnsignedError;

    fn try_from(device_id: u32) -> Result<Self, Self::Error> {
        for triplet in PADWING_BOARDS {
            if device_id == triplet.2 {
                return Ok(BoardId {
                    name: triplet.0,
                    mac_address: triplet.1,
                    device_id: triplet.2,
                });
            }
        }
        Err(TryBoardIdFromUnsignedError { input: device_id })
    }
}
impl BoardId {
    /// Return the name of a physical PadWing board. This is a human readable
    /// name used to identify a board instead of the mac address or device ID.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryBoardIdFromMacAddressError;
    /// # fn main() -> Result<(), TryBoardIdFromMacAddressError> {
    /// use alpha_g_detector::padwing::BoardId;
    ///
    /// let board_id = BoardId::try_from([236, 40, 255, 135, 84, 2])?;
    /// assert_eq!(board_id.name(), "00");
    /// # Ok(())
    /// # }
    /// ```
    pub fn name(&self) -> &str {
        self.name
    }
    /// Return the mac address of a physical PadWing board.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::ParseBoardIdError;
    /// # fn main() -> Result<(), ParseBoardIdError> {
    /// use alpha_g_detector::padwing::BoardId;
    ///
    /// let board_id = BoardId::try_from("00")?;
    /// assert_eq!(board_id.mac_address(), [236, 40, 255, 135, 84, 2]);
    /// # Ok(())
    /// # }
    /// ```
    pub fn mac_address(&self) -> [u8; 6] {
        self.mac_address
    }
    /// Return the device ID of a physical PadWing board.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::ParseBoardIdError;
    /// # fn main() -> Result<(), ParseBoardIdError> {
    /// use alpha_g_detector::padwing::BoardId;
    ///
    /// let board_id = BoardId::try_from("00")?;
    /// assert_eq!(board_id.device_id(), 2281646316);
    /// # Ok(())
    /// # }
    /// ```
    pub fn device_id(&self) -> u32 {
        self.device_id
    }
}

/// The error type returned when conversion from unsigned integer to [`AfterId`]
/// fails.
#[derive(Error, Debug)]
#[error("unknown conversion from unsigned `{input}` to AfterId")]
pub struct TryAfterIdFromUnsignedError {
    input: u8,
}

/// The error type returned when parsing an [`AfterId`] fails.
#[derive(Error, Debug)]
#[error("unknown parsing from char `{input}` to AfterId")]
pub struct ParseAfterIdError {
    input: char,
}

/// AFTER chip in a PadWing board.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AfterId {
    A,
    B,
    C,
    D,
}
impl TryFrom<u8> for AfterId {
    type Error = TryAfterIdFromUnsignedError;

    fn try_from(num: u8) -> Result<Self, Self::Error> {
        match num {
            0 => Ok(Self::A),
            1 => Ok(Self::B),
            2 => Ok(Self::C),
            3 => Ok(Self::D),
            _ => Err(Self::Error { input: num }),
        }
    }
}
impl TryFrom<char> for AfterId {
    type Error = ParseAfterIdError;

    fn try_from(character: char) -> Result<Self, Self::Error> {
        match character {
            'A' => Ok(Self::A),
            'B' => Ok(Self::B),
            'C' => Ok(Self::C),
            'D' => Ok(Self::D),
            _ => Err(Self::Error { input: character }),
        }
    }
}

/// The error type returned when conversion from
/// [`&[u8]`](https://doc.rust-lang.org/std/primitive.slice.html) to [`Chunk`]
/// fails.
#[derive(Error, Debug)]
pub enum TryChunkFromSliceError {
    /// The input slice is not long enough to contain a complete chunk.
    #[error("incomplete slice (expected at least `{min_expected}` bytes, found `{found}`)")]
    IncompleteSlice { found: usize, min_expected: usize },
    /// Integer representation of device ID doesn't match any known [`BoardId`].
    #[error("unknown device id")]
    UnknownDeviceId(#[from] TryBoardIdFromUnsignedError),
    /// Integer representation of ASIC ID doesn't match any known [`AfterId`].
    #[error("unknown channel id")]
    UnknownChannelId(#[from] TryAfterIdFromUnsignedError),
    /// Integer representation of flags doesn't match any known set of flags.
    #[error("unknown flags `{found:0>8b}`")]
    UnknownFlags { found: u8 },
    /// The number of unpadded payload bytes is below/above the expected
    /// minimum/maximum.
    #[error("bad chunk length `{found}` (expected at least `{min}` and at most `{max}`)")]
    BadChunkLength {
        found: usize,
        min: usize,
        max: usize,
    },
    /// Non-zero value found in bytes meant to be fixed to `0`.
    #[error("zero-bytes mismatch (found `{found:?}`)")]
    ZeroMismatch { found: Vec<u8> },
    /// The CRC-32C value calculated form the first four words of the header
    /// doesn't match the expected value.
    #[error("header CRC-32C mismatch (expected `{expected}`, found `{found}`)")]
    HeaderCRC32CMismatch { found: u32, expected: u32 },
    /// The CRC-32C value calculated form the payload (including padding bytes)
    /// doesn't match the expected value.
    #[error("payload CRC-32C mismatch (expected `{expected}`, found `{found}`)")]
    PayloadCRC32CMismatch { found: u32, expected: u32 },
}

/// MCP Chunk.
///
/// A Chunk in the Message Chunk Protocol. Here, a packet (message) of data is
/// broken into chunks. Each chunk contains a header and a payload. The binary
/// representation of a [`Chunk`] in a data bank is shown below. All multi-byte
/// fields are little-endian:
///
/// <center>
///
/// |Byte(s)|Description|
/// |:-:|:-:|
/// |0-3|Device ID|
/// |4-7|Packet sequence|
/// |8-9|Channel sequence|
/// |10|Channel ID|
/// |11|Flags|
/// |12-13|Chunk ID|
/// |14-15|Chunk length|
/// |16-19|Header CRC-32C|
/// |...|Payload, 32-bit aligned|
/// |Last 4 bytes| Payload CRC-32C|
///
/// </center>
#[derive(Clone, Debug)]
pub struct Chunk {
    // Even though device_id and channel_id represent the BoardId and AfterId,
    // keep them as integers internally to simplify the CRC-32C and printing
    // without having to implemento Into u32/u8.
    // The constructor should ensure that BoardId::try_from and
    // AfterId::try_from cannot fail.
    device_id: u32,
    packet_sequence: u32,
    channel_sequence: u16,
    channel_id: u8,
    flags: u8,
    chunk_id: u16,
    payload: Vec<u8>,
}

impl fmt::Display for Chunk {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "Device ID: {}", self.device_id)?;
        writeln!(f, "Packet sequence: {}", self.packet_sequence)?;
        writeln!(f, "Channel sequence: {}", self.channel_sequence)?;
        writeln!(f, "Channel ID: {}", self.channel_id)?;
        writeln!(f, "Flags: {:0>8b}", self.flags)?;
        writeln!(f, "Chunk ID: {}", self.chunk_id)?;
        writeln!(f, "Chunk length: {}", self.payload.len())?;
        writeln!(f, "Header CRC-32C: {}", self.header_crc32c())?;
        write!(f, "Payload CRC-32C: {}", self.payload_crc32c())?;

        Ok(())
    }
}

impl Chunk {
    /// Return the board ID of the PWB from where the [`Chunk`] is sent.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use alpha_g_detector::padwing::{BoardId, Chunk};
    ///
    /// let buffer = [236, 40, 255, 135, 2, 0, 0, 0, 3, 0, 0, 1, 5, 0, 1, 0, 143, 203, 131, 81, 255, 0, 0, 0, 122, 92, 155, 159];
    /// let chunk = Chunk::try_from(&buffer[..])?;
    ///
    /// assert_eq!(chunk.board_id(), BoardId::try_from("00")?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn board_id(&self) -> BoardId {
        BoardId::try_from(self.device_id).unwrap()
    }
    /// Return the packet sequence. This is a counter associated to a device
    /// which increments every time a [`Chunk`] is sent.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryChunkFromSliceError;
    /// # fn main() -> Result<(), TryChunkFromSliceError> {
    /// use alpha_g_detector::padwing::Chunk;
    ///
    /// let buffer = [236, 40, 255, 135, 2, 0, 0, 0, 3, 0, 0, 1, 5, 0, 1, 0, 143, 203, 131, 81, 255, 0, 0, 0, 122, 92, 155, 159];
    /// let chunk = Chunk::try_from(&buffer[..])?;
    ///
    /// assert_eq!(chunk.packet_sequence(), 2);
    /// # Ok(())
    /// # }
    /// ```
    pub fn packet_sequence(&self) -> u32 {
        self.packet_sequence
    }
    /// Return the channel sequence. This is a counter associated to a channel
    /// ID which increments every time a [`Chunk`] is sent.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryChunkFromSliceError;
    /// # fn main() -> Result<(), TryChunkFromSliceError> {
    /// use alpha_g_detector::padwing::Chunk;
    ///
    /// let buffer = [236, 40, 255, 135, 2, 0, 0, 0, 3, 0, 0, 1, 5, 0, 1, 0, 143, 203, 131, 81, 255, 0, 0, 0, 122, 92, 155, 159];
    /// let chunk = Chunk::try_from(&buffer[..])?;
    ///
    /// assert_eq!(chunk.channel_sequence(), 3);
    /// # Ok(())
    /// # }
    /// ```
    pub fn channel_sequence(&self) -> u16 {
        self.channel_sequence
    }
    /// Return the AFTER chip ID for which this [`Chunk`] corresponds to.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryChunkFromSliceError;
    /// # fn main() -> Result<(), TryChunkFromSliceError> {
    /// use alpha_g_detector::padwing::{AfterId, Chunk};
    ///
    /// let buffer = [236, 40, 255, 135, 2, 0, 0, 0, 3, 0, 0, 1, 5, 0, 1, 0, 143, 203, 131, 81, 255, 0, 0, 0, 122, 92, 155, 159];
    /// let chunk = Chunk::try_from(&buffer[..])?;
    ///
    /// assert_eq!(chunk.after_id(), AfterId::A);
    /// # Ok(())
    /// # }
    /// ```
    pub fn after_id(&self) -> AfterId {
        AfterId::try_from(self.channel_id).unwrap()
    }
    /// Return [`true`] if this is the last [`Chunk`] in a message (by actual
    /// position, not sent sequence).
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryChunkFromSliceError;
    /// # fn main() -> Result<(), TryChunkFromSliceError> {
    /// use alpha_g_detector::padwing::Chunk;
    ///
    /// let buffer = [236, 40, 255, 135, 2, 0, 0, 0, 3, 0, 0, 1, 5, 0, 1, 0, 143, 203, 131, 81, 255, 0, 0, 0, 122, 92, 155, 159];
    /// let chunk = Chunk::try_from(&buffer[..])?;
    ///
    /// assert!(chunk.is_end_of_message());
    /// # Ok(())
    /// # }
    /// ```
    pub fn is_end_of_message(&self) -> bool {
        self.flags & 1 == 1
    }
    /// Return the chunk ID. This is a counter that indicates the position of
    /// the [`Chunk`] within a message. The first chunk has an ID equal to `0`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryChunkFromSliceError;
    /// # fn main() -> Result<(), TryChunkFromSliceError> {
    /// use alpha_g_detector::padwing::Chunk;
    ///
    /// let buffer = [236, 40, 255, 135, 2, 0, 0, 0, 3, 0, 0, 1, 5, 0, 1, 0, 143, 203, 131, 81, 255, 0, 0, 0, 122, 92, 155, 159];
    /// let chunk = Chunk::try_from(&buffer[..])?;
    ///
    /// assert_eq!(chunk.chunk_id(), 5);
    /// # Ok(())
    /// # }
    /// ```
    pub fn chunk_id(&self) -> u16 {
        self.chunk_id
    }
    /// Return the CRC-32C value calculated from the first 16 bytes of the
    /// header.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryChunkFromSliceError;
    /// # fn main() -> Result<(), TryChunkFromSliceError> {
    /// use alpha_g_detector::padwing::Chunk;
    ///
    /// let buffer = [236, 40, 255, 135, 2, 0, 0, 0, 3, 0, 0, 1, 5, 0, 1, 0, 143, 203, 131, 81, 255, 0, 0, 0, 122, 92, 155, 159];
    /// let chunk = Chunk::try_from(&buffer[..])?;
    ///
    /// assert_eq!(chunk.header_crc32c(), 1367591823);
    /// # Ok(())
    /// # }
    /// ```
    pub fn header_crc32c(&self) -> u32 {
        let slice: Vec<u8> = self
            .device_id
            .to_le_bytes()
            .into_iter()
            .chain(self.packet_sequence.to_le_bytes())
            .chain(self.channel_sequence.to_le_bytes())
            .chain(self.channel_id.to_le_bytes())
            .chain(self.flags.to_le_bytes())
            .chain(self.chunk_id.to_le_bytes())
            .chain(u16::try_from(self.payload.len()).unwrap().to_le_bytes())
            .collect();
        !crc32c::crc32c(&slice[..])
    }
    /// Return the payload without padding bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryChunkFromSliceError;
    /// # fn main() -> Result<(), TryChunkFromSliceError> {
    /// use alpha_g_detector::padwing::Chunk;
    ///
    /// let buffer = [236, 40, 255, 135, 2, 0, 0, 0, 3, 0, 0, 1, 5, 0, 1, 0, 143, 203, 131, 81, 255, 0, 0, 0, 122, 92, 155, 159];
    /// let chunk = Chunk::try_from(&buffer[..])?;
    ///
    /// assert_eq!(chunk.payload(), [255]);
    /// # Ok(())
    /// # }
    /// ```
    pub fn payload(&self) -> &[u8] {
        &self.payload
    }
    /// Return the CRC-32C value calculated from the payload and the padding
    /// bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryChunkFromSliceError;
    /// # fn main() -> Result<(), TryChunkFromSliceError> {
    /// use alpha_g_detector::padwing::Chunk;
    ///
    /// let buffer = [236, 40, 255, 135, 2, 0, 0, 0, 3, 0, 0, 1, 5, 0, 1, 0, 143, 203, 131, 81, 255, 0, 0, 0, 122, 92, 155, 159];
    /// let chunk = Chunk::try_from(&buffer[..])?;
    ///
    /// assert_eq!(chunk.payload_crc32c(), 2677759098);
    /// # Ok(())
    /// # }
    /// ```
    pub fn payload_crc32c(&self) -> u32 {
        let padding = match self.payload.len() % 4 {
            0 => 0,
            r => 4 - r,
        };
        let slice: Vec<u8> = self
            .payload
            .clone()
            .into_iter()
            .chain(std::iter::repeat(0).take(padding))
            .collect();
        !crc32c::crc32c(&slice[..])
    }
}

impl TryFrom<&[u8]> for Chunk {
    type Error = TryChunkFromSliceError;

    // All fields are little endian
    fn try_from(slice: &[u8]) -> Result<Self, Self::Error> {
        // 20 -> Header
        // 1 -> Payload
        // 3 -> Padding 32 bit aligned
        // 4 -> Payload CRC-32C
        if slice.len() < 28 {
            return Err(Self::Error::IncompleteSlice {
                found: slice.len(),
                min_expected: 28,
            });
        }
        // payload has to be 32-bit aligned
        if slice.len() % 4 != 0 {
            return Err(Self::Error::IncompleteSlice {
                found: slice.len(),
                min_expected: slice.len() + 4 - slice.len() % 4,
            });
        }
        let device_id = slice[..4].try_into().unwrap();
        let device_id = u32::from_le_bytes(device_id);
        BoardId::try_from(device_id)?;
        let packet_sequence = slice[4..8].try_into().unwrap();
        let packet_sequence = u32::from_le_bytes(packet_sequence);
        let channel_sequence = slice[8..10].try_into().unwrap();
        let channel_sequence = u16::from_le_bytes(channel_sequence);
        let channel_id = slice[10];
        AfterId::try_from(channel_id)?;
        let flags = slice[11];
        if flags != 0 && flags != 1 {
            return Err(Self::Error::UnknownFlags { found: flags });
        }
        let chunk_id = slice[12..14].try_into().unwrap();
        let chunk_id = u16::from_le_bytes(chunk_id);
        let chunk_length = slice[14..16].try_into().unwrap();
        let chunk_length = u16::from_le_bytes(chunk_length).into();
        let max = slice.len() - 24;
        let min = max - 3;
        if chunk_length < min || chunk_length > max {
            return Err(Self::Error::BadChunkLength {
                found: chunk_length,
                min,
                max,
            });
        }
        let header_crc = slice[16..20].try_into().unwrap();
        let header_crc = u32::from_le_bytes(header_crc);
        let expected_crc = !crc32c::crc32c(&slice[0..16]);
        if header_crc != expected_crc {
            return Err(Self::Error::HeaderCRC32CMismatch {
                found: header_crc,
                expected: expected_crc,
            });
        }
        let payload = slice[20..][..chunk_length].to_vec();
        let padding = slice[20 + chunk_length..slice.len() - 4].to_vec();
        if padding.iter().any(|&x| x != 0) {
            return Err(Self::Error::ZeroMismatch { found: padding });
        }
        let payload_crc = slice[slice.len() - 4..].try_into().unwrap();
        let payload_crc = u32::from_le_bytes(payload_crc);
        let expected_crc = !crc32c::crc32c(&slice[20..slice.len() - 4]);
        if payload_crc != expected_crc {
            return Err(Self::Error::PayloadCRC32CMismatch {
                found: payload_crc,
                expected: expected_crc,
            });
        }

        Ok(Self {
            device_id,
            packet_sequence,
            channel_sequence,
            channel_id,
            flags,
            chunk_id,
            payload,
        })
    }
}

/// The error type returned when conversion from unsigned integer to
/// [`Compression`] fails.
#[derive(Error, Debug)]
#[error("unknown conversion from unsigned `{input}` to Compression")]
pub struct TryCompressionFromUnsignedError {
    input: u8,
}

/// Compression types available for the PadWing boards event data.
#[derive(Clone, Copy, Debug)]
pub enum Compression {
    /// Uncompressed raw data. Any SCA channel data is sent without compression,
    /// in 16-bit signed format.
    Raw,
}
impl TryFrom<u8> for Compression {
    type Error = TryCompressionFromUnsignedError;

    fn try_from(num: u8) -> Result<Self, Self::Error> {
        match num {
            0 => Ok(Self::Raw),
            _ => Err(Self::Error { input: num }),
        }
    }
}

/// The error type returned when conversion from unsigned integer to [`Trigger`]
/// fails.
#[derive(Error, Debug)]
#[error("unknown conversion from unsigned `{input}` to Trigger")]
pub struct TryTriggerFromUnsignedError {
    input: u8,
}

/// Trigger sources available that cause an event to be captured.
#[derive(Clone, Copy, Debug)]
pub enum Trigger {
    /// Trigger came from the external pin on the PadWing board.
    External,
    /// Trigger came from the NIOS via user request.
    Manual,
    /// Trigger came from the internal pulser.
    InternalPulse,
}
impl TryFrom<u8> for Trigger {
    type Error = TryTriggerFromUnsignedError;

    fn try_from(num: u8) -> Result<Self, Self::Error> {
        match num {
            0 => Ok(Self::External),
            1 => Ok(Self::Manual),
            3 => Ok(Self::InternalPulse),
            _ => Err(Self::Error { input: num }),
        }
    }
}

/// The error type returned when conversion from unsigned integer to
/// [`ChannelId`] fails.
#[derive(Error, Debug)]
#[error("unknown conversion from unsigned `{input}` to ChannelId")]
pub struct TryChannelIdFromUnsignedError {
    input: u16,
}

/// Channel ID that corresponds to "Reset states" of an AFTER chip.
///
/// I don't understand what these channels are. They correspond to the readout
/// indices of 1, 2, and 3. These are currently not used for anything, they are
/// even suppressed from the PWB output. They are added here for completeness,
/// in case they are ever used in the future.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
// The internal u16 does NOT correspond to the readout index.
// It corresponds to the channel index 1, 2, or 3.
pub struct ResetChannelId(u16);
impl TryFrom<u16> for ResetChannelId {
    type Error = TryChannelIdFromUnsignedError;

    /// Convert from the integer representation of the channel index i.e. `1`,
    /// `2`, or `3` (NOT the readout index) to a [`ResetChannelId`].
    fn try_from(num: u16) -> Result<Self, Self::Error> {
        match num {
            1..=3 => Ok(Self(num)),
            _ => Err(Self::Error { input: num }),
        }
    }
}

/// Channel ID that corresponds to Fixed Pattern Noise channels.
///
/// Every AFTER chip has 4 FPN channels, with readout indices 16, 29, 54, and
/// 67.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
// The internal u16 does NOT correspond to the readout index.
// It corresponds to the channel index 1, 2, 3, or 4.
pub struct FpnChannelId(u16);
impl TryFrom<u16> for FpnChannelId {
    type Error = TryChannelIdFromUnsignedError;

    /// Convert from the integer representation of the channel index i.e. `1`,
    /// `2`, `3`, or `4` (NOT the readout index) to a [`FpnChannelId`].
    fn try_from(num: u16) -> Result<Self, Self::Error> {
        match num {
            1..=4 => Ok(Self(num)),
            _ => Err(Self::Error { input: num }),
        }
    }
}

/// Channel ID that corresponds to cathode pads in the radial Time Projection
/// Chamber.
// The internal u16 does NOT correspond to the readout index.
// It corresponds to the channel index 1, 2, 3, ..., 72.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct PadChannelId(u16);
impl TryFrom<u16> for PadChannelId {
    type Error = TryChannelIdFromUnsignedError;

    /// Convert from the integer representation of the channel index i.e. `1`,
    /// `2`, `3`, ..., `72` (NOT the readout index) to a [`PadChannelId`].
    fn try_from(num: u16) -> Result<Self, Self::Error> {
        match num {
            1..=72 => Ok(Self(num)),
            _ => Err(Self::Error { input: num }),
        }
    }
}

/// Channel ID in a PadWing board.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ChannelId {
    Reset(ResetChannelId),
    /// Fixed pattern noise channel.
    Fpn(FpnChannelId),
    /// Cathode pad channel.
    Pad(PadChannelId),
}
// This TryFrom implementation is possible because all revisions of the boards
// have the same conversion from readout_index -> channel_index
// If this changes with some future revision you will need to do the following:
// Remove this TryFrom implementation for ChannelId.
// The TryFrom implementation for the Reset, FPN, and Pad channels should still
// hold.
// You will need to handle each readout_index -> channel_index conversion in
// the PwbPacket::try_from() implementations directly depending on the
// revision.
impl TryFrom<u16> for ChannelId {
    type Error = TryChannelIdFromUnsignedError;

    /// Perform the conversion from readout index of PWB channel (`1..=79`).
    fn try_from(readout_index: u16) -> Result<Self, Self::Error> {
        match readout_index {
            1..=3 => Ok(ChannelId::Reset(ResetChannelId::try_from(readout_index)?)),
            16 => Ok(ChannelId::Fpn(FpnChannelId::try_from(1)?)),
            29 => Ok(ChannelId::Fpn(FpnChannelId::try_from(2)?)),
            54 => Ok(ChannelId::Fpn(FpnChannelId::try_from(3)?)),
            67 => Ok(ChannelId::Fpn(FpnChannelId::try_from(4)?)),
            4..=79 => Ok(ChannelId::Pad(PadChannelId::try_from({
                let i = readout_index;
                i - (i > 16) as u16 - (i > 29) as u16 - (i > 54) as u16 - (i > 67) as u16 - 3
            })?)),
            _ => Err(TryChannelIdFromUnsignedError {
                input: readout_index,
            }),
        }
    }
}

/// The error type returned when conversion from
/// [`&[u8]`](https://doc.rust-lang.org/std/primitive.slice.html) to
/// [`PwbPacket`] fails.
#[derive(Error, Debug)]
pub enum TryPwbPacketFromSliceError {
    /// The input slice is not long enough to contain a complete packet.
    #[error("incomplete slice (expected at least `{min_expected}` bytes, found `{found}`)")]
    IncompleteSlice { found: usize, min_expected: usize },
    /// Unknown packet version
    #[error("unknown packet version `{found}`")]
    UnknownVersion { found: u8 },
    /// ASCII representation of AFTER chip doesn't match any known [`AfterId`].
    #[error("unknown AFTER id")]
    UnknownAfterId(#[from] ParseAfterIdError),
    /// Integer representation of compression doesn't match any known
    /// [`Compression`].
    #[error("unknown compression")]
    UnknownCompression(#[from] TryCompressionFromUnsignedError),
    /// Integer representation of compression doesn't match any known
    /// [`Trigger`].
    #[error("unknown trigger source")]
    UnknownTrigger(#[from] TryTriggerFromUnsignedError),
    /// MAC address doesn't map to any known [`BoardId`].
    #[error("unknown mac address")]
    UnknownMac(#[from] TryBoardIdFromMacAddressError),
    /// Non-zero value found in bytes meant to be fixed to `0`.
    #[error("zero-bytes mismatch (found `{found:?}`)")]
    ZeroMismatch { found: [u8; 2] },
    /// The value of `last_sca_cell` is larger than `511`. There are only `511`
    /// SCA cells per channel.
    #[error("bad last_sca_cell `{found}`")]
    BadLastScaCell { found: u16 },
    /// The value of `requested_samples` is larger than `511`. There are
    /// only `511` SCA cells per channel.
    #[error("bad requested_samples `{found}`")]
    BadScaSamples { found: usize },
    /// The 79th bit in channels_sent bit mask is set. There are only 79
    /// channels i.e. 78th is maximum possible bit.
    #[error("bad channels sent bit mask")]
    BadScaChannelsSent,
    /// The 79th bit in channels_over_threshold bit mask is set. There are only
    /// 79 channels i.e. 78th is maximum possible bit.
    #[error("bad channels over threshold bit mask")]
    BadScaChannelsThreshold,
    /// Integer representation of a channel ID in the waveforms data doesn't
    /// match any known [`ChannelId`]
    #[error("unknown channel id")]
    UnknownChannelId(#[from] TryChannelIdFromUnsignedError),
    /// Channel ID in the waveforms data doesn't match the expected channels
    /// sent.
    #[error("channel id mismatch (expected `{expected:?}`, found `{found:?}`)")]
    ChannelIdMismatch {
        found: ChannelId,
        expected: ChannelId,
    },
    /// The number of waveform samples for a channel doesn't match the
    /// requested samples.
    #[error("number of samples mismatch (expected `{expected}`, found `{found}`)")]
    NumberOfSamplesMismatch { found: usize, expected: usize },
    /// The end-of-data marker doesn't match the expected `0xCCCCCCCC`.
    #[error("bad end-of-data marker `{found:?}`")]
    BadEndOfDataMarker { found: [u8; 4] },
}

/// Version 2 of a PWB data packet.
///
/// A PWB packet represents the data collected from the channels of an
/// individual AFTER chip in a PadWing board. A PWB data bank in a MIDAS file
/// contains a single [`Chunk`]; the PWB packet is formed from the payload of
/// all chunks sent through the same device/channel. The binary representation
/// of a [`PwbV2Packet`] is shown below. All multi-byte fields are
/// little-endian:
///
/// <center>
///
/// |Byte(s)|Description|
/// |:-:|:-:|
/// |0|Fixed to 2|
/// |1|AFTER ID|
/// |2|Compression type|
/// |3|Trigger source|
/// |4-9|MAC address|
/// |10-11|Trigger delay|
/// |12-17|Trigger timestamp|
/// |18-19|Fixed to 0|
/// |20-21|SCA last cell|
/// |22-23|Requested samples|
/// |24-33|Sent channels bitmask|
/// |34-43|Channels over threshold bitmask|
/// |44-47|Event counter|
/// |48-49|FIFO max depth|
/// |50|Event descriptor write depth|
/// |51|Event descriptor read depth|
/// |...|Waveforms|
///
/// </center>
#[derive(Clone, Debug)]
pub struct PwbV2Packet {
    after_id: AfterId,
    compression: Compression,
    trigger_source: Trigger,
    board_id: BoardId,
    trigger_delay: u16,
    trigger_timestamp: u64,
    last_sca_cell: u16,
    requested_samples: usize,
    channels_sent: Vec<ChannelId>,
    channels_over_threshold: Vec<ChannelId>,
    event_counter: u32,
    fifo_max_depth: u16,
    event_descriptor_write_depth: u8,
    event_descriptor_read_depth: u8,
    // In the constructor, just check that the data has the appropriate format.
    // But store it as a Vec<i16> and return the desired waveform on demand.
    data: Vec<i16>,
}

impl fmt::Display for PwbV2Packet {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "Format revision: {}", self.packet_version())?;
        writeln!(f, "AFTER ID: {:?}", self.after_id)?;
        writeln!(f, "Compression: {:?}", self.compression)?;
        writeln!(f, "Trigger source: {:?}", self.trigger_source)?;
        let mac_address = self.board_id.mac_address();
        writeln!(f, "MAC address: {mac_address:?}")?;
        writeln!(f, "Trigger delay: {}", self.trigger_delay)?;
        writeln!(f, "Trigger timestamp: {}", self.trigger_timestamp)?;
        writeln!(f, "Last SCA cell: {}", self.last_sca_cell)?;
        writeln!(f, "Requested samples: {}", self.requested_samples)?;
        let channels_sent: Vec<u16> = (1..=79)
            .filter(|i| {
                let channel = ChannelId::try_from(*i).unwrap();
                self.channels_sent.contains(&channel)
            })
            .collect();
        writeln!(f, "Channels sent: {channels_sent:?}")?;
        let channels_over_threshold: Vec<u16> = (1..=79)
            .filter(|i| {
                let channel = ChannelId::try_from(*i).unwrap();
                self.channels_over_threshold.contains(&channel)
            })
            .collect();
        writeln!(f, "Channels over threshold: {channels_over_threshold:?}")?;
        writeln!(f, "Event counter: {}", self.event_counter)?;
        writeln!(f, "FIFO max depth: {}", self.fifo_max_depth)?;
        writeln!(
            f,
            "Event descriptor write depth: {}",
            self.event_descriptor_write_depth
        )?;
        write!(
            f,
            "Event descriptor read depth: {}",
            self.event_descriptor_read_depth
        )?;

        Ok(())
    }
}

impl PwbV2Packet {
    /// Return the packet version i.e. format revision. For [`PwbV2Packet`] it
    /// is fixed to `2`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::PwbV2Packet;
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbV2Packet::try_from(&payload[..])?;
    ///
    /// assert_eq!(packet.packet_version(), 2);
    /// # Ok(())
    /// # }
    /// ```
    pub fn packet_version(&self) -> u8 {
        2
    }
    /// Return the [`AfterId`] of the chip in the PadWing board from which the
    /// packet was generated.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::{AfterId, PwbV2Packet};
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbV2Packet::try_from(&payload[..])?;
    ///
    /// assert_eq!(packet.after_id(), AfterId::A);
    /// # Ok(())
    /// # }
    /// ```
    pub fn after_id(&self) -> AfterId {
        self.after_id
    }
    /// Return the [`Compression`] used in the original binary packet data.
    /// This is only useful as a sanity check, any waveform returned by a
    /// [`PwbV2Packet`] is already decompressed and in raw format as a slice of
    /// [`i16`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::{Compression, PwbV2Packet};
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbV2Packet::try_from(&payload[..])?;
    ///
    /// assert!(matches!(packet.compression(), Compression::Raw));
    /// # Ok(())
    /// # }
    /// ```
    pub fn compression(&self) -> Compression {
        self.compression
    }
    /// Return the [`Trigger`] that caused the event to be captured.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::{Trigger, PwbV2Packet};
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbV2Packet::try_from(&payload[..])?;
    ///
    /// assert!(matches!(packet.trigger_source(), Trigger::External));
    /// # Ok(())
    /// # }
    /// ```
    pub fn trigger_source(&self) -> Trigger {
        self.trigger_source
    }
    /// Return the [`BoardId`] of the PadWing board from which the packet was
    /// generated.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use alpha_g_detector::padwing::{BoardId, PwbV2Packet};
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbV2Packet::try_from(&payload[..])?;
    ///
    /// assert_eq!(packet.board_id(), BoardId::try_from("00")?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn board_id(&self) -> BoardId {
        self.board_id
    }
    /// Indicates how long the trigger was delayed from initial request, in
    /// order to allow the SCA data to fill up post-trigger.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::PwbV2Packet;
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbV2Packet::try_from(&payload[..])?;
    ///
    /// assert_eq!(packet.trigger_delay(), 1);
    /// # Ok(())
    /// # }
    /// ```
    pub fn trigger_delay(&self) -> u16 {
        self.trigger_delay
    }
    /// Indicates when the trigger was accepted. The actual timestamp of the
    /// trigger signal is given by `trigger_timestamp - trigger_delay`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::PwbV2Packet;
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbV2Packet::try_from(&payload[..])?;
    ///
    /// assert_eq!(packet.trigger_timestamp(), 2);
    /// # Ok(())
    /// # }
    /// ```
    pub fn trigger_timestamp(&self) -> u64 {
        self.trigger_timestamp
    }
    /// Indicates the last cell written to by the SCA. As there are only `511`
    /// SCA cells per channel, this function is guaranteed to return a value in
    /// the range `1..=511`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::PwbV2Packet;
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbV2Packet::try_from(&payload[..])?;
    ///
    /// assert_eq!(packet.last_sca_cell(), 100);
    /// # Ok(())
    /// # }
    /// ```
    pub fn last_sca_cell(&self) -> u16 {
        self.last_sca_cell
    }
    /// Return the number of requested waveform samples per channel. If a
    /// channel is sent, it is guaranteed to have this number of samples.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::PwbV2Packet;
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbV2Packet::try_from(&payload[..])?;
    ///
    /// assert_eq!(packet.requested_samples(), 511);
    /// # Ok(())
    /// # }
    /// ```
    pub fn requested_samples(&self) -> usize {
        self.requested_samples
    }
    /// Return the [`ChannelId`] of all the channels that sent data for this
    /// event.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::PwbV2Packet;
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbV2Packet::try_from(&payload[..])?;
    ///
    /// assert!(packet.channels_sent().is_empty());
    /// # Ok(())
    /// # }
    /// ```
    pub fn channels_sent(&self) -> &[ChannelId] {
        &self.channels_sent
    }
    /// Return the [`ChannelId`] of all the channels with a waveform that went
    /// over the threshold level. It is possible for a channel to not cross the
    /// threshold level and yet still be sent e.g. when a channel is `FORCED`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::{ChannelId, PwbV2Packet};
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbV2Packet::try_from(&payload[..])?;
    ///
    /// assert_eq!(packet.channels_over_threshold(), &[ChannelId::try_from(3)?]);
    /// # Ok(())
    /// # }
    /// ```
    pub fn channels_over_threshold(&self) -> &[ChannelId] {
        &self.channels_over_threshold
    }
    /// Return a counter that increments on each successful trigger received and
    /// processed.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::PwbV2Packet;
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbV2Packet::try_from(&payload[..])?;
    ///
    /// assert_eq!(packet.event_counter(), 5);
    /// # Ok(())
    /// # }
    /// ```
    pub fn event_counter(&self) -> u32 {
        self.event_counter
    }
    /// Indicates the maximum depth the SCA FIFO reached while streaming into
    /// DDR memory.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::PwbV2Packet;
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbV2Packet::try_from(&payload[..])?;
    ///
    /// assert_eq!(packet.fifo_max_depth(), 200);
    /// # Ok(())
    /// # }
    /// ```
    pub fn fifo_max_depth(&self) -> u16 {
        self.fifo_max_depth
    }
    /// Indicates the depth of the event descriptor on its write side at the
    /// time the event was written.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::PwbV2Packet;
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbV2Packet::try_from(&payload[..])?;
    ///
    /// assert_eq!(packet.event_descriptor_write_depth(), 6);
    /// # Ok(())
    /// # }
    /// ```
    pub fn event_descriptor_write_depth(&self) -> u8 {
        self.event_descriptor_write_depth
    }
    /// Indicates the depth of the event descriptor on its read side at the time
    /// the event was read out.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::PwbV2Packet;
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbV2Packet::try_from(&payload[..])?;
    ///
    /// assert_eq!(packet.event_descriptor_read_depth(), 7);
    /// # Ok(())
    /// # }
    /// ```
    pub fn event_descriptor_read_depth(&self) -> u8 {
        self.event_descriptor_read_depth
    }
    /// Return the digitized waveform samples received by a channel in a PadWing
    /// board. Return [`None`] if the given channel was not sent.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::{ChannelId, PwbV2Packet};
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbV2Packet::try_from(&payload[..])?;
    ///
    /// assert!(packet.waveform_at(ChannelId::try_from(10)?).is_none());
    /// # Ok(())
    /// # }
    /// ```
    pub fn waveform_at(&self, channel: ChannelId) -> Option<&[i16]> {
        if let Some(index) = self.channels_sent.iter().position(|c| *c == channel) {
            let samples_per_channel = if self.requested_samples % 2 == 0 {
                2 + self.requested_samples
            } else {
                2 + self.requested_samples + 1
            };
            let index = samples_per_channel * index;
            Some(&self.data[index + 2..][..self.requested_samples])
        } else {
            None
        }
    }
}

impl TryFrom<&[u8]> for PwbV2Packet {
    type Error = TryPwbPacketFromSliceError;

    // All fields are little endian
    fn try_from(slice: &[u8]) -> Result<Self, Self::Error> {
        if slice.len() < 56 {
            return Err(Self::Error::IncompleteSlice {
                found: slice.len(),
                min_expected: 56,
            });
        }

        if slice[0] != 2 {
            return Err(Self::Error::UnknownVersion { found: slice[0] });
        }
        let after_id = AfterId::try_from(slice[1] as char)?;
        let compression = Compression::try_from(slice[2])?;
        let trigger_source = Trigger::try_from(slice[3])?;
        let board_id: [u8; 6] = slice[4..10].try_into().unwrap();
        let board_id = BoardId::try_from(board_id)?;
        let trigger_delay = slice[10..12].try_into().unwrap();
        let trigger_delay = u16::from_le_bytes(trigger_delay);
        if slice[18..20] != [0, 0] {
            return Err(Self::Error::ZeroMismatch {
                found: slice[18..20].try_into().unwrap(),
            });
        }
        let trigger_timestamp = slice[12..20].try_into().unwrap();
        let trigger_timestamp = u64::from_le_bytes(trigger_timestamp);
        let last_sca_cell = slice[20..22].try_into().unwrap();
        let last_sca_cell = u16::from_le_bytes(last_sca_cell);
        if last_sca_cell > 511 {
            return Err(Self::Error::BadLastScaCell {
                found: last_sca_cell,
            });
        }
        let requested_samples = slice[22..24].try_into().unwrap();
        let requested_samples = u16::from_le_bytes(requested_samples).into();
        if requested_samples > 511 {
            return Err(Self::Error::BadScaSamples {
                found: requested_samples,
            });
        }
        if slice[33] & 128 != 0 {
            return Err(Self::Error::BadScaChannelsSent);
        }
        let mut num = {
            let mut array = [0; 16];
            array[..10].copy_from_slice(&slice[24..34]);
            u128::from_le_bytes(array)
        };
        let mut channels_sent: Vec<u16> = Vec::new();
        while num != 0 {
            let bit = num.leading_zeros();
            channels_sent.push((127 - bit).try_into().unwrap());
            num ^= 1 << (127 - bit);
        }
        let channels_sent: Vec<ChannelId> = channels_sent
            .into_iter()
            .rev()
            .map(|index| ChannelId::try_from(index + 1).unwrap())
            .collect();
        if slice[43] & 128 != 0 {
            return Err(Self::Error::BadScaChannelsThreshold);
        }
        let mut num = {
            let mut array = [0; 16];
            array[..10].copy_from_slice(&slice[34..44]);
            u128::from_le_bytes(array)
        };
        let mut channels_over_threshold: Vec<u16> = Vec::new();
        while num != 0 {
            let bit = num.leading_zeros();
            channels_over_threshold.push((127 - bit).try_into().unwrap());
            num ^= 1 << (127 - bit);
        }
        let channels_over_threshold: Vec<ChannelId> = channels_over_threshold
            .into_iter()
            .rev()
            .map(|index| ChannelId::try_from(index + 1).unwrap())
            .collect();
        let event_counter = slice[44..48].try_into().unwrap();
        let event_counter = u32::from_le_bytes(event_counter);
        let fifo_max_depth = slice[48..50].try_into().unwrap();
        let fifo_max_depth = u16::from_le_bytes(fifo_max_depth);
        let event_descriptor_write_depth = slice[50];
        let event_descriptor_read_depth = slice[51];
        let data = &slice[52..];
        let bytes_per_channel = if requested_samples % 2 == 0 {
            4 + 2 * requested_samples
        } else {
            4 + 2 * requested_samples + 2
        };
        if bytes_per_channel * channels_sent.len() + 4 != data.len() {
            return Err(Self::Error::IncompleteSlice {
                found: slice.len(),
                min_expected: 56 + bytes_per_channel * channels_sent.len(),
            });
        }
        for (index, &channel) in channels_sent.iter().enumerate() {
            let index = bytes_per_channel * index;
            let found_channel = data[index..][..2].try_into().unwrap();
            let found_channel = u16::from_le_bytes(found_channel);
            let found_channel = ChannelId::try_from(found_channel)?;
            if found_channel != channel {
                return Err(Self::Error::ChannelIdMismatch {
                    found: found_channel,
                    expected: channel,
                });
            }
            let found_size = data[index + 2..][..2].try_into().unwrap();
            let found_size = u16::from_le_bytes(found_size).into();
            if found_size != requested_samples {
                return Err(Self::Error::NumberOfSamplesMismatch {
                    found: found_size,
                    expected: requested_samples,
                });
            }
            if requested_samples % 2 != 0
                && data[index + 4 + 2 * requested_samples..][..2] != [0, 0]
            {
                return Err(Self::Error::ZeroMismatch {
                    found: data[index + 4 + 2 * requested_samples..][..2]
                        .try_into()
                        .unwrap(),
                });
            }
        }
        if data[data.len() - 4..] != [204, 204, 204, 204] {
            return Err(Self::Error::BadEndOfDataMarker {
                found: data[data.len() - 4..].try_into().unwrap(),
            });
        }
        let data = data
            .chunks_exact(2)
            .map(|s| {
                let s = s.try_into().unwrap();
                i16::from_le_bytes(s)
            })
            .collect();
        Ok(Self {
            after_id,
            compression,
            trigger_source,
            board_id,
            trigger_delay,
            trigger_timestamp,
            last_sca_cell,
            requested_samples,
            channels_sent,
            channels_over_threshold,
            event_counter,
            fifo_max_depth,
            event_descriptor_write_depth,
            event_descriptor_read_depth,
            data,
        })
    }
}

/// The error type returned when conversion from [`Vec<Chunk>`] to [`PwbPacket`]
/// fails.
#[derive(Error, Debug)]
pub enum TryPwbPacketFromChunksError {
    /// All [`Chunk`]s do not belong to the same device.
    // `Expected` corresponds to that with chunk_id = 0
    #[error("device id mismatch (expected `{expected:?}`, found `{found:?}`)")]
    DeviceIdMismatch { found: BoardId, expected: BoardId },
    /// All [`Chunk`]s do not belong to the same channel within a device.
    // `Expected` corresponds to that with chunk_id = 0
    #[error("channel id mismatch (expected `{expected:?}`, found `{found:?}`)")]
    ChannelIdMismatch { found: AfterId, expected: AfterId },
    /// An intermediate [`Chunk`] is missing from a message.
    #[error("missing chunk with chunk id `{position}`")]
    MissingChunk { position: usize },
    /// The last [`Chunk`] in a message does not have the end_of_message flag.
    #[error("last chunk does not have the `end_of_message` flag")]
    MissingEndOfMessageChunk,
    /// An intermediate [`Chunk`] contains the end_of_message flag.
    #[error("unexpected `end_of_message` found at chunk id `{position}`")]
    MisplacedEndOfMessageChunk { position: usize },
    /// The payload from an intermediate [`Chunk`] has a length different than
    /// expected.
    // All chunks (except last one) need to have the same chunk_length
    #[error("payload length mismatch (expected `{expected}`, found `{found}`)")]
    PayloadLengthMismatch { found: usize, expected: usize },
    /// The concatenated payload from all chunks is not a correct [`PwbPacket`].
    #[error("bad payload")]
    BadPayload(#[from] TryPwbPacketFromSliceError),
}

impl TryFrom<Vec<Chunk>> for PwbV2Packet {
    type Error = TryPwbPacketFromChunksError;

    fn try_from(mut chunks: Vec<Chunk>) -> Result<Self, Self::Error> {
        if chunks.is_empty() {
            return Err(Self::Error::MissingChunk { position: 0 });
        }
        if let Some(index) = chunks
            .iter()
            .position(|c| c.board_id() != chunks[0].board_id())
        {
            return Err(Self::Error::DeviceIdMismatch {
                found: chunks[index].board_id(),
                expected: chunks[0].board_id(),
            });
        }
        if let Some(index) = chunks
            .iter()
            .position(|c| c.after_id() != chunks[0].after_id())
        {
            return Err(Self::Error::ChannelIdMismatch {
                found: chunks[index].after_id(),
                expected: chunks[0].after_id(),
            });
        }
        chunks.sort_unstable_by_key(|c| c.chunk_id);
        if let Some(position) = chunks
            .iter()
            .enumerate()
            .position(|(i, c)| usize::from(c.chunk_id) != i)
        {
            return Err(Self::Error::MissingChunk { position });
        }
        if !chunks.last().unwrap().is_end_of_message() {
            return Err(Self::Error::MissingEndOfMessageChunk);
        }
        if let Some(position) = chunks
            .iter()
            .take(chunks.len() - 1)
            .position(|c| c.is_end_of_message())
        {
            return Err(Self::Error::MisplacedEndOfMessageChunk { position });
        }
        if let Some(index) = chunks
            .iter()
            .take(chunks.len() - 1)
            .position(|c| c.payload().len() != chunks[0].payload().len())
        {
            return Err(Self::Error::PayloadLengthMismatch {
                found: chunks[index].payload().len(),
                expected: chunks[0].payload().len(),
            });
        }
        let max_items = chunks[0].payload().len() * chunks.len();
        let payload = chunks
            .into_iter()
            .fold(Vec::with_capacity(max_items), |mut acc, item| {
                acc.extend_from_slice(&item.payload);
                acc
            });
        Ok(PwbV2Packet::try_from(&payload[..])?)
    }
}

/// PWB data packet.
///
/// This enum can currently contain only a [`PwbV2Packet`]. See its
/// documentation for more details.
#[derive(Clone, Debug)]
pub enum PwbPacket {
    /// Version 2 of a PWB packet.
    V2(PwbV2Packet),
}

impl fmt::Display for PwbPacket {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::V2(packet) => write!(f, "{packet}"),
        }
    }
}

impl PwbPacket {
    /// Return the packet version i.e. format revision.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::PwbPacket;
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbPacket::try_from(&payload[..])?;
    ///
    /// assert_eq!(packet.packet_version(), 2);
    /// # Ok(())
    /// # }
    /// ```
    pub fn packet_version(&self) -> u8 {
        match self {
            Self::V2(packet) => packet.packet_version(),
        }
    }
    /// Return the [`AfterId`] of the chip in the PadWing board from which the
    /// packet was generated.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::{AfterId, PwbPacket};
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbPacket::try_from(&payload[..])?;
    ///
    /// assert_eq!(packet.after_id(), AfterId::A);
    /// # Ok(())
    /// # }
    /// ```
    pub fn after_id(&self) -> AfterId {
        match self {
            Self::V2(packet) => packet.after_id(),
        }
    }
    /// Return the [`Compression`] used in the original binary packet data.
    /// This is only useful as a sanity check, any waveform returned by a
    /// [`PwbPacket`] is already decompressed and in raw format as a slice of
    /// [`i16`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::{Compression, PwbPacket};
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbPacket::try_from(&payload[..])?;
    ///
    /// assert!(matches!(packet.compression(), Compression::Raw));
    /// # Ok(())
    /// # }
    /// ```
    pub fn compression(&self) -> Compression {
        match self {
            Self::V2(packet) => packet.compression(),
        }
    }
    /// Return the [`Trigger`] that caused the event to be captured.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::{Trigger, PwbPacket};
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbPacket::try_from(&payload[..])?;
    ///
    /// assert!(matches!(packet.trigger_source(), Trigger::External));
    /// # Ok(())
    /// # }
    /// ```
    pub fn trigger_source(&self) -> Trigger {
        match self {
            Self::V2(packet) => packet.trigger_source(),
        }
    }
    /// Return the [`BoardId`] of the PadWing board from which the packet was
    /// generated.
    ///
    /// # Examples
    ///
    /// ```
    /// # use std::error::Error;
    /// # fn main() -> Result<(), Box<dyn Error>> {
    /// use alpha_g_detector::padwing::{BoardId, PwbPacket};
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbPacket::try_from(&payload[..])?;
    ///
    /// assert_eq!(packet.board_id(), BoardId::try_from("00")?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn board_id(&self) -> BoardId {
        match self {
            Self::V2(packet) => packet.board_id(),
        }
    }
    /// Indicates how long the trigger was delayed from initial request, in
    /// order to allow the SCA data to fill up post-trigger.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::PwbPacket;
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbPacket::try_from(&payload[..])?;
    ///
    /// assert_eq!(packet.trigger_delay(), 1);
    /// # Ok(())
    /// # }
    /// ```
    pub fn trigger_delay(&self) -> u16 {
        match self {
            Self::V2(packet) => packet.trigger_delay(),
        }
    }
    /// Indicates when the trigger was accepted. The actual timestamp of the
    /// trigger signal is given by `trigger_timestamp - trigger_delay`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::PwbPacket;
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbPacket::try_from(&payload[..])?;
    ///
    /// assert_eq!(packet.trigger_timestamp(), 2);
    /// # Ok(())
    /// # }
    /// ```
    pub fn trigger_timestamp(&self) -> u64 {
        match self {
            Self::V2(packet) => packet.trigger_timestamp(),
        }
    }
    /// Indicates the last cell written to by the SCA. As there are only `511`
    /// SCA cells per channel, this function is guaranteed to return a value in
    /// the range `1..=511`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::PwbPacket;
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbPacket::try_from(&payload[..])?;
    ///
    /// assert_eq!(packet.last_sca_cell(), 100);
    /// # Ok(())
    /// # }
    /// ```
    pub fn last_sca_cell(&self) -> u16 {
        match self {
            Self::V2(packet) => packet.last_sca_cell(),
        }
    }
    /// Return the number of requested waveform samples per channel. If a
    /// channel is sent, it is guaranteed to have this number of samples.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::PwbPacket;
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbPacket::try_from(&payload[..])?;
    ///
    /// assert_eq!(packet.requested_samples(), 511);
    /// # Ok(())
    /// # }
    /// ```
    pub fn requested_samples(&self) -> usize {
        match self {
            Self::V2(packet) => packet.requested_samples(),
        }
    }
    /// Return the [`ChannelId`] of all the channels that sent data for this
    /// event.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::PwbPacket;
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbPacket::try_from(&payload[..])?;
    ///
    /// assert!(packet.channels_sent().is_empty());
    /// # Ok(())
    /// # }
    /// ```
    pub fn channels_sent(&self) -> &[ChannelId] {
        match self {
            Self::V2(packet) => packet.channels_sent(),
        }
    }
    /// Return the [`ChannelId`] of all the channels with a waveform that went
    /// over the threshold level. It is possible for a channel to not cross the
    /// threshold level and yet still be sent e.g. when a channel is `FORCED`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::{ChannelId, PwbPacket};
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbPacket::try_from(&payload[..])?;
    ///
    /// assert_eq!(packet.channels_over_threshold(), &[ChannelId::try_from(3)?]);
    /// # Ok(())
    /// # }
    /// ```
    pub fn channels_over_threshold(&self) -> &[ChannelId] {
        match self {
            Self::V2(packet) => packet.channels_over_threshold(),
        }
    }
    /// Return a counter that increments on each successful trigger received and
    /// processed. Return [`None`] if this is a version 0 or 1 packet (these
    /// don't contain this field).
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::PwbPacket;
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbPacket::try_from(&payload[..])?;
    ///
    /// assert_eq!(packet.event_counter(), Some(5));
    /// # Ok(())
    /// # }
    /// ```
    pub fn event_counter(&self) -> Option<u32> {
        match self {
            Self::V2(packet) => Some(packet.event_counter()),
        }
    }
    /// Indicates the maximum depth the SCA FIFO reached while streaming into
    /// DDR memory. Return [`None`] if this is a version 0 or 1 packet (these
    /// don't contain this field).
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::PwbPacket;
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbPacket::try_from(&payload[..])?;
    ///
    /// assert_eq!(packet.fifo_max_depth(), Some(200));
    /// # Ok(())
    /// # }
    /// ```
    pub fn fifo_max_depth(&self) -> Option<u16> {
        match self {
            Self::V2(packet) => Some(packet.fifo_max_depth()),
        }
    }
    /// Indicates the depth of the event descriptor on its write side at the
    /// time the event was written. Return [`None`] if this is a version 0 or 1
    /// packet (these don't contain this field).
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::PwbPacket;
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbPacket::try_from(&payload[..])?;
    ///
    /// assert_eq!(packet.event_descriptor_write_depth(), Some(6));
    /// # Ok(())
    /// # }
    /// ```
    pub fn event_descriptor_write_depth(&self) -> Option<u8> {
        match self {
            Self::V2(packet) => Some(packet.event_descriptor_write_depth()),
        }
    }
    /// Indicates the depth of the event descriptor on its read side at the time
    /// the event was read out. Return [`None`] if this is a version 0 or 1
    /// packet (these don't contain this field).
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::PwbPacket;
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbPacket::try_from(&payload[..])?;
    ///
    /// assert_eq!(packet.event_descriptor_read_depth(), Some(7));
    /// # Ok(())
    /// # }
    /// ```
    pub fn event_descriptor_read_depth(&self) -> Option<u8> {
        match self {
            Self::V2(packet) => Some(packet.event_descriptor_read_depth()),
        }
    }
    /// Return the digitized waveform samples received by a channel in a PadWing
    /// board. Return [`None`] if the given channel was not sent.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::{ChannelId, PwbPacket};
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbPacket::try_from(&payload[..])?;
    ///
    /// assert!(packet.waveform_at(ChannelId::try_from(10)?).is_none());
    /// # Ok(())
    /// # }
    /// ```
    pub fn waveform_at(&self, channel: ChannelId) -> Option<&[i16]> {
        match self {
            Self::V2(packet) => packet.waveform_at(channel),
        }
    }
    /// Return [`true`] if this PWB packet is a [`PwbV2Packet`], and [`false`]
    /// otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::padwing::TryPwbPacketFromSliceError;
    /// # fn main() -> Result<(), TryPwbPacketFromSliceError> {
    /// use alpha_g_detector::padwing::PwbPacket;
    ///
    /// let payload = [2, 65, 0, 0, 236, 40, 255, 135, 84, 2, 1, 0, 2, 0, 0, 0, 0, 0, 0, 0, 100, 0, 255, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 200, 0, 6, 7, 204, 204, 204, 204];
    /// let packet = PwbPacket::try_from(&payload[..])?;
    ///
    /// assert!(packet.is_v2());
    /// # Ok(())
    /// # }
    /// ```
    pub fn is_v2(&self) -> bool {
        matches!(self, Self::V2(_))
    }
}

impl TryFrom<&[u8]> for PwbPacket {
    type Error = TryPwbPacketFromSliceError;

    fn try_from(slice: &[u8]) -> Result<Self, Self::Error> {
        Ok(PwbPacket::V2(PwbV2Packet::try_from(slice)?))
    }
}

impl TryFrom<Vec<Chunk>> for PwbPacket {
    type Error = TryPwbPacketFromChunksError;

    fn try_from(chunks: Vec<Chunk>) -> Result<Self, Self::Error> {
        Ok(PwbPacket::V2(PwbV2Packet::try_from(chunks)?))
    }
}

/// The error type returned when calculating the Padwing data suppression
/// baseline fails.
#[derive(Error, Debug)]
#[error("short slice (expected at least 68 samples, found `{found}`)")]
pub struct CalculateSuppressionBaselineError {
    found: usize,
}

/// Helper function to return the data suppression baseline of a slice as
/// implemented in the Padwing board firmware.
// Take the run number as input because Konstantin can change the baseline
// calculation at any time. This is not linked to the PwbPacket version. Older
// or future versions might no even have data suppression (hence return Option).
//
// A future alternative to avoid returning a Result, is to have a newtype for
// the waveform. But I am not sure if this is a good place for this; maybe at
// a higher level in the analysis chain.
pub fn suppression_baseline(
    _run_number: u32,
    waveform: &[i16],
) -> Result<Option<i16>, CalculateSuppressionBaselineError> {
    if waveform.len() < 68 {
        return Err(CalculateSuppressionBaselineError {
            found: waveform.len(),
        });
    }
    // Add over i32 to avoid overflow
    let num = waveform[4..][..64]
        .iter()
        .map(|n| i32::from(*n))
        .sum::<i32>();
    Ok(Some((num / 64).try_into().unwrap()))
}

#[cfg(test)]
mod tests;