lk201 0.2.0

LK201 keyboard protocol implementation
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
//! # LK201/LK401 Keyboard Emulator (<https://en.wikipedia.org/wiki/LK201>).
//!
//! The protocol interface is documented in
//! <https://www.netbsd.org/docs/Hardware/Machines/DEC/lk201.html>, and some
//! bootup sequences are documented at <https://vt100.net/keyboard.html>.
//!
//! This crate also includes an optional, slower, but far more accurate hardware
//! emulator gated behind the `hardware` feature flag.
#![allow(unused)]

#[cfg(feature = "hardware")]
mod hardware;
#[cfg(feature = "hardware")]
pub use hardware::lk201::{LK201Hardware, ScanCell};
#[cfg(feature = "hardware")]
pub use hardware::lk250::{LK250Hardware, Lk250Mode};

mod software;
pub use software::{LK201, LK201Sender};

mod keys;

pub use keys::{ALL_KEYS, Key, SpecialKey};
use std::{collections::VecDeque, fmt, sync::mpsc};

use tracing::trace;

/// LED indicators on the LK201 keyboard
///
/// The LED parameter byte is a bitmask: 0x80 | (led_bits)
/// - Bit 7 (0x80): PARAM bit (always set)
/// - Bit 3 (0x08): Hold LED
/// - Bit 2 (0x04): Lock LED  
/// - Bit 1 (0x02): Compose LED
/// - Bit 0 (0x01): Wait LED
///
/// Any combination of LEDs (0x80-0x8F) is valid. Common combinations are named,
/// but Custom(byte) accepts any bitmask value.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Led(u8);

impl Led {
    pub fn new(byte: u8) -> Self {
        Led(byte)
    }

    pub fn is_wait(&self) -> bool {
        self.0 & 0x01 == 0x01
    }

    pub fn is_compose(&self) -> bool {
        self.0 & 0x02 == 0x02
    }

    pub fn is_lock(&self) -> bool {
        self.0 & 0x04 == 0x04
    }

    pub fn is_hold(&self) -> bool {
        self.0 & 0x08 == 0x08
    }

    pub fn is_all(&self) -> bool {
        self.0 & 0x0F == 0x0F
    }
}

impl fmt::Debug for Led {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Led({:02X}=", self.0)?;
        let mut first = true;
        for led in [
            ("Wait", self.is_wait()),
            ("Compose", self.is_compose()),
            ("Lock", self.is_lock()),
            ("Hold", self.is_hold()),
        ] {
            if led.1 {
                if first {
                    first = false;
                } else {
                    write!(f, "+")?;
                }
                write!(f, "{}", led.0)?;
            }
        }
        write!(f, ")")?;
        Ok(())
    }
}

/// Key mode for a keyboard division
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyMode {
    /// Key down generates code once, no repeat
    Down = 0x80,
    /// Key down generates code, then repeats with LK_REPEAT (0xB4)
    AutoDown = 0x82,
    /// Illegal value, unused.
    Illegal = 0x84,
    /// Key down/up both generate codes (for modifier keys)
    UpDown = 0x86,
}

/// Keyboard division (1-14, corresponding to groups of keys)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Division(pub u8);

impl Division {
    pub fn new(div: u8) -> Option<Self> {
        if div <= 14 && div > 0 {
            Some(Division(div))
        } else {
            None
        }
    }
}

/// Auto-repeat register (0-3)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AutoRepeatRegister(pub u8);

impl AutoRepeatRegister {
    pub fn new(reg: u8) -> Option<Self> {
        if reg <= 3 {
            Some(AutoRepeatRegister(reg))
        } else {
            None
        }
    }
}

/// Volume level (0 = max, 7 = min)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Volume(pub u8);

impl Volume {
    pub fn new(level: u8) -> Option<Self> {
        if level <= 7 {
            Some(Volume(level))
        } else {
            None
        }
    }

    pub fn as_param_byte(self) -> u8 {
        0x80 | (self.0 & 0x7)
    }
}

/// Commands sent from the computer to the LK201 keyboard
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum LK201Command {
    // LED Control
    /// Enable specified LED(s)
    LedEnable(Led),
    /// Disable specified LED(s)
    LedDisable(Led),

    // Key Click Control
    /// Enable key clicks with specified volume
    KeyClickEnable(Volume),
    /// Enable key clicks for CTRL key
    CtrlKeyClickEnable,
    /// Disable all key clicks
    KeyClickDisable,
    /// Disable CTRL key clicks
    CtrlKeyClickDisable,
    /// Cause keyboard to generate a single click sound
    SoundClick,

    // Bell Control
    /// Enable bell with specified volume
    BellEnable(Volume),
    /// Disable bell
    BellDisable,
    /// Ring the bell
    RingBell,

    // Key Mode Control
    /// Set mode for a keyboard division
    SetMode { mode: KeyMode, division: Division },
    /// Set mode and associate with auto-repeat register
    SetModeWithAutoRepeat {
        mode: KeyMode,
        division: Division,
        register: AutoRepeatRegister,
    },
    /// Convert all LK_AUTODOWN divisions to LK_DOWN
    RepeatToDown,
    /// Enable auto-repeat on LK_AUTODOWN keys
    EnableRepeat,
    /// Disable auto-repeat on all keys
    DisableRepeat,
    /// Enable LK401 mode
    EnableLK401,
    /// Disable LK401 mode
    DisableLK401,
    /// Temporarily disable auto-repeat for currently pressed key
    TempNoRepeat,

    // Auto-repeat Control
    /// Set auto-repeat parameters for a register
    SetAutoRepeat {
        register: AutoRepeatRegister,
        /// Timeout before repeat starts (in 5ms increments, 1-126)
        timeout: u8,
        /// Repeat rate in Hz (12-125, but not 125)
        rate: u8,
    },

    // Power-Up and Self Test
    /// Initiate keyboard power-up sequence
    PowerUp,
    /// Request keyboard ID (2 bytes returned)
    RequestId,
    /// Restore keyboard to default state
    SetDefaults,
    /// Enter factory test mode
    TestMode,
    /// Exit factory test mode (0x80, also used as LK_PARAM bit)
    TestExit,

    // Keyboard Control
    /// Suspend keyboard transmission, turn on LOCK LED
    Inhibit,
    /// Resume normal keyboard operation
    Resume,

    /// Unknown initial byte
    Unknown(u8),
    /// Unknown 2-byte command
    Unknown2(u8, u8),
    /// Unknown 3-byte command (e.g., 0xE9 xx xx - possibly division-specific repeat control)
    Unknown3(u8, u8, u8),
}

impl LK201Command {
    /// Returns the number of bytes this command occupies
    pub fn len(&self) -> usize {
        match self {
            LK201Command::LedEnable(_) => 2,
            LK201Command::LedDisable(_) => 2,
            LK201Command::KeyClickEnable(_) => 2,
            LK201Command::CtrlKeyClickEnable => 1,
            LK201Command::KeyClickDisable => 1,
            LK201Command::CtrlKeyClickDisable => 1,
            LK201Command::SoundClick => 1,
            LK201Command::BellEnable(_) => 2,
            LK201Command::BellDisable => 1,
            LK201Command::RingBell => 1,
            LK201Command::SetMode { .. } => 1,
            LK201Command::SetModeWithAutoRepeat { .. } => 2,
            LK201Command::RepeatToDown => 1,
            LK201Command::EnableRepeat => 1,
            LK201Command::DisableRepeat => 1,
            LK201Command::EnableLK401 => 1,
            LK201Command::DisableLK401 => 1,
            LK201Command::TempNoRepeat => 1,
            LK201Command::SetAutoRepeat { .. } => 3,
            LK201Command::PowerUp => 1,
            LK201Command::RequestId => 1,
            LK201Command::SetDefaults => 1,
            LK201Command::TestMode => 1,
            LK201Command::TestExit => 1,
            LK201Command::Inhibit => 1,
            LK201Command::Resume => 1,
            LK201Command::Unknown(_) => 1,
            LK201Command::Unknown2(_, _) => 2,
            LK201Command::Unknown3(_, _, _) => 3,
        }
    }

    /// Returns the response the keyboard should send for this command, if any.
    ///
    /// Based on the LK201 documentation and Linux kernel driver:
    /// - Power-up commands return multi-byte sequences
    /// - Mode-related commands return ModeChangeAck (0xBA)
    /// - Test/Inhibit commands return specific acks
    /// - Invalid commands return InputError (0xB6)
    /// - Most other commands (LED, bell, click) have no response
    pub fn response(&self) -> Option<LK201Response> {
        Some(match self {
            // Power-up and ID requests return multi-byte responses
            LK201Command::PowerUp => LK201Response::PowerUpSelfTest {
                keyboard_id_firmware: 0x01, // Standard LK201 firmware ID
                keyboard_id_hardware: 0x00, // Hardware ID from jumpers
                error: PowerUpError::NoError,
                keycode: 0,
            },
            LK201Command::RequestId => LK201Response::KeyboardId {
                firmware_id: 0x01, // Firmware version
                hardware_id: 0x01, // 1 = LK201, 2 = LK401, 3 = LK443, 4 = LK421
            },

            // Mode change commands return ModeChangeAck (0xBA)
            // "Upon successful receipt of the command, the LK201 responds with LK_MODECHG_ACK"
            LK201Command::SetMode { .. } => LK201Response::ModeChangeAck,
            LK201Command::SetModeWithAutoRepeat { .. } => LK201Response::ModeChangeAck,
            LK201Command::TempNoRepeat => LK201Response::ModeChangeAck,
            LK201Command::SetDefaults => LK201Response::ModeChangeAck,

            // Special control commands with specific acks
            LK201Command::TestMode => LK201Response::TestModeAck,
            LK201Command::Inhibit => LK201Response::KeyboardLockAck,

            // Invalid commands return InputError
            LK201Command::Unknown(_) => LK201Response::InputError,
            LK201Command::Unknown2(_, _) => LK201Response::InputError,
            LK201Command::Unknown3(_, _, _) => LK201Response::InputError,

            // All other commands (LED, bell, click, autorepeat rate, etc.) have no response
            _ => return None,
        })
    }
}

impl TryFrom<&VecDeque<u8>> for LK201Command {
    type Error = ();

    fn try_from(value: &VecDeque<u8>) -> Result<Self, Self::Error> {
        let Some(&byte0) = value.get(0) else {
            return Err(());
        };

        match byte0 {
            // LED Control
            0x13 => {
                let Some(&led_byte) = value.get(1) else {
                    return Err(());
                };
                let led = Led::new(led_byte);
                Ok(LK201Command::LedEnable(led))
            }
            0x11 => {
                let Some(&led_byte) = value.get(1) else {
                    return Err(());
                };
                let led = Led::new(led_byte);
                Ok(LK201Command::LedDisable(led))
            }

            // Key Click Control
            0x1B => {
                let Some(&vol_byte) = value.get(1) else {
                    return Err(());
                };
                let Some(volume) = Volume::new((vol_byte & 0x7) as u8) else {
                    return Ok(LK201Command::Unknown2(0x1B, vol_byte));
                };
                Ok(LK201Command::KeyClickEnable(volume))
            }
            0xBB => Ok(LK201Command::CtrlKeyClickEnable),
            0x99 => Ok(LK201Command::KeyClickDisable),
            0xB9 => Ok(LK201Command::CtrlKeyClickDisable),
            0x9F => Ok(LK201Command::SoundClick),
            0x80 => Ok(LK201Command::TestExit),

            // Bell Control
            0x23 => {
                let Some(&vol_byte) = value.get(1) else {
                    return Err(());
                };
                let Some(volume) = Volume::new((vol_byte & 0x7) as u8) else {
                    return Ok(LK201Command::Unknown2(0x23, vol_byte));
                };
                Ok(LK201Command::BellEnable(volume))
            }
            0xA1 => Ok(LK201Command::BellDisable),
            0xA7 => Ok(LK201Command::RingBell),

            // Autorepeat rate commands (0x78-0x7F range: bits 6-3 = 1111, bits 2-1 = register)
            0x78..=0x7F if (byte0 >> 3) & 0xF == 0xF => {
                let Some(&timeout) = value.get(1) else {
                    return Err(());
                };
                let Some(&rate) = value.get(2) else {
                    return Err(());
                };
                let Some(register) = AutoRepeatRegister::new((byte0 >> 1) & 0x3) else {
                    return Ok(LK201Command::Unknown2(0x78, byte0));
                };
                Ok(LK201Command::SetAutoRepeat {
                    register,
                    timeout: timeout & 0x7F,
                    rate: rate & 0x7F,
                })
            }

            // Key Mode Control
            // Check if this is a mode command by examining the structure
            // Note: 0x80 (TestExit) has the same bit pattern as SetMode{division:0, mode:Down}
            // It's only interpreted as TestExit when the keyboard is already in test mode
            b if (b & 0x01) == 0 => {
                // Bit 0 is 0, could be a mode command
                let division_bits = (b >> 3) & 0xF;
                let mode_bits = (b >> 1) & 0x3;
                let has_param = (b & 0x80) == 0;

                // Check if division is valid (0-14)
                if division_bits <= 14 {
                    let Some(division) = Division::new(division_bits) else {
                        return Ok(LK201Command::Unknown(b));
                    };
                    let mode = match mode_bits {
                        0b00 => KeyMode::Down,
                        0b01 => KeyMode::AutoDown,
                        0b11 => KeyMode::UpDown,
                        _ => return Ok(LK201Command::Unknown(b)),
                    };

                    // Check PARAM bit (bit 7)
                    if has_param {
                        // PARAM = 0, parameter follows with autorepeat register
                        let Some(&param_byte) = value.get(1) else {
                            return Err(());
                        };
                        let Some(register) = AutoRepeatRegister::new(param_byte & 0x3) else {
                            return Ok(LK201Command::Unknown2(b, param_byte));
                        };
                        return Ok(LK201Command::SetModeWithAutoRepeat {
                            mode,
                            division,
                            register,
                        });
                    } else {
                        // PARAM = 1, no parameter
                        return Ok(LK201Command::SetMode { mode, division });
                    }
                }

                // Not a valid mode command, fall through
                Ok(LK201Command::Unknown(byte0))
            }

            // Other Commands
            0xC1 => Ok(LK201Command::TempNoRepeat),
            0xD9 => Ok(LK201Command::RepeatToDown),
            0xE1 => Ok(LK201Command::DisableRepeat),
            0xE3 => Ok(LK201Command::EnableRepeat),
            0xE9 => Ok(LK201Command::EnableLK401),
            0xEB => Ok(LK201Command::DisableLK401),

            // Power-Up and Self Test
            0xFD => Ok(LK201Command::PowerUp),
            0xAB => Ok(LK201Command::RequestId),
            0xD3 => Ok(LK201Command::SetDefaults),
            0xCB => Ok(LK201Command::TestMode),

            // Keyboard Control
            0x8B => Ok(LK201Command::Resume),
            0x89 => Ok(LK201Command::Inhibit),

            // Unknown command
            _ => Ok(LK201Command::Unknown(byte0)),
        }
    }
}

impl Into<Vec<u8>> for LK201Command {
    fn into(self) -> Vec<u8> {
        match self {
            LK201Command::LedEnable(led) => vec![0x13, led.0],
            LK201Command::LedDisable(led) => vec![0x11, led.0],
            LK201Command::KeyClickEnable(vol) => vec![0x1B, vol.as_param_byte()],
            LK201Command::CtrlKeyClickEnable => vec![0xBB],
            LK201Command::KeyClickDisable => vec![0x99],
            LK201Command::CtrlKeyClickDisable => vec![0xB9],
            LK201Command::SoundClick => vec![0x9F],
            LK201Command::BellEnable(vol) => vec![0x23, vol.as_param_byte()],
            LK201Command::BellDisable => vec![0xA1],
            LK201Command::RingBell => vec![0xA7],
            LK201Command::SetMode { mode, division } => {
                let mode_bits = match mode {
                    KeyMode::Down => 0b00,
                    KeyMode::AutoDown => 0b01,
                    KeyMode::UpDown => 0b11,
                    KeyMode::Illegal => 0b10,
                };
                vec![(division.0 << 3) | (mode_bits << 1) | 0x80]
            }
            LK201Command::SetModeWithAutoRepeat {
                mode,
                division,
                register,
            } => {
                let mode_bits = match mode {
                    KeyMode::Down => 0b00,
                    KeyMode::AutoDown => 0b01,
                    KeyMode::UpDown => 0b11,
                    KeyMode::Illegal => 0b10,
                };
                vec![
                    (division.0 << 3) | (mode_bits << 1),
                    0x80 | (register.0 & 0x3),
                ]
            }
            LK201Command::RepeatToDown => vec![0xD9],
            LK201Command::EnableRepeat => vec![0xE3],
            LK201Command::DisableRepeat => vec![0xE1],
            LK201Command::EnableLK401 => vec![0xE9],
            LK201Command::DisableLK401 => vec![0xEB],
            LK201Command::TempNoRepeat => vec![0xC1],
            LK201Command::SetAutoRepeat {
                register,
                timeout,
                rate,
            } => {
                vec![
                    0b0_1111_000 | (register.0 << 1),
                    (timeout / 5) & 0x7F,
                    rate & 0x7F | 0x80,
                ]
            }
            LK201Command::PowerUp => vec![0xFD],
            LK201Command::RequestId => vec![0xAB],
            LK201Command::SetDefaults => vec![0xD3],
            LK201Command::TestMode => vec![0xCB],
            LK201Command::TestExit => vec![0x80],
            LK201Command::Inhibit => vec![0x89],
            LK201Command::Resume => vec![0x8B],
            LK201Command::Unknown(b) => vec![b],
            LK201Command::Unknown2(b1, b2) => vec![b1, b2],
            LK201Command::Unknown3(b1, b2, b3) => vec![b1, b2, b3],
        }
    }
}

/// Special keycodes that have specific meanings
pub mod keycodes {
    /// Caps Lock key
    pub const KEY_LOCK: u8 = 0xB0;
    /// Shift key
    pub const KEY_SHIFT: u8 = 0xAE;
    /// Control key
    pub const KEY_CTRL: u8 = 0xAF;
    /// Compose key
    pub const KEY_COMP: u8 = 0xB1;
}

/// Responses sent from the LK201 keyboard to the computer
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LK201Response {
    // Power-up and ID
    /// Power-up self test result (4 bytes: ID1, ID2, error, keycode)
    PowerUpSelfTest {
        keyboard_id_firmware: u8,
        keyboard_id_hardware: u8,
        error: PowerUpError,
        keycode: u8,
    },
    /// Keyboard ID response (2 bytes)
    KeyboardId { firmware_id: u8, hardware_id: u8 },

    // Acknowledgments
    /// Mode change acknowledged
    ModeChangeAck,
    /// Keyboard locked acknowledged
    KeyboardLockAck,
    /// Test mode acknowledged
    TestModeAck,

    // Errors
    /// Input error (invalid command received)
    InputError,
    /// Output error (keystrokes lost during inhibit)
    OutputError,

    // Key Events
    /// Key pressed (keycode 0x00-0xFF)
    KeyDown(u8),
    /// Key repeat indicator (sent repeatedly for held keys in AutoDown mode)
    Repeat,
    /// All keys released (sent when last key in UpDown mode is released)
    AllUp,
    /// Prefix indicating next byte is keycode for key already down
    PrefixKeyDown(u8),
}

impl LK201Response {
    /// Serialize this response to bytes for transmission
    pub fn to_bytes(&self) -> Vec<u8> {
        match self {
            LK201Response::PowerUpSelfTest {
                keyboard_id_firmware,
                keyboard_id_hardware,
                error,
                keycode,
            } => {
                vec![
                    *keyboard_id_firmware,
                    *keyboard_id_hardware,
                    (*error).into(),
                    *keycode,
                ]
            }
            LK201Response::KeyboardId {
                firmware_id,
                hardware_id,
            } => {
                vec![*firmware_id, *hardware_id]
            }
            LK201Response::ModeChangeAck => vec![0xBA],
            LK201Response::TestModeAck => vec![0xB8],
            LK201Response::KeyboardLockAck => vec![0xB7],
            LK201Response::InputError => vec![0xB6],
            LK201Response::OutputError => vec![0xB5],
            LK201Response::KeyDown(keycode) => vec![*keycode],
            LK201Response::Repeat => vec![0xB4],
            LK201Response::AllUp => vec![0xB3],
            LK201Response::PrefixKeyDown(keycode) => vec![0xB9, *keycode],
        }
    }
}

/// Keyboard type IDs (returned in byte 1 of KeyboardId response)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyboardType {
    /// LK201 keyboard
    LK201 = 1,
    /// LK401 keyboard (has ALT keys)
    LK401 = 2,
    /// LK443 keyboard
    LK443 = 3,
    /// LK421 keyboard
    LK421 = 4,
}

impl KeyboardType {
    pub fn from_id(id: u8) -> Option<Self> {
        match id {
            1 => Some(KeyboardType::LK201),
            2 => Some(KeyboardType::LK401),
            3 => Some(KeyboardType::LK443),
            4 => Some(KeyboardType::LK421),
            _ => None,
        }
    }
}

/// Power-up self test error codes
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PowerUpError {
    /// No error detected
    NoError,
    /// Key was down during power-up
    KeyDownError,
    /// Keyboard failure on power-up test
    PowerError,
    /// Unknown error code
    Unknown(u8),
}

impl From<u8> for PowerUpError {
    fn from(byte: u8) -> Self {
        match byte {
            0x00 => PowerUpError::NoError,
            0x3D => PowerUpError::KeyDownError,
            0x3E => PowerUpError::PowerError,
            other => PowerUpError::Unknown(other),
        }
    }
}

impl From<PowerUpError> for u8 {
    fn from(error: PowerUpError) -> u8 {
        match error {
            PowerUpError::NoError => 0x00,
            PowerUpError::KeyDownError => 0x3D,
            PowerUpError::PowerError => 0x3E,
            PowerUpError::Unknown(byte) => byte,
        }
    }
}

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

    #[track_caller]
    fn test_parse(input: &[u8], expected: LK201Command) {
        let queue = VecDeque::from_iter(input.iter().copied());
        let command = LK201Command::try_from(&queue).unwrap();
        assert_eq!(
            command, expected,
            "input: {:02X?}, expected: {:?}",
            input, expected
        );
        assert_eq!(
            input.len(),
            command.len(),
            "input: {:02X?}, expected: {:?}",
            input,
            expected
        );
    }

    #[test]
    fn test_mode_commands() {
        // 0A 80: division 1, autodown, register 0
        test_parse(
            &[0x0A, 0x80],
            LK201Command::SetModeWithAutoRepeat {
                division: Division(1),
                mode: KeyMode::AutoDown,
                register: AutoRepeatRegister(0),
            },
        );

        // 12 81: division 2, autodown, register 1
        test_parse(
            &[0x12, 0x81],
            LK201Command::SetModeWithAutoRepeat {
                division: Division(2),
                mode: KeyMode::AutoDown,
                register: AutoRepeatRegister(1),
            },
        );

        // 72 82: division 14, autodown, register 2
        test_parse(
            &[0x72, 0x82],
            LK201Command::SetModeWithAutoRepeat {
                division: Division(14),
                mode: KeyMode::AutoDown,
                register: AutoRepeatRegister(2),
            },
        );

        // A2: division 4, autodown, no register parameter
        test_parse(
            &[0xA2],
            LK201Command::SetMode {
                mode: KeyMode::AutoDown,
                division: Division(4),
            },
        );
    }

    #[test]
    fn test_autorepeat_commands() {
        // 78 64 9E: register 0, timeout 0x64, rate 0x9E
        test_parse(
            &[0x78, 0x64, 0x9E],
            LK201Command::SetAutoRepeat {
                register: AutoRepeatRegister(0),
                timeout: 0x64,
                rate: 0x1E,
            },
        );

        // 7A 64 9E: register 1, timeout 0x64, rate 0x9E
        test_parse(
            &[0x7A, 0x64, 0x9E],
            LK201Command::SetAutoRepeat {
                register: AutoRepeatRegister(1),
                timeout: 0x64,
                rate: 0x1E,
            },
        );

        // 7C 64 9E: register 2, timeout 0x64, rate 0x9E
        test_parse(
            &[0x7C, 0x64, 0x9E],
            LK201Command::SetAutoRepeat {
                register: AutoRepeatRegister(2),
                timeout: 0x64,
                rate: 0x1E,
            },
        );
    }

    #[test]
    fn test_led_commands() {
        // LED enable and disable with named combinations
        test_parse(&[0x13, 0x84], LK201Command::LedEnable(Led::new(0x84)));
        test_parse(&[0x11, 0x88], LK201Command::LedDisable(Led::new(0x88)));
        test_parse(&[0x13, 0x8F], LK201Command::LedEnable(Led::new(0x8F)));
        test_parse(&[0x13, 0x81], LK201Command::LedEnable(Led::new(0x81)));

        // LED bitmask combinations (any combination of bits 0-3 is valid)
        test_parse(&[0x13, 0x80], LK201Command::LedEnable(Led::new(0x80))); // No LEDs
        test_parse(&[0x13, 0x83], LK201Command::LedEnable(Led::new(0x83))); // Wait + Compose
        test_parse(&[0x13, 0x85], LK201Command::LedEnable(Led::new(0x85))); // Wait + Lock
        test_parse(&[0x13, 0x86], LK201Command::LedEnable(Led::new(0x86))); // Compose + Lock
        test_parse(&[0x13, 0x8C], LK201Command::LedEnable(Led::new(0x8C))); // Lock + Hold
        test_parse(&[0x11, 0x8D], LK201Command::LedDisable(Led::new(0x8D))); // Wait + Lock + Hold
    }

    #[test]
    fn test_bell_and_click_commands() {
        // Bell commands
        test_parse(&[0x23, 0x80], LK201Command::BellEnable(Volume(0)));
        test_parse(&[0xA1], LK201Command::BellDisable);
        test_parse(&[0xA7], LK201Command::RingBell);

        // Click commands
        test_parse(&[0x1B, 0x80], LK201Command::KeyClickEnable(Volume(0)));
        test_parse(&[0x99], LK201Command::KeyClickDisable);
        test_parse(&[0xBB], LK201Command::CtrlKeyClickEnable);
        test_parse(&[0xB9], LK201Command::CtrlKeyClickDisable);
    }

    #[test]
    fn test_control_commands() {
        test_parse(&[0xFD], LK201Command::PowerUp);
        test_parse(&[0xAB], LK201Command::RequestId);
        test_parse(&[0xE3], LK201Command::EnableRepeat);
        test_parse(&[0xE1], LK201Command::DisableRepeat);
        test_parse(&[0xD9], LK201Command::RepeatToDown);
        test_parse(&[0xC1], LK201Command::TempNoRepeat);
        test_parse(&[0xD3], LK201Command::SetDefaults);
        test_parse(&[0xCB], LK201Command::TestMode);
        test_parse(&[0x8B], LK201Command::Resume);
        test_parse(&[0x89], LK201Command::Inhibit);
        test_parse(&[0x80], LK201Command::TestExit);
    }

    #[test]
    fn test_unknown_commands() {
        // Test that invalid command bytes are parsed as Unknown
        test_parse(&[0x0D], LK201Command::Unknown(0x0D));
        test_parse(&[0xFF], LK201Command::Unknown(0xFF));
        test_parse(&[0x01], LK201Command::Unknown(0x01));
        test_parse(&[0x55], LK201Command::Unknown(0x55));

        // Verify Unknown commands return InputError response
        let cmd = LK201Command::Unknown(0x0D);
        let resp = cmd.response().unwrap();
        assert_eq!(resp, LK201Response::InputError);
        assert_eq!(resp.to_bytes(), vec![0xB6]);
    }

    #[test]
    fn test_command_responses() {
        // Commands that return multi-byte responses
        let cmd = LK201Command::PowerUp;
        let resp = cmd.response().unwrap();
        assert_eq!(resp.to_bytes(), vec![0x01, 0x00, 0x00, 0x00]);

        let cmd = LK201Command::RequestId;
        let resp = cmd.response().unwrap();
        assert_eq!(resp.to_bytes(), vec![0x01, 0x01]);

        // Mode commands return ModeChangeAck (0xBA)
        let cmd = LK201Command::SetMode {
            mode: KeyMode::AutoDown,
            division: Division(1),
        };
        let resp = cmd.response().unwrap();
        assert_eq!(resp.to_bytes(), vec![0xBA]);

        let cmd = LK201Command::SetModeWithAutoRepeat {
            mode: KeyMode::AutoDown,
            division: Division(1),
            register: AutoRepeatRegister(0),
        };
        let resp = cmd.response().unwrap();
        assert_eq!(resp.to_bytes(), vec![0xBA]);

        let resp = LK201Command::SetDefaults.response().unwrap();
        assert_eq!(resp.to_bytes(), vec![0xBA]);

        // Special acks
        let cmd = LK201Command::TestMode;
        let resp = cmd.response().unwrap();
        assert_eq!(resp.to_bytes(), vec![0xB8]);

        let cmd = LK201Command::Inhibit;
        let resp = cmd.response().unwrap();
        assert_eq!(resp.to_bytes(), vec![0xB7]);

        // Error response
        let cmd = LK201Command::Unknown(0xFF);
        let resp = cmd.response().unwrap();
        assert_eq!(resp.to_bytes(), vec![0xB6]);

        // Commands with no response
        assert!(LK201Command::LedEnable(Led::new(0x84)).response().is_none());
        assert!(LK201Command::BellEnable(Volume(4)).response().is_none());
        assert!(LK201Command::KeyClickDisable.response().is_none());
        assert!(LK201Command::Resume.response().is_none());
    }

    #[test]
    fn test_response_serialization() {
        // Test all response types serialize correctly
        let resp = LK201Response::ModeChangeAck;
        assert_eq!(resp.to_bytes(), vec![0xBA]);

        let resp = LK201Response::KeyboardLockAck;
        assert_eq!(resp.to_bytes(), vec![0xB7]);

        let resp = LK201Response::TestModeAck;
        assert_eq!(resp.to_bytes(), vec![0xB8]);

        let resp = LK201Response::InputError;
        assert_eq!(resp.to_bytes(), vec![0xB6]);

        let resp = LK201Response::OutputError;
        assert_eq!(resp.to_bytes(), vec![0xB5]);

        let resp = LK201Response::Repeat;
        assert_eq!(resp.to_bytes(), vec![0xB4]);

        let resp = LK201Response::AllUp;
        assert_eq!(resp.to_bytes(), vec![0xB3]);

        let resp = LK201Response::KeyDown(0x42);
        assert_eq!(resp.to_bytes(), vec![0x42]);

        let resp = LK201Response::PrefixKeyDown(0x42);
        assert_eq!(resp.to_bytes(), vec![0xB9, 0x42]);
    }

    #[test]
    fn test_full_sequence() {
        // Test parsing a complete initialization sequence
        // Division 1 (letters), autodown, register 0
        test_parse(
            &[0x0A, 0x80],
            LK201Command::SetModeWithAutoRepeat {
                division: Division(1),
                mode: KeyMode::AutoDown,
                register: AutoRepeatRegister(0),
            },
        );

        // Division 3 (Delete key), autodown, register 0
        test_parse(
            &[0x1A, 0x80],
            LK201Command::SetModeWithAutoRepeat {
                division: Division(3),
                mode: KeyMode::AutoDown,
                register: AutoRepeatRegister(0),
            },
        );

        // Division 7 (left/right arrows), autodown, register 0
        test_parse(
            &[0x3A, 0x80],
            LK201Command::SetModeWithAutoRepeat {
                division: Division(7),
                mode: KeyMode::AutoDown,
                register: AutoRepeatRegister(0),
            },
        );

        // Division 8 (up/down arrows), autodown, register 1
        test_parse(
            &[0x42, 0x81],
            LK201Command::SetModeWithAutoRepeat {
                division: Division(8),
                mode: KeyMode::AutoDown,
                register: AutoRepeatRegister(1),
            },
        );

        // Division 9 (E1-E6), autodown, register 2
        test_parse(
            &[0x4A, 0x82],
            LK201Command::SetModeWithAutoRepeat {
                division: Division(9),
                mode: KeyMode::AutoDown,
                register: AutoRepeatRegister(2),
            },
        );

        // Division 11 (F6-F10), autodown, register 2
        test_parse(
            &[0x5A, 0x82],
            LK201Command::SetModeWithAutoRepeat {
                division: Division(11),
                mode: KeyMode::AutoDown,
                register: AutoRepeatRegister(2),
            },
        );

        // Division 12 (F11-F14), autodown, register 2
        test_parse(
            &[0x62, 0x82],
            LK201Command::SetModeWithAutoRepeat {
                division: Division(12),
                mode: KeyMode::AutoDown,
                register: AutoRepeatRegister(2),
            },
        );

        // Division 13 (Help, Do), autodown, register 2
        test_parse(
            &[0x6A, 0x82],
            LK201Command::SetModeWithAutoRepeat {
                division: Division(13),
                mode: KeyMode::AutoDown,
                register: AutoRepeatRegister(2),
            },
        );
    }

    #[test]
    fn test_lk201() {
        test_parse(&[0xE9], LK201Command::EnableLK401);
        test_parse(&[0xEB], LK201Command::DisableLK401);
    }
}