fork/GramFirmware

git clone https://git.julia.blue/fork/GramFirmware

Jonathan HaylettNintendo Switch USB support (#20)38b67d3

codespace-scaling-space-guide-56rpxqvxpg2v57v
2.3 KiB86 linesraw
1#include "TUKeyboard.hpp"
2
3#include <Adafruit_TinyUSB.h>
4#include <TUCompositeHID.hpp>
5
6uint8_t TUKeyboard::_descriptor[] = { TUD_HID_REPORT_DESC_KEYBOARD(HID_REPORT_ID(_report_id)) };
7
8#define MODIFIER_MASK(mod_kc) (1 << (mod_kc & 0x0F))
9
10TUKeyboard::TUKeyboard() {}
11
12void TUKeyboard::registerDescriptor() {
13    TUCompositeHID::addDescriptor(_descriptor, sizeof(_descriptor));
14}
15
16void TUKeyboard::begin() {
17    TUCompositeHID::_usb_hid.begin();
18    releaseAll();
19}
20
21void TUKeyboard::press(uint8_t keycode) {
22    // If keycode >= E0 then it's a modifier key.
23    if (keycode >= 0xE0) {
24        // Create bitmask from the modifier keycode to set the corresponding bit in the modifier
25        // byte.
26        uint8_t bitmask = MODIFIER_MASK(keycode);
27        _report.modifier |= bitmask;
28        return;
29    }
30
31    // Check if the key is already pressed so that we don't send the same keycode multiple times in
32    // the same report.
33    for (int i = 0; i < 6; i++) {
34        if (_report.keycode[i] == keycode) {
35            return;
36        }
37    }
38
39    // Place this keycode in the report in place of the first empty keycode.
40    for (int i = 0; i < 6; i++) {
41        if (_report.keycode[i] == HID_KEY_NONE) {
42            _report.keycode[i] = keycode;
43            return;
44        }
45    }
46}
47
48void TUKeyboard::release(uint8_t keycode) {
49    // If keycode >= E0 then it's a modifier key.
50    if (keycode >= 0xE0) {
51        // Create bitmask from the modifier keycode to unset the corresponding bit in the modifier
52        // byte.
53        uint8_t bitmask = ~MODIFIER_MASK(keycode);
54        _report.modifier &= bitmask;
55        return;
56    }
57
58    // Loop through keycodes in report. If we find the specified key code, we clear it.
59    for (int i = 0; i < 6; i++) {
60        if (_report.keycode[i] == keycode) {
61            _report.keycode[i] = HID_KEY_NONE;
62        }
63    }
64}
65
66void TUKeyboard::setPressed(uint8_t keycode, bool pressed) {
67    if (pressed) {
68        press(keycode);
69    } else {
70        release(keycode);
71    }
72}
73
74void TUKeyboard::releaseAll() {
75    for (int i = 0; i < 6; i++) {
76        _report.keycode[i] = 0;
77    }
78    _report.modifier = 0;
79}
80
81void TUKeyboard::sendState() {
82    while (!TUCompositeHID::_usb_hid.ready()) {
83        tight_loop_contents();
84    }
85    TUCompositeHID::_usb_hid.sendReport(_report_id, &_report, sizeof(hid_keyboard_report_t));
86}