pokeys-lib 1.0.4

Pure Rust core library for PoKeys device control - USB/Network connectivity, I/O, PWM, encoders, SPI/I2C protocols
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
//! Encoder support for PoKeys devices
//!
//! This module implements the complete PoKeys encoder protocol specification,
//! supporting up to 25 normal encoders, 3 fast encoders, and 1 ultra-fast encoder.
//!
//! Features:
//! - 4x and 2x sampling modes for precise position tracking
//! - Key mapping for encoder directions
//! - Bulk operations for efficient multi-encoder management
//! - Fast and ultra-fast encoder support for high-speed applications

use crate::device::PoKeysDevice;
use crate::error::{PoKeysError, Result};
use serde::{Deserialize, Serialize};

/// Maximum number of normal encoders supported
pub const MAX_ENCODERS: usize = 25;

/// Maximum number of fast encoders supported  
pub const MAX_FAST_ENCODERS: usize = 3;

/// Ultra-fast encoder index (encoder 25)
pub const ULTRA_FAST_ENCODER_INDEX: u8 = 25;

/// Encoder configuration options
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EncoderOptions {
    /// Enable encoder
    pub enabled: bool,
    /// 4x sampling mode (both A and B edges counted)
    pub sampling_4x: bool,
    /// 2x sampling mode (only A edges counted)
    pub sampling_2x: bool,
    /// Direct key mapping for direction A
    pub direct_key_mapping_a: bool,
    /// Macro mapping for direction A
    pub macro_mapping_a: bool,
    /// Direct key mapping for direction B
    pub direct_key_mapping_b: bool,
    /// Macro mapping for direction B
    pub macro_mapping_b: bool,
}

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

impl EncoderOptions {
    /// Create new encoder options with all features disabled
    pub fn new() -> Self {
        Self {
            enabled: false,
            sampling_4x: false,
            sampling_2x: false,
            direct_key_mapping_a: false,
            macro_mapping_a: false,
            direct_key_mapping_b: false,
            macro_mapping_b: false,
        }
    }

    /// Create encoder options with 4x sampling enabled
    pub fn with_4x_sampling() -> Self {
        Self {
            enabled: true,
            sampling_4x: true,
            sampling_2x: false,
            direct_key_mapping_a: false,
            macro_mapping_a: false,
            direct_key_mapping_b: false,
            macro_mapping_b: false,
        }
    }

    /// Create encoder options with 2x sampling enabled
    pub fn with_2x_sampling() -> Self {
        Self {
            enabled: true,
            sampling_4x: false,
            sampling_2x: true,
            direct_key_mapping_a: false,
            macro_mapping_a: false,
            direct_key_mapping_b: false,
            macro_mapping_b: false,
        }
    }

    /// Convert options to protocol byte format
    /// Bit layout: [macro_b][key_b][macro_a][key_a][reserved][2x][4x][enable]
    pub fn to_byte(&self) -> u8 {
        let mut options = 0u8;
        if self.enabled {
            options |= 1 << 0;
        }
        if self.sampling_4x {
            options |= 1 << 1;
        }
        if self.sampling_2x {
            options |= 1 << 2;
        }
        // bit 3 is reserved
        if self.direct_key_mapping_a {
            options |= 1 << 4;
        }
        if self.macro_mapping_a {
            options |= 1 << 5;
        }
        if self.direct_key_mapping_b {
            options |= 1 << 6;
        }
        if self.macro_mapping_b {
            options |= 1 << 7;
        }
        options
    }

    /// Create options from protocol byte format
    pub fn from_byte(byte: u8) -> Self {
        Self {
            enabled: (byte & (1 << 0)) != 0,
            sampling_4x: (byte & (1 << 1)) != 0,
            sampling_2x: (byte & (1 << 2)) != 0,
            direct_key_mapping_a: (byte & (1 << 4)) != 0,
            macro_mapping_a: (byte & (1 << 5)) != 0,
            direct_key_mapping_b: (byte & (1 << 6)) != 0,
            macro_mapping_b: (byte & (1 << 7)) != 0,
        }
    }
}

/// Fast-encoder hardware configuration selector (protocol command `0xCE`
/// byte 3 = "FastEncodersConfiguration").
///
/// Only one configuration may be active at a time. Newer PoKeys56/57 devices
/// support only [`Config2`](Self::Config2); older PoKeys55 hardware supports
/// both.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FastEncoderConfiguration {
    /// Fast encoders disabled.
    Disabled,
    /// Config 1 — encoder 1 on pins 1-2, encoder 2 on pins 3-4, encoder 3 on pins 15-16.
    /// (PoKeys55-era devices only.)
    Config1,
    /// Config 2 — encoder 1 on pins 1-2, encoder 2 on pins 5-6, encoder 3 on pins 15-16.
    /// Supported by all devices with fast encoder hardware.
    Config2,
}

impl FastEncoderConfiguration {
    /// Byte value for the "FastEncodersConfiguration" field of command `0xCE`.
    /// Matches the PoKeysLib C reference constants:
    /// `PK_FASTENCODER_CONF_CFG1 = 0x01`, `PK_FASTENCODER_CONF_CFG2 = 0x10`.
    pub fn to_byte(self) -> u8 {
        match self {
            FastEncoderConfiguration::Disabled => 0x00,
            FastEncoderConfiguration::Config1 => 0x01,
            FastEncoderConfiguration::Config2 => 0x10,
        }
    }

    /// Decode the byte field back to a configuration. Unknown values map to
    /// [`Disabled`](Self::Disabled).
    pub fn from_byte(byte: u8) -> Self {
        match byte {
            0x01 => FastEncoderConfiguration::Config1,
            0x10 => FastEncoderConfiguration::Config2,
            _ => FastEncoderConfiguration::Disabled,
        }
    }
}

/// Per-encoder options for the fast encoders (protocol command `0xCE`
/// byte 4 = "FastEncodersOptions").
///
/// Bit layout matches the PoKeysLib C reference (`ePK_FastEncoderOptions`):
///
/// | Bit | Mask | Meaning                           |
/// |-----|------|-----------------------------------|
/// | 4   | 0x10 | Disable 4x sampling (default is 4x on). |
/// | 5   | 0x20 | Invert direction of fast encoder 1. |
/// | 6   | 0x40 | Invert direction of fast encoder 2. |
/// | 7   | 0x80 | Invert direction of fast encoder 3. |
///
/// Bits 0-3 are reserved (the low nibble carries nothing — the configuration
/// selector lives in a separate byte, see [`FastEncoderConfiguration`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct FastEncoderOptions {
    /// Disable 4x sampling for the fast encoders (default is 4x enabled).
    pub disable_4x_sampling: bool,
    /// Invert direction of fast encoder 1.
    pub invert_direction_1: bool,
    /// Invert direction of fast encoder 2.
    pub invert_direction_2: bool,
    /// Invert direction of fast encoder 3.
    pub invert_direction_3: bool,
}

/// Bit 4 (`0x10`) of the fast-encoders options byte — disable 4x sampling.
pub(crate) const FAST_ENCODER_DISABLE_4X_SAMPLING: u8 = 0x10;
/// Bit 5 (`0x20`) — invert direction of fast encoder 1.
pub(crate) const FAST_ENCODER_INVERT_E1: u8 = 0x20;
/// Bit 6 (`0x40`) — invert direction of fast encoder 2.
pub(crate) const FAST_ENCODER_INVERT_E2: u8 = 0x40;
/// Bit 7 (`0x80`) — invert direction of fast encoder 3.
pub(crate) const FAST_ENCODER_INVERT_E3: u8 = 0x80;

impl FastEncoderOptions {
    /// Pack the options into the protocol byte (byte 4 of command `0xCE`).
    pub fn to_byte(self) -> u8 {
        let mut b = 0u8;
        if self.disable_4x_sampling {
            b |= FAST_ENCODER_DISABLE_4X_SAMPLING;
        }
        if self.invert_direction_1 {
            b |= FAST_ENCODER_INVERT_E1;
        }
        if self.invert_direction_2 {
            b |= FAST_ENCODER_INVERT_E2;
        }
        if self.invert_direction_3 {
            b |= FAST_ENCODER_INVERT_E3;
        }
        b
    }

    /// Decode an options byte back into the struct (reserved bits ignored).
    pub fn from_byte(byte: u8) -> Self {
        Self {
            disable_4x_sampling: (byte & FAST_ENCODER_DISABLE_4X_SAMPLING) != 0,
            invert_direction_1: (byte & FAST_ENCODER_INVERT_E1) != 0,
            invert_direction_2: (byte & FAST_ENCODER_INVERT_E2) != 0,
            invert_direction_3: (byte & FAST_ENCODER_INVERT_E3) != 0,
        }
    }
}

/// Ultra-fast encoder options (protocol command `0x1C` byte 4 = "additional options").
///
/// Bit layout matches PoKeysLib C reference (`ePK_UltraFastEncoderOptions`):
///
/// | Bit | Mask | Meaning                        |
/// |-----|------|--------------------------------|
/// | 0   | 0x01 | Invert direction.              |
/// | 1   | 0x02 | Signal mode: `false` = quadrature (A/B), `true` = direction + clock. |
/// | 2   | 0x04 | Enable 4x sampling.            |
///
/// Bits 3-7 are reserved.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct UltraFastEncoderOptions {
    /// Invert direction (bit 0).
    pub invert_direction: bool,
    /// Signal mode. `false` = A/B are quadrature inputs; `true` = A is the
    /// direction signal and B is the clock signal.
    pub signal_mode_direction_clock: bool,
    /// Enable 4x sampling (both edges of A and B counted).
    pub enable_4x_sampling: bool,
}

/// Bit 0 — invert direction (ultra-fast).
pub(crate) const UFENC_INVERT_DIRECTION: u8 = 0x01;
/// Bit 1 — signal mode (ultra-fast).
pub(crate) const UFENC_SIGNAL_MODE: u8 = 0x02;
/// Bit 2 — enable 4x sampling (ultra-fast).
pub(crate) const UFENC_ENABLE_4X_SAMPLING: u8 = 0x04;

impl UltraFastEncoderOptions {
    /// Pack into the options byte sent to the device.
    pub fn to_byte(self) -> u8 {
        let mut b = 0u8;
        if self.invert_direction {
            b |= UFENC_INVERT_DIRECTION;
        }
        if self.signal_mode_direction_clock {
            b |= UFENC_SIGNAL_MODE;
        }
        if self.enable_4x_sampling {
            b |= UFENC_ENABLE_4X_SAMPLING;
        }
        b
    }

    /// Decode from a device-reported options byte.
    pub fn from_byte(byte: u8) -> Self {
        Self {
            invert_direction: (byte & UFENC_INVERT_DIRECTION) != 0,
            signal_mode_direction_clock: (byte & UFENC_SIGNAL_MODE) != 0,
            enable_4x_sampling: (byte & UFENC_ENABLE_4X_SAMPLING) != 0,
        }
    }
}

/// Encoder data structure containing all encoder state and configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EncoderData {
    /// Current encoder value (32-bit signed)
    pub encoder_value: i32,
    /// Encoder configuration options
    pub encoder_options: u8,
    /// Channel A input pin (0-54)
    pub channel_a_pin: u8,
    /// Channel B input pin (0-54)
    pub channel_b_pin: u8,
    /// Direction A key code for keyboard mapping
    pub dir_a_key_code: u8,
    /// Direction A key modifier for keyboard mapping
    pub dir_a_key_modifier: u8,
    /// Direction B key code for keyboard mapping
    pub dir_b_key_code: u8,
    /// Direction B key modifier for keyboard mapping
    pub dir_b_key_modifier: u8,
}

impl EncoderData {
    /// Create new encoder data with default values
    pub fn new() -> Self {
        Self {
            encoder_value: 0,
            encoder_options: 0,
            channel_a_pin: 0,
            channel_b_pin: 0,
            dir_a_key_code: 0,
            dir_a_key_modifier: 0,
            dir_b_key_code: 0,
            dir_b_key_modifier: 0,
        }
    }

    /// Get encoder options as structured data
    pub fn get_options(&self) -> EncoderOptions {
        EncoderOptions::from_byte(self.encoder_options)
    }

    /// Set encoder options from structured data
    pub fn set_options(&mut self, options: EncoderOptions) {
        self.encoder_options = options.to_byte();
    }

    /// Check if encoder is enabled
    pub fn is_enabled(&self) -> bool {
        (self.encoder_options & 1) != 0
    }

    /// Check if 4x sampling is enabled
    pub fn is_4x_sampling(&self) -> bool {
        (self.encoder_options & (1 << 1)) != 0
    }

    /// Check if 2x sampling is enabled
    pub fn is_2x_sampling(&self) -> bool {
        (self.encoder_options & (1 << 2)) != 0
    }

    /// Get sampling mode as string for debugging
    pub fn sampling_mode_str(&self) -> &'static str {
        if self.is_4x_sampling() {
            "4x (both edges)"
        } else if self.is_2x_sampling() {
            "2x (A edges only)"
        } else {
            "1x (disabled)"
        }
    }
}

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

impl PoKeysDevice {
    /// Configure encoder with pins and options
    /// Protocol: 0x11 - Individual encoder settings (per protocol spec)
    pub fn configure_encoder(
        &mut self,
        encoder_id: u8,
        channel_a_pin: u8,
        channel_b_pin: u8,
        options: EncoderOptions,
    ) -> Result<()> {
        if encoder_id as usize >= self.encoders.len() {
            return Err(PoKeysError::Parameter(format!(
                "Invalid encoder ID: {}",
                encoder_id
            )));
        }

        // Convert 1-based pin numbers to 0-based for protocol
        // The calling code uses 1-based pin numbers, but the protocol expects 0-based
        let protocol_pin_a = if channel_a_pin > 0 {
            channel_a_pin - 1
        } else {
            0
        };
        let protocol_pin_b = if channel_b_pin > 0 {
            channel_b_pin - 1
        } else {
            0
        };

        let encoder = &mut self.encoders[encoder_id as usize];
        encoder.channel_a_pin = protocol_pin_a; // Store 0-based internally
        encoder.channel_b_pin = protocol_pin_b; // Store 0-based internally
        encoder.set_options(options);

        log::info!(
            "Configuring encoder {} with pins A={}, B={} (1-based: A={}, B={}), options={:08b} using protocol 0x11",
            encoder_id,
            protocol_pin_a,
            protocol_pin_b,
            channel_a_pin,
            channel_b_pin,
            options.to_byte()
        );

        // Use protocol command 0x11 for individual encoder configuration
        // Per spec: byte 2: 0x11, byte 3: encoder ID (0-25), byte 4: option, byte 5: channel A, byte 6: channel B
        let response = self.send_request(
            0x11,              // Command: Encoder settings (per protocol spec)
            encoder_id,        // Encoder ID (0-25)
            options.to_byte(), // Options byte
            protocol_pin_a,    // Channel A input pin (0-based)
            protocol_pin_b,    // Channel B input pin (0-based)
        )?;

        log::info!("Encoder configuration response: {:?}", &response[0..8]);

        // Check response status per spec: byte 3 (index 2) = 0 = OK, 1 = encoder ID out of range or configuration locked
        if response.len() > 2 {
            match response[2] {
                // Status is at index 2 (spec byte 3)
                0 => {
                    log::info!("Encoder {} configuration successful", encoder_id);
                }
                1 => {
                    return Err(PoKeysError::Protocol(format!(
                        "Encoder {} configuration failed: encoder ID out of range or configuration locked",
                        encoder_id
                    )));
                }
                other => {
                    return Err(PoKeysError::Protocol(format!(
                        "Encoder {} configuration failed with status: {} (0x{:02X})",
                        encoder_id, other, other
                    )));
                }
            }
        }

        Ok(())
    }

    /// Read encoder settings using protocol 0x16
    pub fn read_encoder_settings(&mut self, encoder_id: u8) -> Result<EncoderData> {
        if encoder_id >= MAX_ENCODERS as u8 {
            return Err(PoKeysError::Parameter(format!(
                "Encoder ID {} exceeds maximum {}",
                encoder_id, MAX_ENCODERS
            )));
        }

        log::info!(
            "Reading encoder {} settings using protocol 0x16",
            encoder_id
        );

        // Use protocol command 0x16 for reading individual encoder settings
        // Per spec: byte 2: 0x16, byte 3: encoder (0-25), byte 4-6: 0
        let response = self.send_request(
            0x16,       // Command: Read encoder settings
            encoder_id, // Encoder ID (0-25)
            0,          // Reserved
            0,          // Reserved
            0,          // Reserved
        )?;

        log::info!("Read encoder settings response: {:?}", &response[0..8]);

        // Parse response per spec, accounting for header byte:
        // Index 0: header (0xAA), Index 1: command (0x16), Index 2: encoder, Index 3: options, Index 4: channel A, Index 5: channel B
        if response.len() >= 6 {
            let returned_encoder_id = response[2]; // Encoder ID at index 2
            let options_byte = response[3]; // Options at index 3
            let channel_a_pin = response[4]; // Channel A pin at index 4
            let channel_b_pin = response[5]; // Channel B pin at index 5

            if returned_encoder_id != encoder_id {
                log::warn!(
                    "Response encoder ID {} doesn't match requested {}",
                    returned_encoder_id,
                    encoder_id
                );
            }

            // Convert 0-based protocol pins to 1-based for display/API consistency
            let display_pin_a = channel_a_pin + 1;
            let display_pin_b = channel_b_pin + 1;

            let settings = EncoderData {
                channel_a_pin: display_pin_a, // Return 1-based pin numbers
                channel_b_pin: display_pin_b, // Return 1-based pin numbers
                encoder_options: options_byte,
                ..Default::default()
            };

            log::info!(
                "Encoder {} settings: A={}, B={} (protocol: A={}, B={}), options={:08b}",
                encoder_id,
                display_pin_a,
                display_pin_b,
                channel_a_pin,
                channel_b_pin,
                options_byte
            );

            Ok(settings)
        } else {
            Err(PoKeysError::Protocol(
                "Invalid encoder settings response length".to_string(),
            ))
        }
    }

    /// Enable or disable encoder
    pub fn enable_encoder(&mut self, encoder_id: u8, enable: bool) -> Result<()> {
        if encoder_id as usize >= self.encoders.len() {
            return Err(PoKeysError::Parameter(format!(
                "Invalid encoder ID: {}",
                encoder_id
            )));
        }

        // Get current pin assignments
        let (channel_a_pin, channel_b_pin) = {
            let encoder = &self.encoders[encoder_id as usize];
            (encoder.channel_a_pin, encoder.channel_b_pin)
        };

        // Update options
        let mut options = {
            let encoder = &self.encoders[encoder_id as usize];
            encoder.get_options()
        };
        options.enabled = enable;

        self.configure_encoder(encoder_id, channel_a_pin, channel_b_pin, options)
    }

    /// Set encoder sampling mode (4x or 2x)
    pub fn set_encoder_sampling(
        &mut self,
        encoder_id: u8,
        sampling_4x: bool,
        sampling_2x: bool,
    ) -> Result<()> {
        if encoder_id as usize >= self.encoders.len() {
            return Err(PoKeysError::Parameter(format!(
                "Invalid encoder ID: {}",
                encoder_id
            )));
        }

        // Validate sampling mode - only one can be active
        if sampling_4x && sampling_2x {
            return Err(PoKeysError::Parameter(
                "Cannot enable both 4x and 2x sampling simultaneously".to_string(),
            ));
        }

        // Get current pin assignments
        let (channel_a_pin, channel_b_pin) = {
            let encoder = &self.encoders[encoder_id as usize];
            (encoder.channel_a_pin, encoder.channel_b_pin)
        };

        // Update options
        let mut options = {
            let encoder = &self.encoders[encoder_id as usize];
            encoder.get_options()
        };
        options.sampling_4x = sampling_4x;
        options.sampling_2x = sampling_2x;

        self.configure_encoder(encoder_id, channel_a_pin, channel_b_pin, options)
    }

    /// Configure encoder key mapping for direction A
    /// Protocol: 0x12 - Encoder key mapping for direction A
    pub fn configure_encoder_key_mapping_a(
        &mut self,
        encoder_id: u8,
        key_code: u8,
        key_modifier: u8,
    ) -> Result<()> {
        if encoder_id as usize >= self.encoders.len() {
            return Err(PoKeysError::Parameter(format!(
                "Invalid encoder ID: {}",
                encoder_id
            )));
        }

        let encoder = &mut self.encoders[encoder_id as usize];
        encoder.dir_a_key_code = key_code;
        encoder.dir_a_key_modifier = key_modifier;

        // Send key mapping configuration using protocol command 0x12
        let response = self.send_request(
            0x12,         // Command: Encoder key mapping for direction A
            encoder_id,   // Encoder ID (0-25)
            0,            // Reserved
            key_code,     // Key code or macro ID
            key_modifier, // Key modifier
        )?;

        // Check response status
        if response.len() > 3 && response[3] != 0 {
            return Err(PoKeysError::Protocol(format!(
                "Encoder key mapping A failed for encoder {}: status {}",
                encoder_id, response[3]
            )));
        }

        Ok(())
    }

    /// Configure encoder key mapping for direction B
    /// Protocol: 0x13 - Encoder key mapping for direction B
    pub fn configure_encoder_key_mapping_b(
        &mut self,
        encoder_id: u8,
        key_code: u8,
        key_modifier: u8,
    ) -> Result<()> {
        if encoder_id as usize >= self.encoders.len() {
            return Err(PoKeysError::Parameter(format!(
                "Invalid encoder ID: {}",
                encoder_id
            )));
        }

        let encoder = &mut self.encoders[encoder_id as usize];
        encoder.dir_b_key_code = key_code;
        encoder.dir_b_key_modifier = key_modifier;

        // Send key mapping configuration using protocol command 0x13
        let response = self.send_request(
            0x13,         // Command: Encoder key mapping for direction B
            encoder_id,   // Encoder ID (0-25)
            0,            // Reserved
            key_code,     // Key code or macro ID
            key_modifier, // Key modifier
        )?;

        // Check response status
        if response.len() > 3 && response[3] != 0 {
            return Err(PoKeysError::Protocol(format!(
                "Encoder key mapping B failed for encoder {}: status {}",
                encoder_id, response[3]
            )));
        }

        Ok(())
    }

    /// Read encoder key mapping for direction A
    /// Protocol: 0x17 - Read encoder key mapping for direction A
    pub fn read_encoder_key_mapping_a(&mut self, encoder_id: u8) -> Result<(u8, u8)> {
        if encoder_id as usize >= self.encoders.len() {
            return Err(PoKeysError::Parameter(format!(
                "Invalid encoder ID: {}",
                encoder_id
            )));
        }

        let response = self.send_request(
            0x17,       // Command: Read encoder key mapping for direction A
            encoder_id, // Encoder ID (0-25)
            0,          // Reserved
            0,          // Reserved
            0,          // Reserved
        )?;

        if response.len() < 8 {
            return Err(PoKeysError::Protocol("Invalid response length".to_string()));
        }

        // Parse response: byte 5 = key code, byte 6 = key modifier
        let key_code = response[5];
        let key_modifier = response[6];

        // Update local cache
        self.encoders[encoder_id as usize].dir_a_key_code = key_code;
        self.encoders[encoder_id as usize].dir_a_key_modifier = key_modifier;

        Ok((key_code, key_modifier))
    }

    /// Read encoder key mapping for direction B
    /// Protocol: 0x18 - Read encoder key mapping for direction B
    pub fn read_encoder_key_mapping_b(&mut self, encoder_id: u8) -> Result<(u8, u8)> {
        if encoder_id as usize >= self.encoders.len() {
            return Err(PoKeysError::Parameter(format!(
                "Invalid encoder ID: {}",
                encoder_id
            )));
        }

        let response = self.send_request(
            0x18,       // Command: Read encoder key mapping for direction B
            encoder_id, // Encoder ID (0-25)
            0,          // Reserved
            0,          // Reserved
            0,          // Reserved
        )?;

        if response.len() < 8 {
            return Err(PoKeysError::Protocol("Invalid response length".to_string()));
        }

        // Parse response: byte 5 = key code, byte 6 = key modifier
        let key_code = response[5];
        let key_modifier = response[6];

        // Update local cache
        self.encoders[encoder_id as usize].dir_b_key_code = key_code;
        self.encoders[encoder_id as usize].dir_b_key_modifier = key_modifier;

        Ok((key_code, key_modifier))
    }

    /// Read encoder RAW value
    /// Protocol: 0x19 - Read encoder RAW value
    pub fn read_encoder_raw_value(&mut self, encoder_id: u8) -> Result<i32> {
        if encoder_id as usize >= self.encoders.len() {
            return Err(PoKeysError::Parameter(format!(
                "Invalid encoder ID: {}",
                encoder_id
            )));
        }

        let response = self.send_request(
            0x19,       // Command: Read encoder RAW value
            encoder_id, // Encoder ID (0-25)
            0,          // Reserved
            0,          // Reserved
            0,          // Reserved
        )?;

        if response.len() < 8 {
            return Err(PoKeysError::Protocol("Invalid response length".to_string()));
        }

        // Parse response: byte 4 = RAW value (8-bit for individual read)
        // Note: For full 32-bit values, use bulk read operations
        let raw_value = response[4] as i8 as i32; // Sign-extend 8-bit to 32-bit

        // Update local cache
        self.encoders[encoder_id as usize].encoder_value = raw_value;

        Ok(raw_value)
    }

    /// Reset encoder RAW value to zero
    /// Protocol: 0x1A - Reset encoder RAW value
    pub fn reset_encoder_raw_value(&mut self, encoder_id: u8) -> Result<()> {
        if encoder_id as usize >= self.encoders.len() {
            return Err(PoKeysError::Parameter(format!(
                "Invalid encoder ID: {}",
                encoder_id
            )));
        }

        let response = self.send_request(
            0x1A,       // Command: Reset encoder RAW value
            encoder_id, // Encoder ID (0-25)
            0,          // Reserved
            0,          // Reserved
            0,          // Reserved
        )?;

        // Check if command was successful (no specific error checking in protocol)
        if response.len() < 8 {
            return Err(PoKeysError::Protocol("Invalid response length".to_string()));
        }

        // Update local cache
        self.encoders[encoder_id as usize].encoder_value = 0;

        Ok(())
    }

    /// Get encoder value (convenience method)
    pub fn get_encoder_value(&mut self, encoder_id: u8) -> Result<i32> {
        self.read_encoder_raw_value(encoder_id)
    }

    /// Reset encoder value (convenience method)
    pub fn reset_encoder(&mut self, encoder_id: u8) -> Result<()> {
        self.reset_encoder_raw_value(encoder_id)
    }

    /// Get encoder long RAW values (bulk operation)
    /// Protocol: 0xCD - Get encoder long RAW values
    /// option: 0 = encoders 1-13, 1 = encoders 14-26
    pub fn read_encoder_long_values(&mut self, group: u8) -> Result<Vec<i32>> {
        if group > 1 {
            return Err(PoKeysError::Parameter(
                "Group must be 0 (encoders 1-13) or 1 (encoders 14-26)".to_string(),
            ));
        }

        let response = self.send_request(
            0xCD,  // Command: Get encoder long RAW values
            group, // Option: 0 or 1
            0,     // Reserved
            0,     // Reserved
            0,     // Reserved
        )?;

        if response.len() < 64 {
            return Err(PoKeysError::Protocol(
                "Invalid response length for bulk encoder read".to_string(),
            ));
        }

        let mut values = Vec::new();

        // Parse 32-bit values starting from byte 8 (protocol spec says byte 9, but that's 1-based)
        // Group 0: encoders 1-13, Group 1: encoders 14-26
        for i in 0..13 {
            let byte_offset = 8 + (i * 4); // Start at byte 8 in 0-based array, 4 bytes per encoder
            if byte_offset + 3 < response.len() {
                let value = i32::from_le_bytes([
                    response[byte_offset],
                    response[byte_offset + 1],
                    response[byte_offset + 2],
                    response[byte_offset + 3],
                ]);
                values.push(value);

                // Update local cache - map to 0-based encoder IDs
                let encoder_index = if group == 0 { i } else { 13 + i };
                if encoder_index < self.encoders.len() {
                    self.encoders[encoder_index].encoder_value = value;
                }
            }
        }

        // Handle ultra-fast encoder for group 1 (bytes 56-59 in 0-based array)
        if group == 1 && response.len() >= 60 {
            let ultra_fast_value = i32::from_le_bytes([
                response[56], // Protocol spec byte 57 = array index 56
                response[57], // Protocol spec byte 58 = array index 57
                response[58], // Protocol spec byte 59 = array index 58
                response[59], // Protocol spec byte 60 = array index 59
            ]);
            // Ultra-fast encoder is at index 25 (encoder 26 in 1-based numbering)
            if self.encoders.len() > 25 {
                self.encoders[25].encoder_value = ultra_fast_value;
            }
        }

        log::info!("Bulk read group {} returned {} values", group, values.len());
        Ok(values)
    }

    /// Set encoder long RAW values (bulk operation)
    /// Protocol: 0xCD - Set encoder long RAW values
    /// option: 10 = encoders 1-13, 11 = encoders 14-26
    pub fn set_encoder_long_values(&mut self, group: u8, values: &[i32]) -> Result<()> {
        if group > 1 {
            return Err(PoKeysError::Parameter(
                "Group must be 0 (encoders 1-13) or 1 (encoders 14-26)".to_string(),
            ));
        }

        let expected_count = if group == 0 { 13 } else { 12 }; // Group 1 has 12 regular + ultra-fast
        if values.len() < expected_count {
            return Err(PoKeysError::Parameter(format!(
                "Need {} values for group {}",
                expected_count, group
            )));
        }

        // Prepare request with values
        let mut request = vec![0u8; 64];
        request[2] = 0xCD; // Command
        request[3] = group + 10; // Option: 10 or 11 for set operation
        request[7] = self.get_next_request_id(); // Request ID

        // Pack 32-bit values starting from byte 9
        for (i, &value) in values.iter().enumerate() {
            let byte_offset = 9 + (i * 4);
            if byte_offset + 3 < request.len() {
                let bytes = value.to_le_bytes();
                request[byte_offset] = bytes[0];
                request[byte_offset + 1] = bytes[1];
                request[byte_offset + 2] = bytes[2];
                request[byte_offset + 3] = bytes[3];
            }
        }

        let _response = self.send_raw_request(&request)?;

        // Update local cache
        let start_encoder = if group == 0 { 1 } else { 14 };
        for (i, &value) in values.iter().enumerate() {
            let encoder_index = start_encoder + i;
            if encoder_index < self.encoders.len() {
                self.encoders[encoder_index].encoder_value = value;
            }
        }

        Ok(())
    }

    /// Read all encoder values using bulk operations (more efficient)
    pub fn read_all_encoder_values(&mut self) -> Result<Vec<i32>> {
        let mut all_values = Vec::new();

        // Read encoders 1-13
        let group1_values = self.read_encoder_long_values(0)?;
        all_values.extend(group1_values);

        // Read encoders 14-25 + ultra-fast
        let group2_values = self.read_encoder_long_values(1)?;
        all_values.extend(group2_values);

        Ok(all_values)
    }

    /// Configure encoder options (bulk operation)
    /// Protocol: 0xC4 - Encoder option
    pub fn configure_encoder_options_bulk(&mut self, options: &[u8]) -> Result<Vec<u8>> {
        if options.len() != 25 {
            return Err(PoKeysError::Parameter(
                "Need exactly 25 encoder options".to_string(),
            ));
        }

        let mut request = vec![0u8; 64];
        request[2] = 0xC4; // Command
        request[3] = 1; // Option: 1 = set
        request[7] = self.get_next_request_id(); // Request ID

        // Copy encoder options to bytes 9-33
        for (i, &option) in options.iter().enumerate() {
            request[9 + i] = option;
        }

        let response = self.send_raw_request(&request)?;

        // Parse returned options from bytes 9-33
        let mut returned_options = Vec::new();
        if response.len() >= 34 {
            for i in 0..25 {
                returned_options.push(response[9 + i]);
                // Update local cache
                if i < self.encoders.len() {
                    self.encoders[i].encoder_options = response[9 + i];
                }
            }
        }

        Ok(returned_options)
    }

    /// Read encoder options (bulk operation)
    /// Protocol: 0xC4 - Encoder option
    pub fn read_encoder_options_bulk(&mut self) -> Result<Vec<u8>> {
        let response = self.send_request(
            0xC4, // Command: Encoder option
            0,    // Option: 0 = get
            0,    // Reserved
            0,    // Reserved
            0,    // Reserved
        )?;

        let mut options = Vec::new();
        if response.len() >= 34 {
            for i in 0..25 {
                options.push(response[9 + i]);
                // Update local cache
                if i < self.encoders.len() {
                    self.encoders[i].encoder_options = response[9 + i];
                }
            }
        }

        Ok(options)
    }

    /// Configure the fast encoders via protocol command `0xCE`.
    ///
    /// `0xCE` uses two bytes: the **configuration selector** (which pin
    /// configuration / enable state to use) and the **options byte**
    /// (per-encoder direction invert + 4x-sampling control). They are passed
    /// as typed values so callers don't have to know the bit layout.
    ///
    /// Per PoKeysLib C reference (`PoKeysLibEncoders.c:154`):
    /// `req[2] = FastEncodersConfiguration`, `req[3] = FastEncodersOptions`.
    pub fn configure_fast_encoders(
        &mut self,
        config: FastEncoderConfiguration,
        options: FastEncoderOptions,
    ) -> Result<()> {
        let config_byte = config.to_byte();
        let options_byte = options.to_byte();

        self.fast_encoders_configuration = config_byte;
        self.fast_encoders_options = options_byte;

        let response = self.send_request(
            0xCE,         // Command: Enable/disable fast encoders
            config_byte,  // param1: FastEncodersConfiguration
            options_byte, // param2: FastEncodersOptions
            0,            // param3: reserved
            0,            // param4: reserved
        )?;

        // Response byte 3 (0-based index 2) is status.
        if response.len() > 2 {
            let status = response[2];
            if status != 0 {
                return Err(PoKeysError::Protocol(format!(
                    "Fast encoder configuration failed: status {}",
                    status
                )));
            }
        }

        Ok(())
    }

    /// Read fast encoder values
    pub fn read_fast_encoder_values(&mut self) -> Result<[i32; 3]> {
        // Fast encoders use the bulk read operation for encoders 0, 1, 2
        let values = self.read_encoder_long_values(0)?;

        let mut fast_values = [0i32; 3];
        let copy_len = 3.min(values.len());
        fast_values[..copy_len].copy_from_slice(&values[..copy_len]);

        Ok(fast_values)
    }

    /// Configure the ultra-fast encoder via protocol command `0x1C`
    /// (PoKeys56E and later).
    ///
    /// The ultra-fast encoder uses fixed pins: Pin 8 (Phase A), Pin 12 (Phase B),
    /// Pin 13 (Index).
    ///
    /// Bit layout of the options byte matches PoKeysLib C reference
    /// (`ePK_UltraFastEncoderOptions`): bit 0 = invert direction, bit 1 = signal
    /// mode, bit 2 = enable 4x sampling. See [`UltraFastEncoderOptions`].
    pub fn configure_ultra_fast_encoder(
        &mut self,
        enable: bool,
        options: UltraFastEncoderOptions,
        reset_on_index: bool,
        filter_delay: u32,
    ) -> Result<()> {
        let options_byte = options.to_byte();

        self.ultra_fast_encoder_configuration = if enable { 1 } else { 0 };
        self.ultra_fast_encoder_options = options_byte;
        self.ultra_fast_encoder_filter = filter_delay;

        // Packet layout per spec / PoKeysLib:
        //   byte 2 (param1) = enable flag (1 = enable, 0 = disable, 0xFF = read)
        //   byte 3 (param2) = options byte
        //   byte 4 (param3) = reset-on-index flag
        //   byte 5 (param4) = reserved (0)
        //   bytes 8..12     = filter delay (u32 LE) — placed via `with_data`
        let filter_bytes = filter_delay.to_le_bytes();
        let response = self.send_request_with_data(
            0x1C,
            if enable { 1 } else { 0 },
            options_byte,
            if reset_on_index { 1 } else { 0 },
            0,
            &filter_bytes,
        )?;

        // Response byte 3 (0-based index 2) is status.
        if response.len() > 2 {
            let status = response[2];
            if status != 0 {
                return Err(PoKeysError::Protocol(format!(
                    "Ultra-fast encoder configuration failed: status {}",
                    status
                )));
            }
        }

        Ok(())
    }

    /// Read the ultra-fast encoder's current configuration.
    ///
    /// Protocol: `0x1C` with `param1 = 0xFF` to request a read. Returns the
    /// enable flag, decoded [`UltraFastEncoderOptions`], and the filter delay
    /// (u32 LE at response bytes 8..12).
    pub fn read_ultra_fast_encoder_config(
        &mut self,
    ) -> Result<(bool, UltraFastEncoderOptions, u32)> {
        let response = self.send_request(0x1C, 0xFF, 0, 0, 0)?;

        if response.len() < 12 {
            return Err(PoKeysError::Protocol("Invalid response length".to_string()));
        }

        // Spec: byte 3 (index 2) = enable flag echo, byte 4 (index 3) = options.
        let enabled = response[2] != 0;
        let options = UltraFastEncoderOptions::from_byte(response[3]);
        let filter_delay =
            u32::from_le_bytes([response[8], response[9], response[10], response[11]]);

        Ok((enabled, options, filter_delay))
    }

    /// Read ultra-fast encoder value
    pub fn read_ultra_fast_encoder_value(&mut self) -> Result<i32> {
        // Ultra-fast encoder is included in bulk read group 1
        let values = self.read_encoder_long_values(1)?;

        // Ultra-fast encoder is the last value in group 1
        if let Some(&value) = values.last() {
            Ok(value)
        } else {
            Err(PoKeysError::Protocol(
                "No ultra-fast encoder value in response".to_string(),
            ))
        }
    }

    /// Set ultra-fast encoder value
    pub fn set_ultra_fast_encoder_value(&mut self, value: i32) -> Result<()> {
        // Use bulk set operation for group 1 with only the ultra-fast encoder value
        // We need to read current values first, then set only the ultra-fast one
        let mut values = self.read_encoder_long_values(1)?;

        // Set the ultra-fast encoder value (last in the array)
        if let Some(last) = values.last_mut() {
            *last = value;
        } else {
            return Err(PoKeysError::Protocol(
                "Cannot set ultra-fast encoder value".to_string(),
            ));
        }

        self.set_encoder_long_values(1, &values)
    }
    /// Configure encoder with keyboard mapping (convenience method)
    #[allow(clippy::too_many_arguments)]
    pub fn configure_encoder_with_keys(
        &mut self,
        encoder_id: u8,
        channel_a_pin: u8,
        channel_b_pin: u8,
        sampling_4x: bool,
        sampling_2x: bool,
        dir_a_key_code: u8,
        dir_a_key_modifier: u8,
        dir_b_key_code: u8,
        dir_b_key_modifier: u8,
    ) -> Result<()> {
        // Configure basic encoder settings
        let mut options = EncoderOptions::new();
        options.enabled = true;
        options.sampling_4x = sampling_4x;
        options.sampling_2x = sampling_2x;
        options.direct_key_mapping_a = true;
        options.direct_key_mapping_b = true;

        self.configure_encoder(encoder_id, channel_a_pin, channel_b_pin, options)?;

        // Configure key mappings
        self.configure_encoder_key_mapping_a(encoder_id, dir_a_key_code, dir_a_key_modifier)?;
        self.configure_encoder_key_mapping_b(encoder_id, dir_b_key_code, dir_b_key_modifier)?;

        Ok(())
    }

    /// Get encoder sampling mode as string (for debugging/display)
    pub fn get_encoder_sampling_mode(&self, encoder_id: u8) -> Result<String> {
        if encoder_id as usize >= self.encoders.len() {
            return Err(PoKeysError::Parameter(format!(
                "Invalid encoder ID: {}",
                encoder_id
            )));
        }

        let encoder = &self.encoders[encoder_id as usize];
        Ok(encoder.sampling_mode_str().to_string())
    }

    /// Check if encoder is configured for 4x sampling
    pub fn is_encoder_4x_sampling(&self, encoder_id: u8) -> Result<bool> {
        if encoder_id as usize >= self.encoders.len() {
            return Err(PoKeysError::Parameter(format!(
                "Invalid encoder ID: {}",
                encoder_id
            )));
        }

        Ok(self.encoders[encoder_id as usize].is_4x_sampling())
    }

    /// Check if encoder is configured for 2x sampling
    pub fn is_encoder_2x_sampling(&self, encoder_id: u8) -> Result<bool> {
        if encoder_id as usize >= self.encoders.len() {
            return Err(PoKeysError::Parameter(format!(
                "Invalid encoder ID: {}",
                encoder_id
            )));
        }

        Ok(self.encoders[encoder_id as usize].is_2x_sampling())
    }

    /// Get all enabled encoders
    pub fn get_enabled_encoders(&self) -> Vec<u8> {
        self.encoders
            .iter()
            .enumerate()
            .filter_map(|(i, encoder)| {
                if encoder.is_enabled() {
                    Some(i as u8)
                } else {
                    None
                }
            })
            .collect()
    }

    /// Helper method to get next request ID (implement in device)
    fn get_next_request_id(&mut self) -> u8 {
        // This should be implemented in the device structure
        // For now, return a simple incrementing counter
        static mut REQUEST_ID: u8 = 0;
        unsafe {
            REQUEST_ID = REQUEST_ID.wrapping_add(1);
            REQUEST_ID
        }
    }

    /// Helper method to send raw request (implement in device)
    fn send_raw_request(&mut self, request: &[u8]) -> Result<Vec<u8>> {
        // This should use the actual communication interface
        // For now, delegate to the existing send_request method and convert array to Vec
        if request.len() >= 8 {
            let response_array =
                self.send_request(request[2], request[3], request[4], request[5], request[6])?;
            Ok(response_array.to_vec())
        } else {
            Err(PoKeysError::Protocol("Invalid request format".to_string()))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_encoder_options_4x_sampling() {
        let options = EncoderOptions::with_4x_sampling();
        assert!(options.enabled);
        assert!(options.sampling_4x);
        assert!(!options.sampling_2x);

        let byte = options.to_byte();
        assert_eq!(byte & 0b00000011, 0b00000011); // enabled + 4x sampling

        let options_from_byte = EncoderOptions::from_byte(byte);
        assert!(options_from_byte.enabled);
        assert!(options_from_byte.sampling_4x);
        assert!(!options_from_byte.sampling_2x);
    }

    #[test]
    fn test_encoder_options_2x_sampling() {
        let options = EncoderOptions::with_2x_sampling();
        assert!(options.enabled);
        assert!(!options.sampling_4x);
        assert!(options.sampling_2x);

        let byte = options.to_byte();
        assert_eq!(byte & 0b00000111, 0b00000101); // enabled + 2x sampling

        let options_from_byte = EncoderOptions::from_byte(byte);
        assert!(options_from_byte.enabled);
        assert!(!options_from_byte.sampling_4x);
        assert!(options_from_byte.sampling_2x);
    }

    #[test]
    fn test_encoder_options_key_mapping() {
        let mut options = EncoderOptions::new();
        options.enabled = true;
        options.direct_key_mapping_a = true;
        options.macro_mapping_b = true;

        let byte = options.to_byte();
        assert_eq!(byte & 0b11110001, 0b10010001); // enabled + key_a + macro_b

        let options_from_byte = EncoderOptions::from_byte(byte);
        assert!(options_from_byte.enabled);
        assert!(options_from_byte.direct_key_mapping_a);
        assert!(options_from_byte.macro_mapping_b);
        assert!(!options_from_byte.direct_key_mapping_b);
        assert!(!options_from_byte.macro_mapping_a);
    }

    #[test]
    fn test_encoder_data_sampling_modes() {
        let mut encoder = EncoderData::new();

        // Test 4x sampling
        let options_4x = EncoderOptions::with_4x_sampling();
        encoder.set_options(options_4x);
        assert!(encoder.is_4x_sampling());
        assert!(!encoder.is_2x_sampling());
        assert_eq!(encoder.sampling_mode_str(), "4x (both edges)");

        // Test 2x sampling
        let options_2x = EncoderOptions::with_2x_sampling();
        encoder.set_options(options_2x);
        assert!(!encoder.is_4x_sampling());
        assert!(encoder.is_2x_sampling());
        assert_eq!(encoder.sampling_mode_str(), "2x (A edges only)");

        // Test disabled
        let options_disabled = EncoderOptions::new();
        encoder.set_options(options_disabled);
        assert!(!encoder.is_4x_sampling());
        assert!(!encoder.is_2x_sampling());
        assert_eq!(encoder.sampling_mode_str(), "1x (disabled)");
    }

    #[test]
    fn test_encoder_constants() {
        assert_eq!(MAX_ENCODERS, 25);
        assert_eq!(MAX_FAST_ENCODERS, 3);
        assert_eq!(ULTRA_FAST_ENCODER_INDEX, 25);
    }

    // ---- Fast encoder (0xCE) bit-layout tests ----------------------------
    //
    // These bit positions are authoritative per the PoLabs PoKeysLib C
    // reference (`ePK_FastEncoderOptions` in LinuxCnc_PokeysLibComp/
    // pokeys_uspace/PoKeysComp.h, also matching PoLabsEE/PoKeysLib usage).

    #[test]
    fn test_fast_encoder_configuration_to_byte() {
        assert_eq!(FastEncoderConfiguration::Disabled.to_byte(), 0x00);
        assert_eq!(FastEncoderConfiguration::Config1.to_byte(), 0x01);
        assert_eq!(FastEncoderConfiguration::Config2.to_byte(), 0x10);
    }

    #[test]
    fn test_fast_encoder_configuration_round_trip() {
        for cfg in [
            FastEncoderConfiguration::Disabled,
            FastEncoderConfiguration::Config1,
            FastEncoderConfiguration::Config2,
        ] {
            assert_eq!(FastEncoderConfiguration::from_byte(cfg.to_byte()), cfg);
        }
    }

    #[test]
    fn test_fast_encoder_options_bit_masks() {
        // Each flag alone must land on the exact bit the firmware expects.
        assert_eq!(
            FastEncoderOptions {
                disable_4x_sampling: true,
                ..Default::default()
            }
            .to_byte(),
            0x10
        );
        assert_eq!(
            FastEncoderOptions {
                invert_direction_1: true,
                ..Default::default()
            }
            .to_byte(),
            0x20
        );
        assert_eq!(
            FastEncoderOptions {
                invert_direction_2: true,
                ..Default::default()
            }
            .to_byte(),
            0x40
        );
        assert_eq!(
            FastEncoderOptions {
                invert_direction_3: true,
                ..Default::default()
            }
            .to_byte(),
            0x80
        );
    }

    #[test]
    fn test_fast_encoder_options_combined() {
        // All four flags set → 0x10 | 0x20 | 0x40 | 0x80 = 0xF0.
        let all = FastEncoderOptions {
            disable_4x_sampling: true,
            invert_direction_1: true,
            invert_direction_2: true,
            invert_direction_3: true,
        };
        assert_eq!(all.to_byte(), 0xF0);
    }

    #[test]
    fn test_fast_encoder_options_round_trip() {
        let o = FastEncoderOptions {
            disable_4x_sampling: false,
            invert_direction_1: true,
            invert_direction_2: false,
            invert_direction_3: true,
        };
        assert_eq!(FastEncoderOptions::from_byte(o.to_byte()), o);
    }

    #[test]
    fn test_fast_encoder_options_ignores_reserved_low_nibble() {
        // Low nibble must not leak into any field.
        let decoded = FastEncoderOptions::from_byte(0x0F);
        assert_eq!(decoded, FastEncoderOptions::default());
    }

    // ---- Ultra-fast encoder (0x1C) bit-layout tests ---------------------
    //
    // Per `ePK_UltraFastEncoderOptions`: bit 0 = invert direction,
    // bit 1 = signal mode, bit 2 = enable 4x sampling.

    #[test]
    fn test_ultra_fast_encoder_options_bit_masks() {
        assert_eq!(
            UltraFastEncoderOptions {
                invert_direction: true,
                ..Default::default()
            }
            .to_byte(),
            0x01
        );
        assert_eq!(
            UltraFastEncoderOptions {
                signal_mode_direction_clock: true,
                ..Default::default()
            }
            .to_byte(),
            0x02
        );
        assert_eq!(
            UltraFastEncoderOptions {
                enable_4x_sampling: true,
                ..Default::default()
            }
            .to_byte(),
            0x04
        );
    }

    #[test]
    fn test_ultra_fast_encoder_options_combined() {
        // invert + signal mode + 4x sampling → 0x07.
        let all = UltraFastEncoderOptions {
            invert_direction: true,
            signal_mode_direction_clock: true,
            enable_4x_sampling: true,
        };
        assert_eq!(all.to_byte(), 0x07);
    }

    #[test]
    fn test_ultra_fast_encoder_options_round_trip() {
        let o = UltraFastEncoderOptions {
            invert_direction: true,
            signal_mode_direction_clock: false,
            enable_4x_sampling: true,
        };
        assert_eq!(UltraFastEncoderOptions::from_byte(o.to_byte()), o);
    }

    #[test]
    fn test_ultra_fast_encoder_options_ignores_reserved_high_bits() {
        // Bits 3-7 are reserved; must not leak into any field.
        let decoded = UltraFastEncoderOptions::from_byte(0xF8);
        assert_eq!(decoded, UltraFastEncoderOptions::default());
    }
}