rfid-silion-compat 0.1.0

Async Rust library for Silion RFID readers with serial and Web Serial support
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
//! Command-layer protocol types and host packet builders.
//!
//! This module contains low-level request payload models and helpers for
//! constructing wire packets for Silion reader commands.

use crate::async_proto::{ASYNC_MARKER, ASYNC_TERMINATOR, subcommand_crc};
use crate::codes::{AntennaPortsOption, CommandCode, RegionCode};
use crate::error::ProtocolError;
use crate::frame::{build_host_frame, push_u16_be, push_u32_be};
use crate::parsers::{AntennaPair, AntennaPower, AntennaPowerSettling};

/// Select/singulation payload used by inventory and tag access commands.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SelectContent {
    /// Address (bits).
    pub address_bits: u32,
    /// Number of selected bits.
    pub bit_len: u16,
    /// Select data bytes.
    pub data: Vec<u8>,
}

impl SelectContent {
    /// Encode the SelectContent according to the Silion protocol, using select_option_bits to determine encoding.
    ///
    /// - If select_option_bits.extended_data_length() is true, bit_len is encoded as u16 (big-endian), otherwise as u8.
    /// - Data is encoded as-is.
    /// Encode the SelectContent according to the Silion protocol, using InventoryOption to determine encoding.
    ///
    /// - If option.select_option_bits_struct().extended_data_length() is true, bit_len is encoded as u16 (big-endian), otherwise as u8.
    /// - Data is encoded as-is.
    pub(crate) fn encode_with_option(&self, out: &mut Vec<u8>, option: InventoryOption) {
        let select_option_bits = option.select_option_bits();
        if select_option_bits.mode() != Some(SelectMode::Epc) {
            push_u32_be(out, self.address_bits);
        }
        if select_option_bits.extended_data_length() {
            // Encode bit_len as u16 (big-endian)
            out.push((self.bit_len >> 8) as u8);
            out.push((self.bit_len & 0xFF) as u8);
        } else {
            // Encode bit_len as u8
            out.push(self.bit_len as u8);
        }
        out.extend_from_slice(&self.data);
    }
}

/// Tag singulation/select operation mode for inventory commands.
///
/// These values represent the target memory bank or select operation mode as defined
/// in the Silion protocol for Tag Inventory commands. They occupy bits 0-3 of the
/// select-option field.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum SelectMode {
    /// Select functionality is disabled. First tag found will be the tag operated on.
    /// No other Tag Singulation Fields should be specified.
    /// Note: When Select is disabled, commands do not support an access password.
    /// Use `SelectMode::PasswordOnly` to send a password without Select Content.
    Disabled = 0x00,
    /// Select on the value of the EPC.
    Epc = 0x01,
    /// Select on contents of TID memory bank (Gen2 bank 0x02).
    Tid = 0x02,
    /// Select on contents of User Memory bank (Gen2 bank 0x03).
    UserMemory = 0x03,
    /// Select on contents of the EPC memory bank (Gen2 bank 0x01).
    EpcBank = 0x04,
    /// Use this option to specify an access password without performing a Select.
    /// When this option is used, do not pass a Select Content field.
    PasswordOnly = 0x05,
}

impl SelectMode {
    /// Return the raw protocol value.
    pub const fn as_u8(self) -> u8 {
        self as u8
    }

    /// Create from the raw protocol value.
    pub const fn from_u8(value: u8) -> Option<Self> {
        match value {
            0x00 => Some(SelectMode::Disabled),
            0x01 => Some(SelectMode::Epc),
            0x02 => Some(SelectMode::Tid),
            0x03 => Some(SelectMode::UserMemory),
            0x04 => Some(SelectMode::EpcBank),
            0x05 => Some(SelectMode::PasswordOnly),
            _ => None,
        }
    }
}

/// Select-option bits for inventory commands.
///
/// The select-option field (bits 0, 1, 2, 3, 5 of the option byte) controls tag
/// singulation/select behavior. Includes the select mode plus optional flags.
///
/// | Mode | Value | Meaning |
/// |------|-------|---------|
/// | Select Mode (bits 0-2) | 0x00-0x05 | Target memory bank or operation (see [`SelectMode`]) |
/// | Invert Flag (bit 3) | 0x08 | Invert matching: return tags that do NOT match |
/// | Extended Data Length (bit 5) | 0x20 | Select Data Length is 2 bytes instead of 1 |
///
/// # Examples
///
/// Create a select option for EPC matching:
/// ```
/// use rfid_silion_compat::command::{SelectMode, SelectOptionBits};
///
/// let opts = SelectOptionBits::new(SelectMode::Epc);
/// assert_eq!(opts.raw(), 0x01);
/// ```
///
/// Create a select option with invert flag:
/// ```
/// use rfid_silion_compat::command::{SelectMode, SelectOptionBits};
///
/// let opts = SelectOptionBits::new(SelectMode::UserMemory)
///     .with_invert_flag(true);
/// assert_eq!(opts.raw(), 0x0B); // 0x03 | 0x08
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SelectOptionBits(u8);

impl SelectOptionBits {
    /// Create with the given select mode and no additional flags.
    pub const fn new(mode: SelectMode) -> Self {
        Self(mode.as_u8())
    }

    /// Create from the raw protocol byte (lower bits only, 0x2F mask).
    pub const fn from_raw(raw: u8) -> Self {
        Self(raw & 0x2F)
    }

    /// Return the raw protocol byte (includes all select-option bits).
    pub const fn raw(self) -> u8 {
        self.0
    }

    /// Return the select mode (bits 0-2, values 0x00-0x05).
    pub const fn mode(self) -> Option<SelectMode> {
        SelectMode::from_u8(self.0 & 0x0F)
    }

    /// Return whether the invert flag is set (bit 3).
    ///
    /// When set, tags NOT matching the specified Tag Singulation Fields will be returned.
    pub const fn invert_flag(self) -> bool {
        (self.0 & 0x08) != 0
    }

    /// Return whether the extended data length flag is set (bit 5).
    ///
    /// When set, Select Data Length is 2 bytes instead of 1, allowing Select Data
    /// to be greater than 255 bits.
    pub const fn extended_data_length(self) -> bool {
        (self.0 & 0x20) != 0
    }

    /// Set or clear the invert flag (bit 3).
    pub const fn with_invert_flag(self, en: bool) -> Self {
        Self(if en { self.0 | 0x08 } else { self.0 & !0x08 })
    }

    /// Set or clear the extended data length flag (bit 5).
    pub const fn with_extended_data_length(self, en: bool) -> Self {
        Self(if en { self.0 | 0x20 } else { self.0 & !0x20 })
    }
}

impl From<SelectMode> for SelectOptionBits {
    fn from(mode: SelectMode) -> Self {
        Self::new(mode)
    }
}

impl From<u8> for SelectOptionBits {
    fn from(value: u8) -> Self {
        Self::from_raw(value)
    }
}

impl From<SelectOptionBits> for u8 {
    fn from(value: SelectOptionBits) -> Self {
        value.raw()
    }
}

/// Option byte used by inventory commands (for example `0x22` and async start `0xAA48`).
///
/// Lower bits include select-option flags documented under Tag Inventory
/// commands. Higher bits are command-specific non-select option flags.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InventoryOption(u8);

impl InventoryOption {
    /// Create a default option byte with all bits cleared.
    pub const fn default() -> Self {
        Self(0)
    }

    /// Create from the raw protocol byte.
    pub const fn from_raw(raw: u8) -> Self {
        Self(raw)
    }

    /// Return the raw protocol byte.
    pub const fn raw(self) -> u8 {
        self.0
    }

    /// Return select-option bits as a SelectOptionBits struct.
    pub const fn select_option_bits(self) -> SelectOptionBits {
        SelectOptionBits::from_raw(self.0 & 0x2F)
    }

    /// Return whether Single Tag Inventory metadata mode is enabled (bit 4 / `0x10`).
    ///
    /// For command `0x21`: when enabled, host command includes 2-byte Metadata Flags
    /// and reader returns EPC + metadata. When disabled, command omits Metadata Flags
    /// and reader returns EPC-only payload.
    pub const fn single_tag_metadata_enabled(self) -> bool {
        (self.0 & 0x10) != 0
    }

    /// Set or clear Single Tag Inventory metadata mode bit (bit 4 / `0x10`).
    pub const fn with_single_tag_metadata(self, enabled: bool) -> Self {
        if enabled {
            Self(self.0 | 0x10)
        } else {
            Self(self.0 & !0x10)
        }
    }
}

impl From<u8> for InventoryOption {
    fn from(value: u8) -> Self {
        Self::from_raw(value)
    }
}

impl From<SelectOptionBits> for InventoryOption {
    fn from(bits: SelectOptionBits) -> Self {
        Self(bits.raw())
    }
}

impl From<InventoryOption> for u8 {
    fn from(value: InventoryOption) -> Self {
        value.raw()
    }
}

/// Search flags used by inventory commands (for example `0x22` and `0xAA48`).
///
/// For asynchronous inventory, protocol docs define extra semantics:
/// - bits 8..=11: rest ratio steps (0..=15)
/// - bit 15: heartbeat enable
/// - bit 14: auto-stop enable
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "web-serial", derive(serde::Serialize))]
pub struct InventorySearchFlags(u16);

impl InventorySearchFlags {
    /// Create a default search flags value with all bits cleared.
    pub const fn new() -> Self {
        Self(0)
    }

    /// Create from the raw protocol value.
    pub const fn from_raw(raw: u16) -> Self {
        Self(raw)
    }

    /// Return the raw protocol value.
    pub const fn raw(self) -> u16 {
        self.0
    }

    /// Extract asynchronous rest-ratio steps from bits 8..=11.
    pub const fn async_rest_ratio_steps(self) -> u8 {
        ((self.0 >> 8) & 0x0F) as u8
    }

    /// Return whether asynchronous heartbeat is enabled (bit 15).
    pub const fn async_heartbeat_enabled(self) -> bool {
        (self.0 & 0x8000) != 0
    }

    /// Return whether asynchronous auto-stop is enabled (bit 14).
    pub const fn async_auto_stop_enabled(self) -> bool {
        (self.0 & 0x4000) != 0
    }

    /// Return whether inventory embedded command mode is enabled (bit 2).
    ///
    /// This bit is documented for command `0x22` and reused by
    /// asynchronous inventory start (`0xAA48`).
    pub const fn embedded_command_enabled(self) -> bool {
        (self.0 & 0x0004) != 0
    }

    /// Set asynchronous rest-ratio steps (0..=15) in bits 8..=11.
    pub fn with_async_rest_ratio_steps(self, steps: u8) -> Result<Self, ProtocolError> {
        if steps > 15 {
            return Err(ProtocolError::InvalidArgument(
                "async rest ratio steps must be in 0..=15",
            ));
        }
        let raw = (self.0 & !(0x0F << 8)) | ((steps as u16) << 8);
        Ok(Self(raw))
    }

    /// Set or clear asynchronous heartbeat enable (bit 15).
    pub const fn with_async_heartbeat(self, enabled: bool) -> Self {
        if enabled {
            Self(self.0 | 0x8000)
        } else {
            Self(self.0 & !0x8000)
        }
    }

    /// Set or clear asynchronous auto-stop enable (bit 14).
    pub const fn with_async_auto_stop(self, enabled: bool) -> Self {
        if enabled {
            Self(self.0 | 0x4000)
        } else {
            Self(self.0 & !0x4000)
        }
    }

    /// Set or clear inventory embedded command mode (bit 2).
    pub const fn with_embedded_command(self, enabled: bool) -> Self {
        if enabled {
            Self(self.0 | 0x0004)
        } else {
            Self(self.0 & !0x0004)
        }
    }
}

impl From<u16> for InventorySearchFlags {
    fn from(value: u16) -> Self {
        Self::from_raw(value)
    }
}

impl From<InventorySearchFlags> for u16 {
    fn from(value: InventorySearchFlags) -> Self {
        value.raw()
    }
}

impl Default for InventorySearchFlags {
    fn default() -> Self {
        Self::new()
    }
}

/// Metadata flags that control which per-tag metadata fields the reader
/// includes in inventory responses.
///
/// Defined in the Single Tag Inventory (`0x21`), Get Tag Buffer (`0x29`), and
/// Asynchronous Inventory (`0xAA`) command specifications.
///
/// Each enabled bit requests one additional metadata field in the response.
/// When all bits are zero the reader returns only the EPC and tag CRC.
///
/// | Bit | Value  | Field         | Size    | Description |
/// |-----|--------|---------------|---------|-------------|
/// |  0  | 0x0001 | Read Count    | 1 byte  | Number of times the tag was archived |
/// |  1  | 0x0002 | RSSI          | 1 byte  | Signal strength, signed (dBm) |
/// |  2  | 0x0004 | Antenna ID    | 1 byte  | Logic antenna number |
/// |  3  | 0x0008 | Frequency     | 3 bytes | Frequency at archival (kHz) |
/// |  4  | 0x0010 | Timestamp     | 4 bytes | Elapsed time from inventory start (ms) |
/// |  5  | 0x0020 | RFU           | 2 bytes | Reserved for future use |
/// |  6  | 0x0040 | Protocol ID   | 1 byte  | Tag protocol (0x05 = Gen2) |
/// |  7  | 0x0080 | Data Length   | 2 bytes | Tag data length (0x0000 for 0x21) |
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "web-serial", derive(serde::Serialize))]
pub struct MetadataFlags(u16);

impl MetadataFlags {
    /// No metadata: only EPC and tag CRC are returned.
    pub const NONE: Self = Self(0x0000);
    /// All defined metadata bits set (`0x00FF`).
    pub const ALL: Self = Self(0x00FF);

    /// Create from the raw protocol value.
    pub const fn from_raw(raw: u16) -> Self {
        Self(raw)
    }

    /// Return the raw protocol value.
    pub const fn raw(self) -> u16 {
        self.0
    }

    /// Whether the Read Count field is requested (bit 0).
    pub const fn read_count(self) -> bool {
        (self.0 & 0x0001) != 0
    }
    /// Whether the RSSI field is requested (bit 1).
    pub const fn rssi(self) -> bool {
        (self.0 & 0x0002) != 0
    }
    /// Whether the Antenna ID field is requested (bit 2).
    pub const fn antenna_id(self) -> bool {
        (self.0 & 0x0004) != 0
    }
    /// Whether the Frequency field is requested (bit 3).
    pub const fn frequency(self) -> bool {
        (self.0 & 0x0008) != 0
    }
    /// Whether the Timestamp field is requested (bit 4).
    pub const fn timestamp(self) -> bool {
        (self.0 & 0x0010) != 0
    }
    /// Whether the RFU reserved field is requested (bit 5).
    pub const fn rfu(self) -> bool {
        (self.0 & 0x0020) != 0
    }
    /// Whether the Protocol ID field is requested (bit 6).
    pub const fn protocol_id(self) -> bool {
        (self.0 & 0x0040) != 0
    }
    /// Whether the Data Length field is requested (bit 7).
    pub const fn data_length(self) -> bool {
        (self.0 & 0x0080) != 0
    }

    /// Set or clear the Read Count bit (bit 0).
    pub const fn with_read_count(self, en: bool) -> Self {
        Self(if en {
            self.0 | 0x0001
        } else {
            self.0 & !0x0001
        })
    }
    /// Set or clear the RSSI bit (bit 1).
    pub const fn with_rssi(self, en: bool) -> Self {
        Self(if en {
            self.0 | 0x0002
        } else {
            self.0 & !0x0002
        })
    }
    /// Set or clear the Antenna ID bit (bit 2).
    pub const fn with_antenna_id(self, en: bool) -> Self {
        Self(if en {
            self.0 | 0x0004
        } else {
            self.0 & !0x0004
        })
    }
    /// Set or clear the Frequency bit (bit 3).
    pub const fn with_frequency(self, en: bool) -> Self {
        Self(if en {
            self.0 | 0x0008
        } else {
            self.0 & !0x0008
        })
    }
    /// Set or clear the Timestamp bit (bit 4).
    pub const fn with_timestamp(self, en: bool) -> Self {
        Self(if en {
            self.0 | 0x0010
        } else {
            self.0 & !0x0010
        })
    }
    /// Set or clear the RFU reserved bit (bit 5).
    pub const fn with_rfu(self, en: bool) -> Self {
        Self(if en {
            self.0 | 0x0020
        } else {
            self.0 & !0x0020
        })
    }
    /// Set or clear the Protocol ID bit (bit 6).
    pub const fn with_protocol_id(self, en: bool) -> Self {
        Self(if en {
            self.0 | 0x0040
        } else {
            self.0 & !0x0040
        })
    }
    /// Set or clear the Data Length bit (bit 7).
    pub const fn with_data_length(self, en: bool) -> Self {
        Self(if en {
            self.0 | 0x0080
        } else {
            self.0 & !0x0080
        })
    }
}

impl From<u16> for MetadataFlags {
    fn from(value: u16) -> Self {
        Self::from_raw(value)
    }
}

impl From<MetadataFlags> for u16 {
    fn from(value: MetadataFlags) -> Self {
        value.raw()
    }
}

/// Tag memory bank selector used by read/write access commands.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum MemBank {
    /// Gen2 Reserved bank (`0x00`).
    Reserved = 0x00,
    /// Gen2 EPC bank (`0x01`).
    Epc = 0x01,
    /// Gen2 TID bank (`0x02`).
    Tid = 0x02,
    /// Gen2 User bank (`0x03`).
    User = 0x03,
}

impl MemBank {
    /// Return the raw protocol value.
    pub const fn as_u8(self) -> u8 {
        self as u8
    }

    /// Parse a raw protocol value into a typed memory bank.
    pub fn from_u8(raw: u8) -> Result<Self, ProtocolError> {
        match raw {
            0x00 => Ok(Self::Reserved),
            0x01 => Ok(Self::Epc),
            0x02 => Ok(Self::Tid),
            0x03 => Ok(Self::User),
            _ => Err(ProtocolError::InvalidArgument(
                "membank must be one of 0x00..=0x03",
            )),
        }
    }
}

impl From<MemBank> for u8 {
    fn from(value: MemBank) -> Self {
        value.as_u8()
    }
}

/// Typed inventory embedded command content.
///
/// The protocol currently documents embedded command opcode `0x28`
/// (Read Tag Data) for inventory commands.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InventoryEmbeddedCommandContent {
    /// Embedded command `0x28` (Read Tag Data).
    ReadTagData(EmbeddedReadTagData),
}

impl InventoryEmbeddedCommandContent {
    fn encoded_len(&self) -> usize {
        match self {
            Self::ReadTagData(cmd) => 3 + cmd.data_field_len(),
        }
    }

    fn encode(&self, out: &mut Vec<u8>) {
        match self {
            Self::ReadTagData(cmd) => cmd.encode(out),
        }
    }
}

/// Typed fields for embedded command `0x28` (Read Tag Data).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EmbeddedReadTagData {
    /// Target memory bank.
    pub read_membank: MemBank,
    /// Start address in words.
    pub read_address_words: u32,
    /// Number of words to read.
    pub word_count: u8,
}

impl EmbeddedReadTagData {
    fn data_field_len(&self) -> usize {
        // Timeout(2) + Option(1) + MemBank(1) + Address(4) + WordCount(1)
        9
    }

    fn encode(&self, out: &mut Vec<u8>) {
        // Embedded command frame format:
        // Count(1)=1 | Length(1) | Opcode(1=0x28) | DataField(9)
        out.push(0x01);
        out.push(self.data_field_len() as u8);
        out.push(CommandCode::ReadTagData.as_u8());

        // Vendor docs state timeout/option are ignored for embedded reads.
        push_u16_be(out, 0x0000);
        out.push(0x00);
        out.push(self.read_membank.as_u8());
        push_u32_be(out, self.read_address_words);
        out.push(self.word_count);
    }
}

/// Asynchronous inventory subcommand IDs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u16)]
pub enum AsyncSubcommandCode {
    /// Start async inventory.
    Start = 0xAA48,
    /// Stop async inventory.
    Stop = 0xAA49,
}

/// Typed subcommand data for Start AsyncInventory (`0xAA48`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AsyncInventoryStartData {
    /// Metadata flags controlling which per-tag fields the reader returns.
    pub metadata_flags: MetadataFlags,
    /// Option byte, same meaning as command `0x22` select option bits.
    pub option: InventoryOption,
    /// Search flags (2 bytes), same meaning as command `0x22`.
    pub search_flags: InventorySearchFlags,
    /// Optional access password (4 bytes) when required by option.
    pub access_password: Option<u32>,
    /// Optional select content when select operation is enabled.
    pub select_content: Option<SelectContent>,
    /// Optional typed embedded command content.
    pub embedded_command_content: Option<InventoryEmbeddedCommandContent>,
}

impl AsyncInventoryStartData {
    fn encode(&self) -> Vec<u8> {
        let mut data = Vec::with_capacity(
            2 + 1
                + 2
                + if self.access_password.is_some() { 4 } else { 0 }
                + self
                    .select_content
                    .as_ref()
                    .map(|s| 4 + 2 + s.data.len()) // worst case: 2 bytes for bit_len
                    .unwrap_or(0)
                + self
                    .embedded_command_content
                    .as_ref()
                    .map(InventoryEmbeddedCommandContent::encoded_len)
                    .unwrap_or(0),
        );

        push_u16_be(&mut data, self.metadata_flags.raw());
        data.push(self.option.raw());
        push_u16_be(&mut data, self.search_flags.raw());

        if let Some(password) = self.access_password {
            push_u32_be(&mut data, password);
        }

        if let Some(select) = &self.select_content {
            select.encode_with_option(&mut data, self.option);
        }

        if let Some(embedded) = &self.embedded_command_content {
            embedded.encode(&mut data);
        }
        data
    }
}

/// Typed payload variants for command `0x91` (Set Antenna Ports).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AntennaPortsConfiguration {
    /// Set the single TX/RX pair used for tag access operations.
    AccessPair(AntennaPair),
    /// Set the ordered TX/RX pairs used during inventory operations.
    InventoryPairs(Vec<AntennaPair>),
    /// Set read/write power per logical TX antenna.
    ///
    /// Power fields use `0.01 dBm` units in the protocol docs, though current
    /// firmware is documented as effectively applying about `1 dBm` precision.
    Power(Vec<AntennaPower>),
    /// Set read/write power and settling time per logical TX antenna.
    ///
    /// Power fields use `0.01 dBm` units in the protocol docs, though current
    /// firmware is documented as effectively applying about `1 dBm` precision.
    PowerAndSettling(Vec<AntennaPowerSettling>),
}

impl AntennaPortsConfiguration {
    fn encode(&self) -> Result<Vec<u8>, ProtocolError> {
        match self {
            Self::AccessPair(pair) => Ok(vec![
                AntennaPortsOption::AccessPair.as_u8(),
                pair.tx,
                pair.rx,
            ]),
            Self::InventoryPairs(pairs) => {
                if pairs.is_empty() {
                    return Err(ProtocolError::InvalidArgument(
                        "inventory antenna pairs cannot be empty",
                    ));
                }
                let mut data = Vec::with_capacity(1 + pairs.len() * 2);
                data.push(AntennaPortsOption::InventoryPairs.as_u8());
                for pair in pairs {
                    data.push(pair.tx);
                    data.push(pair.rx);
                }
                Ok(data)
            }
            Self::Power(entries) => {
                if entries.is_empty() {
                    return Err(ProtocolError::InvalidArgument(
                        "antenna power entries cannot be empty",
                    ));
                }
                let mut data = Vec::with_capacity(1 + entries.len() * 5);
                data.push(AntennaPortsOption::Power.as_u8());
                for entry in entries {
                    data.push(entry.tx);
                    push_u16_be(&mut data, entry.read_power);
                    push_u16_be(&mut data, entry.write_power);
                }
                Ok(data)
            }
            Self::PowerAndSettling(entries) => {
                if entries.is_empty() {
                    return Err(ProtocolError::InvalidArgument(
                        "antenna power and settling entries cannot be empty",
                    ));
                }
                let mut data = Vec::with_capacity(1 + entries.len() * 7);
                data.push(AntennaPortsOption::PowerAndSettling.as_u8());
                for entry in entries {
                    data.push(entry.tx);
                    push_u16_be(&mut data, entry.read_power);
                    push_u16_be(&mut data, entry.write_power);
                    push_u16_be(&mut data, entry.settling_time_us);
                }
                Ok(data)
            }
        }
    }
}

/// Command builders for all protocol command groups.
pub struct HostCommand;

impl HostCommand {
    /// Build a raw command packet from command code and data field bytes.
    ///
    /// Use this when the crate does not yet provide a typed builder for a
    /// command variant you need.
    ///
    /// # Examples
    /// ```rust
    /// use rfid_silion_compat::command::HostCommand;
    ///
    /// let packet = HostCommand::raw(0x03, &[]).unwrap();
    /// assert_eq!(packet, vec![0xFF, 0x00, 0x03, 0x1D, 0x0C]);
    /// ```
    pub fn raw(command: u8, data: &[u8]) -> Result<Vec<u8>, ProtocolError> {
        build_host_frame(command, data)
    }

    /// Build command `0x01` (Write Flash).
    ///
    /// This bootloader command writes firmware words into flash memory.
    /// `finflag` indicates whether this is the final chunk (`0xFF` means last).
    pub fn write_flash(
        finflag: u8,
        write_addr: u32,
        write_data: &[u8],
    ) -> Result<Vec<u8>, ProtocolError> {
        if write_data.is_empty() || (write_data.len() % 4 != 0) {
            return Err(ProtocolError::InvalidArgument(
                "write_data must be non-empty and a multiple of 4 bytes",
            ));
        }
        if write_data.len() > 128 {
            return Err(ProtocolError::InvalidArgument(
                "write_data cannot exceed 128 bytes",
            ));
        }
        let words = (write_data.len() / 4) as u8;
        let mut data = Vec::with_capacity(1 + 4 + 1 + write_data.len());
        data.push(finflag);
        push_u32_be(&mut data, write_addr);
        data.push(words);
        data.extend_from_slice(write_data);
        build_host_frame(CommandCode::WriteFlash.as_u8(), &data)
    }

    /// Build command `0x02` (Read Flash).
    ///
    /// This bootloader command reads flash contents from `read_addr` for
    /// `read_len_words * 4` bytes.
    pub fn read_flash(read_addr: u32, read_len_words: u8) -> Result<Vec<u8>, ProtocolError> {
        if read_len_words > 32 {
            return Err(ProtocolError::InvalidArgument(
                "read_len_words must be <= 32",
            ));
        }
        let mut data = Vec::with_capacity(5);
        push_u32_be(&mut data, read_addr);
        data.push(read_len_words);
        build_host_frame(CommandCode::ReadFlash.as_u8(), &data)
    }

    /// Build command `0x03` (Get Version).
    ///
    /// Reader replies with bootloader/hardware/firmware version fields and
    /// supported protocol flags.
    ///
    /// # Examples
    /// ```rust
    /// use rfid_silion_compat::command::HostCommand;
    ///
    /// let packet = HostCommand::get_version().unwrap();
    /// assert_eq!(packet, vec![0xFF, 0x00, 0x03, 0x1D, 0x0C]);
    /// ```
    pub fn get_version() -> Result<Vec<u8>, ProtocolError> {
        build_host_frame(CommandCode::GetVersion.as_u8(), &[])
    }

    /// Build command `0x04` (Boot Firmware).
    ///
    /// Switches execution to app firmware when currently in bootloader.
    pub fn boot_firmware() -> Result<Vec<u8>, ProtocolError> {
        build_host_frame(CommandCode::BootFirmware.as_u8(), &[])
    }

    /// Build command `0x06` (Set Baud Rate).
    ///
    /// `baud_rate` is encoded as a 32-bit big-endian integer as required by
    /// the protocol documentation.
    ///
    /// # Examples
    /// ```rust
    /// use rfid_silion_compat::command::HostCommand;
    ///
    /// // 115200 decimal = 0x0001C200
    /// let packet = HostCommand::set_baud_rate(115_200).unwrap();
    /// assert_eq!(packet, vec![0xFF, 0x04, 0x06, 0x00, 0x01, 0xC2, 0x00, 0xA4, 0x60]);
    /// ```
    pub fn set_baud_rate(baud_rate: u32) -> Result<Vec<u8>, ProtocolError> {
        let mut data = Vec::with_capacity(4);
        push_u32_be(&mut data, baud_rate);
        build_host_frame(CommandCode::SetBaudRate.as_u8(), &data)
    }

    /// Build command `0x08` (Verify Firmware).
    ///
    /// This is the bootloader verification command used after firmware burn.
    pub fn verify_firmware(
        check_addr: u32,
        check_data_len_words: u32,
        check_crc: u32,
    ) -> Result<Vec<u8>, ProtocolError> {
        let mut data = Vec::with_capacity(12);
        push_u32_be(&mut data, check_addr);
        push_u32_be(&mut data, check_data_len_words);
        push_u32_be(&mut data, check_crc);
        build_host_frame(CommandCode::VerifyFirmware.as_u8(), &data)
    }

    /// Build command `0x09` (Boot Bootloader).
    ///
    /// Requests transition from app firmware back to bootloader.
    pub fn boot_bootloader() -> Result<Vec<u8>, ProtocolError> {
        build_host_frame(CommandCode::BootBootloader.as_u8(), &[])
    }

    /// Build command `0x0C` (Get Run Phase).
    ///
    /// Reader returns whether it is currently in bootloader or app firmware.
    ///
    /// # Examples
    /// ```rust
    /// use rfid_silion_compat::command::HostCommand;
    ///
    /// let packet = HostCommand::get_run_phase().unwrap();
    /// assert_eq!(packet, vec![0xFF, 0x00, 0x0C, 0x1D, 0x03]);
    /// ```
    pub fn get_run_phase() -> Result<Vec<u8>, ProtocolError> {
        build_host_frame(CommandCode::GetRunPhase.as_u8(), &[])
    }

    /// Build command `0x10` (Get Serial Number).
    ///
    /// `option` and `data_flags` are reserved by the vendor docs.
    pub fn get_serial_number(option: u8, data_flags: u8) -> Result<Vec<u8>, ProtocolError> {
        build_host_frame(CommandCode::GetSerialNumber.as_u8(), &[option, data_flags])
    }

    /// Build command `0x21` (Single Tag Inventory).
    ///
    /// Inventories one tag within `timeout_ms`. Optional metadata and select
    /// filter fields follow the protocol option bits.
    pub fn single_tag_inventory(
        timeout_ms: u16,
        option: InventoryOption,
        metadata_flags: Option<MetadataFlags>,
        select: Option<SelectContent>,
    ) -> Result<Vec<u8>, ProtocolError> {
        if option.single_tag_metadata_enabled() && metadata_flags.is_none() {
            return Err(ProtocolError::InvalidArgument(
                "single_tag_inventory requires metadata_flags when option bit 4 (0x10) is set",
            ));
        }
        if !option.single_tag_metadata_enabled() && metadata_flags.is_some() {
            return Err(ProtocolError::InvalidArgument(
                "single_tag_inventory must omit metadata_flags when option bit 4 (0x10) is clear",
            ));
        }

        let mut data = Vec::new();
        push_u16_be(&mut data, timeout_ms);
        data.push(option.raw());
        if let Some(flags) = metadata_flags {
            push_u16_be(&mut data, flags.raw());
        }
        if let Some(sel) = select {
            sel.encode_with_option(&mut data, option);
        }
        build_host_frame(CommandCode::SingleTagInventory.as_u8(), &data)
    }

    /// Build command `0x22` (Synchronous Inventory).
    ///
    /// Performs timed multi-tag inventory and archives tag results into reader
    /// tag buffer for later retrieval by command `0x29`.
    pub fn synchronous_inventory(
        option: InventoryOption,
        search_flags: u16,
        timeout_ms: u16,
        access_password: Option<u32>,
        select: Option<SelectContent>,
        embedded_command: Option<&[u8]>,
    ) -> Result<Vec<u8>, ProtocolError> {
        Self::synchronous_inventory_raw_embedded(
            option,
            InventorySearchFlags::from_raw(search_flags),
            timeout_ms,
            access_password,
            select,
            embedded_command,
        )
    }

    /// Build command `0x22` (Synchronous Inventory) using typed option/flags
    /// and typed embedded command content.
    pub fn synchronous_inventory_typed(
        option: InventoryOption,
        search_flags: InventorySearchFlags,
        timeout_ms: u16,
        access_password: Option<u32>,
        select: Option<SelectContent>,
        embedded_command: Option<InventoryEmbeddedCommandContent>,
    ) -> Result<Vec<u8>, ProtocolError> {
        let mut data = Vec::new();
        data.push(option.raw());
        push_u16_be(&mut data, search_flags.raw());
        push_u16_be(&mut data, timeout_ms);
        if let Some(pw) = access_password {
            push_u32_be(&mut data, pw);
        }
        if let Some(sel) = select {
            sel.encode_with_option(&mut data, option);
        }
        if let Some(embedded) = embedded_command {
            embedded.encode(&mut data);
        }
        build_host_frame(CommandCode::SynchronousInventory.as_u8(), &data)
    }

    /// Build command `0x22` (Synchronous Inventory) with raw embedded bytes.
    ///
    /// Prefer [`HostCommand::synchronous_inventory_typed`] where possible.
    pub fn synchronous_inventory_raw_embedded(
        option: InventoryOption,
        search_flags: InventorySearchFlags,
        timeout_ms: u16,
        access_password: Option<u32>,
        select: Option<SelectContent>,
        embedded_command: Option<&[u8]>,
    ) -> Result<Vec<u8>, ProtocolError> {
        let mut data = Vec::new();
        data.push(option.raw());
        push_u16_be(&mut data, search_flags.raw());
        push_u16_be(&mut data, timeout_ms);
        if let Some(pw) = access_password {
            push_u32_be(&mut data, pw);
        }
        if let Some(sel) = select {
            sel.encode_with_option(&mut data, option);
        }
        if let Some(embedded) = embedded_command {
            data.extend_from_slice(embedded);
        }
        build_host_frame(CommandCode::SynchronousInventory.as_u8(), &data)
    }

    /// Build command `0x29` (Get Tag Buffer).
    ///
    /// Retrieves archived tag EPC/metadata records from synchronous inventory.
    pub fn get_tag_buffer(
        metadata_flags: MetadataFlags,
        option: InventoryOption,
    ) -> Result<Vec<u8>, ProtocolError> {
        let mut data = Vec::with_capacity(3);
        push_u16_be(&mut data, metadata_flags.raw());
        data.push(option.raw());
        build_host_frame(CommandCode::GetTagBuffer.as_u8(), &data)
    }

    /// Build command `0x23` (Write Tag EPC).
    ///
    /// Writes EPC data and lets reader update EPC length bits in PC word.
    pub fn write_tag_epc(
        timeout_ms: u16,
        option: InventoryOption,
        access_password: Option<u32>,
        select: Option<SelectContent>,
        epc: &[u8],
    ) -> Result<Vec<u8>, ProtocolError> {
        if epc.is_empty() {
            return Err(ProtocolError::InvalidArgument("epc cannot be empty"));
        }
        let mut data = Vec::new();
        push_u16_be(&mut data, timeout_ms);
        data.push(option.raw());
        if option.raw() == 0x00 {
            data.push(0x00); // RFU byte required when option is 0x00
        }
        if option.raw() != 0x00 {
            if let Some(pw) = access_password {
                push_u32_be(&mut data, pw);
            } else {
                push_u32_be(&mut data, 0x00000000);
            }
        }
        if let Some(sel) = select {
            sel.encode_with_option(&mut data, option);
        }
        data.extend_from_slice(epc);
        build_host_frame(CommandCode::WriteTagEpc.as_u8(), &data)
    }

    /// Build command `0x24` (Write Tag Data).
    ///
    /// Writes user-supplied bytes to a target bank/address on selected tag.
    pub fn write_tag_data(
        timeout_ms: u16,
        option: InventoryOption,
        write_address_words: u32,
        write_membank: MemBank,
        access_password: Option<u32>,
        select: Option<SelectContent>,
        write_data: &[u8],
    ) -> Result<Vec<u8>, ProtocolError> {
        if write_data.is_empty() || (write_data.len() % 2 != 0) {
            return Err(ProtocolError::InvalidArgument(
                "write_data must be non-empty and multiple of 2 bytes",
            ));
        }
        if write_data.len() > 64 {
            return Err(ProtocolError::InvalidArgument(
                "write_data must be <= 64 bytes",
            ));
        }
        let mut data = Vec::new();
        push_u16_be(&mut data, timeout_ms);
        data.push(option.raw());
        push_u32_be(&mut data, write_address_words);
        data.push(write_membank.as_u8());
        if let Some(pw) = access_password {
            push_u32_be(&mut data, pw);
        } else {
            push_u32_be(&mut data, 0x00000000);
        }
        if let Some(sel) = select {
            sel.encode_with_option(&mut data, option);
        }
        data.extend_from_slice(write_data);
        build_host_frame(CommandCode::WriteTagData.as_u8(), &data)
    }

    /// Build command `0x25` (Lock Tag).
    ///
    /// Applies Gen2 lock actions defined by `mask_bits` and `action_bits`.
    pub fn lock_tag(
        timeout_ms: u16,
        option: InventoryOption,
        access_password: u32,
        mask_bits: u16,
        action_bits: u16,
        select: Option<SelectContent>,
    ) -> Result<Vec<u8>, ProtocolError> {
        let mut data = Vec::new();
        push_u16_be(&mut data, timeout_ms);
        data.push(option.raw());
        push_u32_be(&mut data, access_password);
        push_u16_be(&mut data, mask_bits);
        push_u16_be(&mut data, action_bits);
        if let Some(sel) = select {
            sel.encode_with_option(&mut data, option);
        }
        build_host_frame(CommandCode::LockTag.as_u8(), &data)
    }

    /// Build command `0x26` (Kill Tag).
    ///
    /// Permanently kills a matching tag using `kill_password`.
    pub fn kill_tag(
        timeout_ms: u16,
        option: InventoryOption,
        kill_password: u32,
        select: Option<SelectContent>,
    ) -> Result<Vec<u8>, ProtocolError> {
        let mut data = Vec::new();
        push_u16_be(&mut data, timeout_ms);
        data.push(option.raw());
        push_u32_be(&mut data, kill_password);
        data.push(0x00); // RFU byte required by protocol docs
        if let Some(sel) = select {
            sel.encode_with_option(&mut data, option);
        }
        build_host_frame(CommandCode::KillTag.as_u8(), &data)
    }

    /// Build command `0x28` (Read Tag Data).
    ///
    /// Reads memory words from a tag bank and optionally requests metadata.
    pub fn read_tag_data(
        timeout_ms: u16,
        option: InventoryOption,
        metadata_flags: Option<MetadataFlags>,
        read_membank: MemBank,
        read_address_words: u32,
        word_count: u8,
        access_password: Option<u32>,
        select: Option<SelectContent>,
    ) -> Result<Vec<u8>, ProtocolError> {
        if word_count == 0 || word_count > 96 {
            return Err(ProtocolError::InvalidArgument(
                "word_count must be in 1..=96",
            ));
        }
        let mut data = Vec::new();
        push_u16_be(&mut data, timeout_ms);
        data.push(option.raw());
        if let Some(flags) = metadata_flags {
            push_u16_be(&mut data, flags.raw());
        }
        data.push(read_membank.as_u8());
        push_u32_be(&mut data, read_address_words);
        data.push(word_count);
        if let Some(pw) = access_password {
            push_u32_be(&mut data, pw);
        } else {
            push_u32_be(&mut data, 0x00000000);
        }
        if let Some(sel) = select {
            sel.encode_with_option(&mut data, option);
        }
        println!("Read Tag Data command data: {:02X?}", data);
        build_host_frame(CommandCode::ReadTagData.as_u8(), &data)
    }

    /// Build command `0x91` (Set Antenna Ports).
    ///
    /// The payload shape depends on the configuration variant and is encoded
    /// according to the option-specific layout from the protocol docs.
    ///
    /// # Examples
    /// ```rust
    /// use rfid_silion_compat::{AntennaPair, AntennaPortsConfiguration};
    /// use rfid_silion_compat::command::HostCommand;
    ///
    /// let packet = HostCommand::set_antenna_ports(&AntennaPortsConfiguration::AccessPair(
    ///     AntennaPair { tx: 0x01, rx: 0x01 },
    /// ))
    /// .unwrap();
    /// assert_eq!(packet, vec![0xFF, 0x03, 0x91, 0x00, 0x01, 0x01, 0x62, 0x87]);
    /// ```
    pub fn set_antenna_ports(config: &AntennaPortsConfiguration) -> Result<Vec<u8>, ProtocolError> {
        let data = config.encode()?;
        build_host_frame(CommandCode::SetAntennaPorts.as_u8(), &data)
    }

    /// Build command `0x93` (Set Current Tag Protocol).
    ///
    /// Current firmware expects `protocol` equal to `0x0005` (GEN2).
    pub fn set_current_tag_protocol(protocol: u16) -> Result<Vec<u8>, ProtocolError> {
        let mut data = Vec::with_capacity(2);
        push_u16_be(&mut data, protocol);
        build_host_frame(CommandCode::SetCurrentTagProtocol.as_u8(), &data)
    }

    /// Build command `0x95` (Set Frequency Hopping).
    ///
    /// Sets hop table or reserved regulatory hopping time format.
    pub fn set_frequency_hopping(data_field: &[u8]) -> Result<Vec<u8>, ProtocolError> {
        build_host_frame(CommandCode::SetFrequencyHopping.as_u8(), data_field)
    }

    /// Build command `0x96` (Set GPO / Get GPO status).
    ///
    /// Non-empty `data_field` sets GPO pin states. Empty data requests current
    /// GPO status in the response payload.
    pub fn set_gpo(data_field: &[u8]) -> Result<Vec<u8>, ProtocolError> {
        build_host_frame(CommandCode::SetGpo.as_u8(), data_field)
    }

    /// Build command `0x97` (Set Current Region).
    ///
    /// Selects working region code used by frequency/hopping constraints.
    ///
    /// # Examples
    /// ```rust
    /// use rfid_silion_compat::RegionCode;
    /// use rfid_silion_compat::command::HostCommand;
    ///
    /// let packet = HostCommand::set_current_region(RegionCode::NorthAmerica).unwrap();
    /// assert_eq!(packet, vec![0xFF, 0x01, 0x97, 0x01, 0x4B, 0xBC]);
    /// ```
    pub fn set_current_region(region_code: RegionCode) -> Result<Vec<u8>, ProtocolError> {
        build_host_frame(
            CommandCode::SetCurrentRegion.as_u8(),
            &[region_code.as_u8()],
        )
    }

    /// Build command `0x9A` (Set Reader Configuration).
    ///
    /// Sets one reader key/value under `option` 0x01 format.
    pub fn set_reader_configuration(
        option: u8,
        key: u8,
        value: u8,
    ) -> Result<Vec<u8>, ProtocolError> {
        build_host_frame(
            CommandCode::SetReaderConfiguration.as_u8(),
            &[option, key, value],
        )
    }

    /// Build command `0x9B` (Set Protocol Configuration).
    ///
    /// Sets protocol parameter values (session, target, Q, etc.) according to
    /// option/value presence required by the selected parameter.
    pub fn set_protocol_configuration(
        protocol_value: u8,
        parameter: u8,
        option: Option<u8>,
        value: Option<u8>,
    ) -> Result<Vec<u8>, ProtocolError> {
        let mut data = vec![protocol_value, parameter];
        if let Some(opt) = option {
            data.push(opt);
        }
        if let Some(v) = value {
            data.push(v);
        }
        build_host_frame(CommandCode::SetProtocolConfiguration.as_u8(), &data)
    }

    /// Build command `0x61` (Get Antenna Ports).
    ///
    /// `option` selects which antenna view is requested (access pair,
    /// inventory pairs, powers, powers+settling, or connection states).
    pub fn get_antenna_ports(option: AntennaPortsOption) -> Result<Vec<u8>, ProtocolError> {
        build_host_frame(CommandCode::GetAntennaPorts.as_u8(), &[option.as_u8()])
    }

    /// Build command `0x63` (Get Current Tag Protocol).
    ///
    /// Returns active tag protocol (currently GEN2 `0x0005`).
    pub fn get_current_tag_protocol() -> Result<Vec<u8>, ProtocolError> {
        build_host_frame(CommandCode::GetCurrentTagProtocol.as_u8(), &[])
    }

    /// Build command `0x65` (Get Frequency Hopping).
    ///
    /// `None` requests the full hop table. `Some(0x01)` requests regulatory
    /// hopping time payload format.
    ///
    /// # Examples
    /// ```rust
    /// use rfid_silion_compat::command::HostCommand;
    ///
    /// let table_req = HostCommand::get_frequency_hopping(None).unwrap();
    /// assert_eq!(table_req, vec![0xFF, 0x00, 0x65, 0x1D, 0x6A]);
    ///
    /// let hop_time_req = HostCommand::get_frequency_hopping(Some(0x01)).unwrap();
    /// assert_eq!(hop_time_req, vec![0xFF, 0x01, 0x65, 0x01, 0xB9, 0xBC]);
    /// ```
    pub fn get_frequency_hopping(option: Option<u8>) -> Result<Vec<u8>, ProtocolError> {
        match option {
            Some(v) => build_host_frame(CommandCode::GetFrequencyHopping.as_u8(), &[v]),
            None => build_host_frame(CommandCode::GetFrequencyHopping.as_u8(), &[]),
        }
    }

    /// Build command `0x66` (Get GPI).
    ///
    /// Returns input pin states ordered by pin number.
    pub fn get_gpi() -> Result<Vec<u8>, ProtocolError> {
        build_host_frame(CommandCode::GetGpi.as_u8(), &[])
    }

    /// Build command `0x67` (Get Current Region).
    ///
    /// Returns active region code.
    pub fn get_current_region() -> Result<Vec<u8>, ProtocolError> {
        build_host_frame(CommandCode::GetCurrentRegion.as_u8(), &[])
    }

    /// Build command `0x71` (Get Available Regions).
    ///
    /// Returns region codes supported by the connected reader firmware.
    pub fn get_available_regions() -> Result<Vec<u8>, ProtocolError> {
        build_host_frame(CommandCode::GetAvailableRegions.as_u8(), &[])
    }

    /// Build command `0x6A` (Get Reader Configuration).
    ///
    /// Requests one key under a given option namespace.
    pub fn get_reader_configuration(option: u8, key: u8) -> Result<Vec<u8>, ProtocolError> {
        build_host_frame(CommandCode::GetReaderConfiguration.as_u8(), &[option, key])
    }

    /// Build command `0x6B` (Get Protocol Configuration).
    ///
    /// Requests one protocol parameter for a selected protocol id.
    ///
    /// # Examples
    /// ```rust
    /// use rfid_silion_compat::command::HostCommand;
    ///
    /// // Protocol 0x05 (GEN2), parameter 0x00 (session)
    /// let packet = HostCommand::get_protocol_configuration(0x05, 0x00).unwrap();
    /// assert_eq!(packet, vec![0xFF, 0x02, 0x6B, 0x05, 0x00, 0x3A, 0x6F]);
    /// ```
    pub fn get_protocol_configuration(
        protocol_value: u8,
        parameter: u8,
    ) -> Result<Vec<u8>, ProtocolError> {
        build_host_frame(
            CommandCode::GetProtocolConfiguration.as_u8(),
            &[protocol_value, parameter],
        )
    }

    /// Build command `0x72` (Get Current Temperature).
    ///
    /// Returns reader board temperature as one byte.
    pub fn get_current_temperature() -> Result<Vec<u8>, ProtocolError> {
        build_host_frame(CommandCode::GetCurrentTemperature.as_u8(), &[])
    }

    /// Build command `0xAA` Start Async Inventory subcommand (`0xAA48`).
    ///
    /// `start` follows the documented subcommand data format:
    /// `MetadataFlags(2) | Option(1) | SearchFlags(2) | [AccessPassword(4)] |
    /// [SelectContent] | [EmbeddedCommandContent]`.
    ///
    /// # Examples
    /// ```rust
    /// use rfid_silion_compat::{
    ///     EmbeddedReadTagData, InventoryEmbeddedCommandContent, InventorySearchFlags, MemBank,
    ///     MetadataFlags,
    /// };
    /// use rfid_silion_compat::command::{AsyncInventoryStartData, HostCommand, InventoryOption};
    ///
    /// let search_flags = InventorySearchFlags::new()
    ///     .with_async_heartbeat(true)
    ///     .with_async_auto_stop(false)
    ///     .with_embedded_command(true)
    ///     .with_async_rest_ratio_steps(3)
    ///     .unwrap();
    ///
    /// let start = AsyncInventoryStartData {
    ///     metadata_flags: MetadataFlags::ALL,
    ///     option: InventoryOption::default(),
    ///     search_flags,
    ///     access_password: None,
    ///     select_content: None,
    ///     embedded_command_content: Some(InventoryEmbeddedCommandContent::ReadTagData(
    ///         EmbeddedReadTagData {
    ///             read_membank: MemBank::Tid,
    ///             read_address_words: 0,
    ///             word_count: 2,
    ///         },
    ///     )),
    /// };
    ///
    /// let packet = HostCommand::async_start(&start).unwrap();
    /// assert_eq!(packet[0], 0xFF);
    /// assert_eq!(packet[2], 0xAA);
    /// ```
    pub fn async_start(start: &AsyncInventoryStartData) -> Result<Vec<u8>, ProtocolError> {
        let subcommand_data = start.encode();
        Self::async_inventory(AsyncSubcommandCode::Start, &subcommand_data)
    }

    /// Build command `0xAA` Stop Async Inventory subcommand (`0xAA49`).
    ///
    /// # Examples
    /// ```rust
    /// use rfid_silion_compat::command::HostCommand;
    ///
    /// let packet = HostCommand::async_stop().unwrap();
    /// assert_eq!(
    ///     packet,
    ///     vec![
    ///         0xFF, 0x0E, 0xAA, 0x4D, 0x6F, 0x64, 0x75, 0x6C, 0x65, 0x74,
    ///         0x65, 0x63, 0x68, 0xAA, 0x49, 0xF3, 0xBB, 0x03, 0x91,
    ///     ]
    /// );
    /// ```
    pub fn async_stop() -> Result<Vec<u8>, ProtocolError> {
        Self::async_inventory(AsyncSubcommandCode::Stop, &[])
    }

    /// Build a generic `0xAA` asynchronous inventory command packet.
    ///
    /// This inserts the fixed marker (`Moduletech`), subcommand, subcommand
    /// payload, sub-CRC (8-bit sum), and terminator (`0xBB`) before wrapping the
    /// bytes in a normal host frame.
    pub fn async_inventory(
        subcommand: AsyncSubcommandCode,
        subcommand_data: &[u8],
    ) -> Result<Vec<u8>, ProtocolError> {
        let mut data = Vec::with_capacity(10 + 2 + subcommand_data.len() + 2);
        data.extend_from_slice(ASYNC_MARKER);
        push_u16_be(&mut data, subcommand as u16);
        data.extend_from_slice(subcommand_data);
        let sub_crc = subcommand_crc(subcommand as u16, subcommand_data);
        data.push(sub_crc);
        data.push(ASYNC_TERMINATOR);
        build_host_frame(CommandCode::AsynchronousInventory.as_u8(), &data)
    }
}