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
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::alpha16::aw_map::TpcWirePosition;

/// Anode wire map.
pub mod aw_map;

/// Sampling rate (samples per second) of the ADC channels that receive the
/// Barrel Veto SiPM signals.
pub const ADC16_RATE: f64 = 100e6;
/// Sampling rate (samples per second) of the ADC channels that receive the
/// radial Time Projection Chamber anode wire signals.
pub const ADC32_RATE: f64 = 62.5e6;
/// Maximum value at which the ADC waveforms saturate.
pub const ADC_MAX: i16 = 32764;
/// Minimum value at which the ADC waveforms saturate.
pub const ADC_MIN: i16 = -32768;

/// 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: u8,
}

/// Channel ID that corresponds to SiPMs of the Barrel Veto.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Adc16ChannelId(u8);
impl TryFrom<u8> for Adc16ChannelId {
    type Error = TryChannelIdFromUnsignedError;

    /// There are 16 valid channel ids. Perform the conversion from an integer
    /// in range `0..=15`.
    fn try_from(num: u8) -> Result<Self, Self::Error> {
        if num > 15 {
            Err(TryChannelIdFromUnsignedError { input: num })
        } else {
            Ok(Adc16ChannelId(num))
        }
    }
}

/// Channel ID that corresponds to anode wires in the radial Time Projection
/// Chamber.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Adc32ChannelId(u8);
impl TryFrom<u8> for Adc32ChannelId {
    type Error = TryChannelIdFromUnsignedError;

    /// There are 32 valid channel ids. Perform the conversion from an integer
    /// in range `0..=31`.
    fn try_from(num: u8) -> Result<Self, Self::Error> {
        if num > 31 {
            Err(TryChannelIdFromUnsignedError { input: num })
        } else {
            Ok(Adc32ChannelId(num))
        }
    }
}

/// ADC channel ID in an Alpha16 board.
#[derive(Clone, Copy, Debug)]
pub enum ChannelId {
    /// Barrel Veto SiPM channel.
    A16(Adc16ChannelId),
    /// Radial Time Projection Chamber anode wire channel.
    A32(Adc32ChannelId),
}
// There is not TryFrom implementation because there is not an unambiguous
// integer representation for both channels at the same time.
// Agana uses some times [0-47] with [0-15] BV and [16-47] TPC. In other places
// it uses [0-15] BV and [128-159] TPC. Avoid that mess here.

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

/// Module ID of an Alpha16 board.
///
/// I don't know how this is useful, the mapping to anode wires is independent
/// from the module ID (see [`TpcWirePosition`]). This is included for
/// completeness.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ModuleId(u8);
impl TryFrom<u8> for ModuleId {
    type Error = TryModuleIdFromUnsignedError;

    /// There are 8 valid module ids. Perform the conversion from an integer
    /// in range `0..=7`.
    fn try_from(num: u8) -> Result<Self, Self::Error> {
        if num > 7 {
            Err(TryModuleIdFromUnsignedError { input: num })
        } else {
            Ok(ModuleId(num))
        }
    }
}

/// 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 parsing a [`BoardId`] fails.
#[derive(Error, Debug)]
#[error("unknown parsing from board name `{input}` to BoardId")]
pub struct ParseBoardIdError {
    input: String,
}

// Known Alpha16 board names and mac addresses
// Just add new boards to this list
// ("name", [mac address])
// "name" is 2 ASCII characters that also appear in the data bank name
const ALPHA16BOARDS: [(&str, [u8; 6]); 8] = [
    ("09", [216, 128, 57, 104, 55, 76]),
    ("10", [216, 128, 57, 104, 170, 37]),
    ("11", [216, 128, 57, 104, 172, 127]),
    ("12", [216, 128, 57, 104, 79, 167]),
    ("13", [216, 128, 57, 104, 202, 166]),
    ("14", [216, 128, 57, 104, 142, 130]),
    ("16", [216, 128, 57, 104, 111, 162]),
    ("18", [216, 128, 57, 104, 142, 82]),
];

/// Identity of a physical Alpha16 board.
///
/// It is important to notice that a [`BoardId`] is different to a
/// [`TpcWirePosition`]. The former identifies a physical Alpha16 board, while
/// the latter is a fixed position that maps a location in the rTPC. The mapping
/// between [`BoardId`] and [`TpcWirePosition`] 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],
}
impl TryFrom<&str> for BoardId {
    type Error = ParseBoardIdError;

    fn try_from(name: &str) -> Result<Self, Self::Error> {
        for pair in ALPHA16BOARDS {
            if name == pair.0 {
                return Ok(BoardId {
                    name: pair.0,
                    mac_address: pair.1,
                });
            }
        }
        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 pair in ALPHA16BOARDS {
            if mac == pair.1 {
                return Ok(BoardId {
                    name: pair.0,
                    mac_address: pair.1,
                });
            }
        }
        Err(TryBoardIdFromMacAddressError { input: mac })
    }
}
impl BoardId {
    /// Return the name of a physical Alpha16 board. This is a human readable
    /// name used to identify a board instead of the mac address.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryBoardIdFromMacAddressError;
    /// # fn main() -> Result<(), TryBoardIdFromMacAddressError> {
    /// use alpha_g_detector::alpha16::BoardId;
    ///
    /// let board_id = BoardId::try_from([216, 128, 57, 104, 142, 82])?;
    /// assert_eq!(board_id.name(), "18");
    /// # Ok(())
    /// # }
    /// ```
    pub fn name(&self) -> &str {
        self.name
    }
    /// Return the mac address of a physical Alpha16 board.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryBoardIdFromMacAddressError;
    /// # fn main() -> Result<(), TryBoardIdFromMacAddressError> {
    /// use alpha_g_detector::alpha16::BoardId;
    ///
    /// let board_id = BoardId::try_from([216, 128, 57, 104, 142, 82])?;
    /// assert_eq!(board_id.mac_address(), [216, 128, 57, 104, 142, 82]);
    /// # Ok(())
    /// # }
    /// ```
    pub fn mac_address(&self) -> [u8; 6] {
        self.mac_address
    }
}

/// The error type returned when conversion from
/// [`&[u8]`](https://doc.rust-lang.org/std/primitive.slice.html) to
/// [`AdcPacket`] fails.
#[derive(Error, Debug)]
pub enum TryAdcPacketFromSliceError {
    /// 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 type.
    #[error("unknown packet type `{found}`")]
    UnknownType { found: u8 },
    /// Unknown packet version.
    #[error("unknown packet version `{found}`")]
    UnknownVersion { found: u8 },
    /// Integer representation of Module ID doesn't match any known
    /// [`ModuleId`].
    #[error("unknown module id")]
    UnknownModuleId(#[from] TryModuleIdFromUnsignedError),
    /// Integer representation of channel ID doesn't match any known
    /// [`ChannelId`].
    #[error("unknown channel number")]
    UnknownChannelId(#[from] TryChannelIdFromUnsignedError),
    /// Non-zero value found in bytes meant to be fixed to `0`.
    #[error("zero-bytes mismatch (found `{found:?}`)")]
    ZeroMismatch { found: [u8; 2] },
    /// MAC address doesn't map to any known [`BoardId`].
    #[error("unknown mac address")]
    UnknownMac(#[from] TryBoardIdFromMacAddressError),
    /// Suppression baseline in the footer doesn't match waveform samples.
    #[error("suppression baseline mismatch (expected `{expected}`, found `{found}`)")]
    BaselineMismatch { found: i16, expected: i16 },
    /// The value of `keep_last` is inconsistent with the `keep_bit`, or its
    /// value is less than the minimum required by the suppression baseline.
    // The `keep_more` and `threshold` values are not known here, so a more
    // specific error than this is not possible.
    // If limit == 0, then it is an inconsistency with the `keep_bit`
    // If limit != 0, then value is less than the limit imposed by the
    // suppression baseline.
    #[error("bad keep_last `{found}` (limit was `{limit}`)")]
    BadKeepLast { found: usize, limit: usize },
    /// The `keep_bit` in the footer is inconsistent with the packet size and
    /// data suppression status.
    // The `threshold` is not known here, so a more specific error than this is
    // not possible.
    #[error("keep_bit mismatch (found `{found}`)")]
    KeepBitMismatch { found: bool },
    /// The number of waveform samples is less/more than the minimum/maximum
    /// required by the suppression baseline, `keep_last`, or requested number
    /// of samples.
    #[error("bad number of samples `{found}` (expected at least `{min}` and at most `{max}`)")]
    BadNumberOfSamples {
        found: usize,
        min: usize,
        max: usize,
    },
}

/// Version 3 of an ADC data packet.
///
/// An ADC packet represents the data collected from an individual channel in an
/// Alpha16 board. The binary representation of an [`AdcV3Packet`] in a data
/// bank is shown below. All multi-byte fields are big-endian:
///
/// <center>
///
/// |Byte(s)|Description|
/// |:-:|:-:|
/// |0|Fixed to 1|
/// |1|Fixed to 3|
/// |2-3|Accepted trigger|
/// |4|Module ID|
/// |5|Channel ID|
/// |6-7|Requested samples|
/// |8-11|Event timestamp (LSW)|
/// |12-13|Fixed to 0|
/// |14-19|MAC address|
/// |20-23|Event timestamp (MSW)|
/// |24-27|Trigger offset|
/// |28-31|Build timestamp|
/// |32-33|First waveform sample|
/// |...|Waveform samples|
/// |Last 4 bytes|Data suppression info|
///
/// </center>
///
/// Bytes `[12..size - 4]` are only included in the packet if the `keep_bit` is
/// set after data suppression.
#[derive(Clone, Debug)]
pub struct AdcV3Packet {
    accepted_trigger: u16,
    module_id: ModuleId,
    channel_id: ChannelId,
    requested_samples: usize,
    event_timestamp: u64,
    board_id: Option<BoardId>,
    trigger_offset: Option<i32>,
    build_timestamp: Option<u32>,
    waveform: Vec<i16>,
    suppression_baseline: i16,
    keep_last: usize,
    keep_bit: bool,
    suppression_enabled: bool,
}

impl fmt::Display for AdcV3Packet {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "Packet type: {}", self.packet_type())?;
        writeln!(f, "Packet version: {}", self.packet_version())?;
        writeln!(f, "Accepted trigger: {}", self.accepted_trigger)?;
        writeln!(f, "Module ID: {:?}", self.module_id)?;
        let channel_id = match self.channel_id {
            ChannelId::A16(channel) => format!("{channel:?}"),
            ChannelId::A32(channel) => format!("{channel:?}"),
        };
        writeln!(f, "Channel ID: {channel_id}")?;
        writeln!(f, "Requested samples: {}", self.requested_samples)?;
        writeln!(f, "Event timestamp: {}", self.event_timestamp)?;
        let mac_address = self
            .board_id
            .map_or("None".to_string(), |b| format!("{:?}", b.mac_address()));
        writeln!(f, "MAC address: {mac_address}")?;
        let trigger_offset = self
            .trigger_offset
            .map_or("None".to_string(), |v| v.to_string());
        writeln!(f, "Trigger offset: {trigger_offset}",)?;
        let build_timestamp = self
            .build_timestamp
            .map_or("None".to_string(), |v| v.to_string());
        writeln!(f, "Build timestamp: {build_timestamp}",)?;
        writeln!(f, "Waveform samples: {}", self.waveform.len())?;
        writeln!(f, "Suppression baseline: {}", self.suppression_baseline)?;
        writeln!(f, "Keep last: {}", self.keep_last)?;
        writeln!(f, "Keep bit: {}", self.keep_bit)?;
        write!(f, "Suppression enabled: {}", self.suppression_enabled)?;

        Ok(())
    }
}

impl AdcV3Packet {
    /// Return the packet type.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::AdcV3Packet;
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcV3Packet::try_from(&buffer[..])?;
    ///
    /// assert_eq!(packet.packet_type(), 1);
    /// # Ok(())
    /// # }
    /// ```
    pub fn packet_type(&self) -> u8 {
        1
    }
    /// Return the packet version. For [`AdcV3Packet`] it is fixed to `3`.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::AdcV3Packet;
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcV3Packet::try_from(&buffer[..])?;
    ///
    /// assert_eq!(packet.packet_version(), 3);
    /// # Ok(())
    /// # }
    /// ```
    pub fn packet_version(&self) -> u8 {
        3
    }
    /// In the firmware logic, `accepted_trigger` is a 32-bits unsigned integer.
    /// Return the 16 LSB as [`u16`].
    ///
    /// This is a counter that indicates the number of trigger signals received
    /// from the TRG board. All packets from the same event must have the same
    /// `accepted_trigger` counter.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::AdcV3Packet;
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcV3Packet::try_from(&buffer[..])?;
    ///
    /// assert_eq!(packet.accepted_trigger(), 4);
    /// # Ok(())
    /// # }
    /// ```
    pub fn accepted_trigger(&self) -> u16 {
        self.accepted_trigger
    }
    /// Return the [`ModuleId`] of the Alpha16 board from which the packet was
    /// generated.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::{AdcV3Packet, ModuleId};
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcV3Packet::try_from(&buffer[..])?;
    ///
    /// assert_eq!(packet.module_id(), ModuleId::try_from(5)?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn module_id(&self) -> ModuleId {
        self.module_id
    }
    /// Return the [`ChannelId`] in an Alpha16 board from which the packet was
    /// generated.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::{AdcV3Packet, ChannelId};
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcV3Packet::try_from(&buffer[..])?;
    ///
    /// assert!(matches!(packet.channel_id(), ChannelId::A16(_)));
    /// # Ok(())
    /// # }
    /// ```
    pub fn channel_id(&self) -> ChannelId {
        self.channel_id
    }
    /// Return the number of requested waveform samples. The actual number of
    /// samples in the packet should be obtained from [`waveform`]; due to data
    /// suppression these two are most likely not equal.
    ///
    /// [`waveform`]: AdcV3Packet::waveform.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::AdcV3Packet;
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcV3Packet::try_from(&buffer[..])?;
    ///
    /// assert_eq!(packet.requested_samples(), 699);
    /// # Ok(())
    /// # }
    /// ```
    pub fn requested_samples(&self) -> usize {
        self.requested_samples
    }
    /// I do not know what this field means. It never matches the event
    /// timestamp in the MIDAS event.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::AdcV3Packet;
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcV3Packet::try_from(&buffer[..])?;
    ///
    /// assert_eq!(packet.event_timestamp(), 7);
    /// # Ok(())
    /// # }
    /// ```
    pub fn event_timestamp(&self) -> u64 {
        self.event_timestamp
    }
    /// Return the [`BoardId`] of the Alpha16 board from which the packet was
    /// generated. Return [`None`] if data suppression is enabled and the
    /// `keep_bit` is not set.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::AdcV3Packet;
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcV3Packet::try_from(&buffer[..])?;
    ///
    /// assert!(packet.board_id().is_none());
    /// # Ok(())
    /// # }
    /// ```
    pub fn board_id(&self) -> Option<BoardId> {
        self.board_id
    }
    /// I do not understand what this field means exactly. I know that it
    /// matches `adcXX_trig_delay - adcXX_trig_start` in the ODB (with `XX`
    /// equal to `16` or `32`). Return [`None`] if data suppression is enabled
    /// and the `keep_bit` is not set.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::AdcV3Packet;
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcV3Packet::try_from(&buffer[..])?;
    ///
    /// assert!(packet.trigger_offset().is_none());
    /// # Ok(())
    /// # }
    /// ```
    pub fn trigger_offset(&self) -> Option<i32> {
        self.trigger_offset
    }
    /// Return the SOF file build timestamp; this acts as firmware version.
    /// Return [`None`] if data suppression is enabled and the `keep_bit` is not
    /// set.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::AdcV3Packet;
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcV3Packet::try_from(&buffer[..])?;
    ///
    /// assert!(packet.build_timestamp().is_none());
    /// # Ok(())
    /// # }
    /// ```
    pub fn build_timestamp(&self) -> Option<u32> {
        self.build_timestamp
    }
    /// Return the digitized waveform samples received by an ADC channel in an
    /// Alpha16 board. Return an empty slice if data suppression is enabled and
    /// the `keep_bit` is not set.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::AdcV3Packet;
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcV3Packet::try_from(&buffer[..])?;
    ///
    /// assert!(packet.waveform().is_empty());
    /// # Ok(())
    /// # }
    /// ```
    pub fn waveform(&self) -> &[i16] {
        &self.waveform
    }
    /// Return the data suppression waveform baseline.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::AdcV3Packet;
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcV3Packet::try_from(&buffer[..])?;
    ///
    /// assert_eq!(packet.suppression_baseline(), 0);
    /// # Ok(())
    /// # }
    /// ```
    pub fn suppression_baseline(&self) -> i16 {
        self.suppression_baseline
    }
    /// This is a counter in the firmware side on how many data words are being
    /// kept due to data suppression. If the `keep_bit` is not set, then
    /// `keep_last` is equal to 0. This counter increases by the index of the
    /// last waveform sample over threshold as `keep_last = (index + 2) / 2 + 1`.
    ///
    /// Recall that data suppression doesn't "see" the last 6(?) samples, hence
    /// `keep_last` is not a reliable way to obtain the last waveform sample
    /// over the data suppression threshold. This `keep_last` value is only
    /// really useful in validating/checking the data suppression on the
    /// firmware side. If you are using this for anything else, you are most
    /// likely making a mistake.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::AdcV3Packet;
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcV3Packet::try_from(&buffer[..])?;
    ///
    /// assert_eq!(packet.keep_last(), 0);
    /// # Ok(())
    /// # }
    /// ```
    pub fn keep_last(&self) -> usize {
        self.keep_last
    }
    /// Return [`true`] if at least one [`waveform`] sample is over the data
    /// suppression threshold.
    ///
    /// [`waveform`]: AdcV3Packet::waveform.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::AdcV3Packet;
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcV3Packet::try_from(&buffer[..])?;
    ///
    /// assert!(!packet.keep_bit());
    /// # Ok(())
    /// # }
    /// ```
    pub fn keep_bit(&self) -> bool {
        self.keep_bit
    }
    /// Return [`true`] if data suppression is enabled.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::AdcV3Packet;
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcV3Packet::try_from(&buffer[..])?;
    ///
    /// assert!(packet.is_suppression_enabled());
    /// # Ok(())
    /// # }
    /// ```
    pub fn is_suppression_enabled(&self) -> bool {
        self.suppression_enabled
    }
}

// The minimum number of samples required to reconstruct the data suppression
// baseline.
const BASELINE_SAMPLES: usize = 64;
// Minimum valid value of keep_last different to 0.
// keep_last = (index + 2) / 2 + 1
// And the minimum index is one after the baseline.
const MIN_KEEP_LAST: usize = (BASELINE_SAMPLES + 2) / 2 + 1;

impl TryFrom<&[u8]> for AdcV3Packet {
    type Error = TryAdcPacketFromSliceError;

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

        if slice[0] != 1 {
            return Err(Self::Error::UnknownType { found: slice[0] });
        }
        if slice[1] != 3 {
            return Err(Self::Error::UnknownVersion { found: slice[1] });
        }
        let accepted_trigger = slice[2..4].try_into().unwrap();
        let accepted_trigger = u16::from_be_bytes(accepted_trigger);
        let module_id = ModuleId::try_from(slice[4])?;
        // A value of [0-15] is BV, and a value of [128-159] is rTPC
        let channel_id = slice[5];
        let channel_id = if channel_id < 128 {
            ChannelId::A16(channel_id.try_into()?)
        } else {
            ChannelId::A32((channel_id - 128).try_into()?)
        };
        let requested_samples = slice[6..8].try_into().unwrap();
        let requested_samples = u16::from_be_bytes(requested_samples).into();
        let lsw_event_timestamp = slice[8..12].try_into().unwrap();

        let suppression_baseline = slice[slice.len() - 2..].try_into().unwrap();
        let suppression_baseline = i16::from_be_bytes(suppression_baseline);
        let footer = slice[slice.len() - 4..][..2].try_into().unwrap();
        let footer = u16::from_be_bytes(footer);
        let keep_last = usize::from(footer & 0xFFF);
        let keep_bit = (footer >> 12) & 1 == 1;
        let suppression_enabled = (footer >> 13) & 1 == 1;

        if slice.len() == 16 {
            if !suppression_enabled {
                return Err(Self::Error::IncompleteSlice {
                    found: 16,
                    min_expected: 36,
                });
            }
            if keep_bit {
                return Err(Self::Error::KeepBitMismatch { found: keep_bit });
            }
            if keep_last != 0 {
                return Err(Self::Error::BadKeepLast {
                    found: keep_last,
                    limit: 0,
                });
            }
            return Ok(AdcV3Packet {
                accepted_trigger,
                module_id,
                channel_id,
                requested_samples,
                event_timestamp: u32::from_be_bytes(lsw_event_timestamp).into(),
                board_id: None,
                trigger_offset: None,
                build_timestamp: None,
                waveform: Vec::new(),
                keep_last,
                suppression_baseline,
                keep_bit,
                suppression_enabled,
            });
        }

        if slice.len() < 36 {
            return Err(Self::Error::IncompleteSlice {
                found: slice.len(),
                min_expected: 36,
            });
        }

        if slice[12..14] != [0, 0] {
            return Err(Self::Error::ZeroMismatch {
                found: slice[12..14].try_into().unwrap(),
            });
        }
        let board_id: [u8; 6] = slice[14..20].try_into().unwrap();
        let board_id = BoardId::try_from(board_id)?;
        let msw_event_timestamp = slice[20..24].try_into().unwrap();
        let event_timestamp = [msw_event_timestamp, lsw_event_timestamp].concat();
        let event_timestamp = event_timestamp.try_into().unwrap();
        let event_timestamp = u64::from_be_bytes(event_timestamp);
        let trigger_offset = slice[24..28].try_into().unwrap();
        let trigger_offset = i32::from_be_bytes(trigger_offset);
        let build_timestamp = slice[28..32].try_into().unwrap();
        let build_timestamp = u32::from_be_bytes(build_timestamp);
        let waveform_bytes = slice.len() - 36;
        if waveform_bytes % 2 != 0 {
            return Err(Self::Error::IncompleteSlice {
                // waveform bytes + header + footer
                found: waveform_bytes + 36,
                min_expected: waveform_bytes + 37,
            });
        }
        let waveform: Vec<i16> = slice[32..][..waveform_bytes]
            .chunks_exact(2)
            .map(|b| i16::from_be_bytes(b.try_into().unwrap()))
            .collect();

        if waveform.len() < BASELINE_SAMPLES {
            return Err(Self::Error::BadNumberOfSamples {
                found: waveform.len(),
                min: BASELINE_SAMPLES,
                max: requested_samples - 2,
            });
        }
        let data_baseline = {
            // Add over i32 to avoid overflow
            let num = waveform[..BASELINE_SAMPLES]
                .iter()
                .map(|n| i32::from(*n))
                .sum::<i32>();
            let d = num / 64;
            if num % 64 < 0 {
                d - 1
            } else {
                d
            }
        };
        if data_baseline != suppression_baseline.into() {
            return Err(Self::Error::BaselineMismatch {
                found: suppression_baseline,
                expected: data_baseline.try_into().unwrap(),
            });
        }

        if suppression_enabled {
            if !keep_bit {
                return Err(Self::Error::KeepBitMismatch { found: keep_bit });
            }
            if keep_last < MIN_KEEP_LAST {
                return Err(Self::Error::BadKeepLast {
                    found: keep_last,
                    limit: MIN_KEEP_LAST,
                });
            }
            let last_index = (keep_last - 1) * 2 - 2;
            if waveform.len() <= last_index {
                return Err(Self::Error::BadNumberOfSamples {
                    found: waveform.len(),
                    min: last_index + 1,
                    max: requested_samples - 2,
                });
            }
            if waveform.len() > requested_samples - 2 {
                return Err(Self::Error::BadNumberOfSamples {
                    found: waveform.len(),
                    min: last_index + 1,
                    max: requested_samples - 2,
                });
            }
        } else {
            if keep_bit {
                if keep_last < MIN_KEEP_LAST {
                    return Err(Self::Error::BadKeepLast {
                        found: keep_last,
                        limit: MIN_KEEP_LAST,
                    });
                }
                let last_index = (keep_last - 1) * 2 - 2;
                if waveform.len() <= last_index {
                    return Err(Self::Error::BadNumberOfSamples {
                        found: waveform.len(),
                        min: last_index + 1,
                        max: requested_samples - 2,
                    });
                }
            } else if keep_last != 0 {
                return Err(Self::Error::BadKeepLast {
                    found: keep_last,
                    limit: 0,
                });
            }
            if waveform.len() != requested_samples - 2 {
                return Err(Self::Error::BadNumberOfSamples {
                    found: waveform.len(),
                    min: requested_samples - 2,
                    max: requested_samples - 2,
                });
            }
        }

        Ok(AdcV3Packet {
            accepted_trigger,
            module_id,
            channel_id,
            requested_samples,
            event_timestamp,
            board_id: Some(board_id),
            trigger_offset: Some(trigger_offset),
            build_timestamp: Some(build_timestamp),
            waveform,
            keep_last,
            suppression_baseline,
            keep_bit,
            suppression_enabled,
        })
    }
}

/// ADC data packet.
///
/// This enum can currently contain only an [`AdcV3Packet`]. See its
/// documentation for more details.
#[derive(Clone, Debug)]
pub enum AdcPacket {
    /// Version 3 of an ADC packet.
    V3(AdcV3Packet),
}

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

impl AdcPacket {
    /// Return the packet type.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::AdcPacket;
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcPacket::try_from(&buffer[..])?;
    ///
    /// assert_eq!(packet.packet_type(), 1);
    /// # Ok(())
    /// # }
    /// ```
    pub fn packet_type(&self) -> u8 {
        match self {
            Self::V3(packet) => packet.packet_type(),
        }
    }
    /// Return the packet version.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::AdcPacket;
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcPacket::try_from(&buffer[..])?;
    ///
    /// assert_eq!(packet.packet_version(), 3);
    /// # Ok(())
    /// # }
    /// ```
    pub fn packet_version(&self) -> u8 {
        match self {
            Self::V3(packet) => packet.packet_version(),
        }
    }
    /// In the firmware logic, `accepted_trigger` is a 32-bits unsigned integer.
    /// Return the 16 LSB as [`u16`].
    ///
    /// This is a counter that indicates the number of trigger signals received
    /// from the TRG board. All packets from the same event must have the same
    /// `accepted_trigger` counter.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::AdcPacket;
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcPacket::try_from(&buffer[..])?;
    ///
    /// assert_eq!(packet.accepted_trigger(), 4);
    /// # Ok(())
    /// # }
    /// ```
    pub fn accepted_trigger(&self) -> u16 {
        match self {
            Self::V3(packet) => packet.accepted_trigger(),
        }
    }
    /// Return the [`ModuleId`] of the Alpha16 board from which the packet was
    /// generated.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::{AdcPacket, ModuleId};
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcPacket::try_from(&buffer[..])?;
    ///
    /// assert_eq!(packet.module_id(), ModuleId::try_from(5)?);
    /// # Ok(())
    /// # }
    /// ```
    pub fn module_id(&self) -> ModuleId {
        match self {
            Self::V3(packet) => packet.module_id(),
        }
    }
    /// Return the [`ChannelId`] in an Alpha16 board from which the packet was
    /// generated.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::{AdcPacket, ChannelId};
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcPacket::try_from(&buffer[..])?;
    ///
    /// assert!(matches!(packet.channel_id(), ChannelId::A16(_)));
    /// # Ok(())
    /// # }
    /// ```
    pub fn channel_id(&self) -> ChannelId {
        match self {
            Self::V3(packet) => packet.channel_id(),
        }
    }
    /// Return the number of requested waveform samples. The actual number of
    /// samples in the packet should be obtained from [`waveform`]; due to data
    /// suppression these two are most likely not equal.
    ///
    /// [`waveform`]: AdcV3Packet::waveform.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::AdcPacket;
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcPacket::try_from(&buffer[..])?;
    ///
    /// assert_eq!(packet.requested_samples(), 699);
    /// # Ok(())
    /// # }
    /// ```
    pub fn requested_samples(&self) -> usize {
        match self {
            Self::V3(packet) => packet.requested_samples(),
        }
    }
    /// I do not know what this field means. It never matches the event
    /// timestamp in the MIDAS event.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::AdcPacket;
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcPacket::try_from(&buffer[..])?;
    ///
    /// assert_eq!(packet.event_timestamp(), 7);
    /// # Ok(())
    /// # }
    /// ```
    pub fn event_timestamp(&self) -> u64 {
        match self {
            Self::V3(packet) => packet.event_timestamp(),
        }
    }
    /// Return the [`BoardId`] of the Alpha16 board from which the packet was
    /// generated. Return [`None`] if data suppression is enabled and the
    /// `keep_bit` is not set in a version 3 packet.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::{AdcPacket, BoardId};
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcPacket::try_from(&buffer[..])?;
    ///
    /// assert!(packet.board_id().is_none());
    /// # Ok(())
    /// # }
    /// ```
    pub fn board_id(&self) -> Option<BoardId> {
        match self {
            Self::V3(packet) => packet.board_id(),
        }
    }
    /// I do not understand what this field means exactly. I know that it
    /// matches `adcXX_trig_delay - adcXX_trig_start` in the ODB (with `XX`
    /// equal to `16` or `32`). Return [`None`] if data suppression is enabled
    /// and the `keep_bit` is not set in a version 3 packet.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::AdcPacket;
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcPacket::try_from(&buffer[..])?;
    ///
    /// assert!(packet.trigger_offset().is_none());
    /// # Ok(())
    /// # }
    /// ```
    pub fn trigger_offset(&self) -> Option<i32> {
        match self {
            Self::V3(packet) => packet.trigger_offset(),
        }
    }
    /// Return the SOF file build timestamp; this acts as firmware version.
    /// Return [`None`] if data suppression is enabled and the `keep_bit` is not
    /// set in a version 3 packet.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::AdcPacket;
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcPacket::try_from(&buffer[..])?;
    ///
    /// assert!(packet.build_timestamp().is_none());
    /// # Ok(())
    /// # }
    /// ```
    pub fn build_timestamp(&self) -> Option<u32> {
        match self {
            Self::V3(packet) => packet.build_timestamp(),
        }
    }
    /// Return the digitized waveform samples received by an ADC channel in an
    /// Alpha16 board. Return an empty slice if data suppression is enabled and
    /// the `keep_bit` is not set in a version 3 packet.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::AdcPacket;
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcPacket::try_from(&buffer[..])?;
    ///
    /// assert!(packet.waveform().is_empty());
    /// # Ok(())
    /// # }
    /// ```
    pub fn waveform(&self) -> &[i16] {
        match self {
            Self::V3(packet) => packet.waveform(),
        }
    }
    /// Return the data suppression waveform baseline. Return [`None`] if this
    /// is a version 1 packet (these don't have any data suppression
    /// implemented).
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::AdcPacket;
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcPacket::try_from(&buffer[..])?;
    ///
    /// assert_eq!(packet.suppression_baseline(), Some(0));
    /// # Ok(())
    /// # }
    /// ```
    pub fn suppression_baseline(&self) -> Option<i16> {
        match self {
            Self::V3(packet) => Some(packet.suppression_baseline()),
        }
    }
    /// This is a counter in the firmware side on how many data words are being
    /// kept due to data suppression. If the `keep_bit` is not set, then
    /// `keep_last` is equal to 0. This counter increases by the index of the
    /// last waveform sample over threshold as `keep_last = (index + 2) / 2 + 1`.
    ///
    /// Recall that data suppression doesn't "see" the last 6(?) samples, hence
    /// `keep_last` is not a reliable way to obtain the last waveform sample
    /// over the data suppression threshold. This `keep_last` value is only
    /// really useful in validating/checking the data suppression on the
    /// firmware side. If you are using this for anything else, you are most
    /// likely making a mistake.
    ///
    ///  Return [`None`] if this is a version 1 packet (these don't have any
    ///  data suppression implemented).
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::AdcPacket;
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcPacket::try_from(&buffer[..])?;
    ///
    /// assert_eq!(packet.keep_last(), Some(0));
    /// # Ok(())
    /// # }
    /// ```
    pub fn keep_last(&self) -> Option<usize> {
        match self {
            Self::V3(packet) => Some(packet.keep_last()),
        }
    }
    /// Return [`true`] if at least one [`waveform`] sample is over the data
    /// suppression threshold. Return [`None`] if this is a version 1 packet
    /// (these don't have any data suppression implemented).
    ///
    /// [`waveform`]: AdcV3Packet::waveform.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::AdcPacket;
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcPacket::try_from(&buffer[..])?;
    ///
    /// assert_eq!(packet.keep_bit(), Some(false));
    /// # Ok(())
    /// # }
    /// ```
    pub fn keep_bit(&self) -> Option<bool> {
        match self {
            Self::V3(packet) => Some(packet.keep_bit()),
        }
    }
    /// Return [`true`] if data suppression is enabled. Return [`None`] if this
    /// is a version 1 packet (these don't have any data suppression
    /// implemented).
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::AdcPacket;
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcPacket::try_from(&buffer[..])?;
    ///
    /// assert_eq!(packet.is_suppression_enabled(), Some(true));
    /// # Ok(())
    /// # }
    /// ```
    pub fn is_suppression_enabled(&self) -> Option<bool> {
        match self {
            Self::V3(packet) => Some(packet.is_suppression_enabled()),
        }
    }
    /// Return [`true`] if this adc packet is an [`AdcV3Packet`], and [`false`]
    /// otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// # use alpha_g_detector::alpha16::TryAdcPacketFromSliceError;
    /// # fn main() -> Result<(), TryAdcPacketFromSliceError> {
    /// use alpha_g_detector::alpha16::AdcPacket;
    ///
    /// let buffer = [1, 3, 0, 4, 5, 6, 2, 187, 0, 0, 0, 7, 224, 0, 0, 0];
    /// let packet = AdcPacket::try_from(&buffer[..])?;
    ///
    /// assert!(packet.is_v3());
    /// # Ok(())
    /// # }
    /// ```
    pub fn is_v3(&self) -> bool {
        matches!(self, Self::V3(_))
    }
}

impl TryFrom<&[u8]> for AdcPacket {
    type Error = TryAdcPacketFromSliceError;

    fn try_from(slice: &[u8]) -> Result<Self, Self::Error> {
        Ok(AdcPacket::V3(AdcV3Packet::try_from(slice)?))
    }
}

#[cfg(test)]
mod tests;