qmk_firmware

QMK firmware for my keyboards (Corne, Sweep Ferris) and trackball (Ploopy Adept)
Log | Files | Refs | Submodules | LICENSE

rawhid.md (6429B)


      1 # Raw HID {#raw-hid}
      2 
      3 The Raw HID feature allows for bidirectional communication between QMK and the host computer over an HID interface. This has many potential use cases, such as switching keymaps on the fly or sending useful metrics like CPU/RAM usage.
      4 
      5 In order to communicate with the keyboard using this feature, you will need to write a program that runs on the host. As such, some basic programming skills are required - more if you intend to implement complex behaviour.
      6 
      7 ## Usage {#usage}
      8 
      9 Add the following to your `rules.mk`:
     10 
     11 ```make
     12 RAW_ENABLE = yes
     13 ```
     14 
     15 ## Basic Configuration {#basic-configuration}
     16 
     17 By default, the HID Usage Page and Usage ID for the Raw HID interface are `0xFF60` and `0x61`. However, they can be changed if necessary by adding the following to your `config.h`:
     18 
     19 |Define          |Default |Description                            |
     20 |----------------|--------|---------------------------------------|
     21 |`RAW_USAGE_PAGE`|`0xFF60`|The usage page of the Raw HID interface|
     22 |`RAW_USAGE_ID`  |`0x61`  |The usage ID of the Raw HID interface  |
     23 
     24 ## Sending Data to the Keyboard {#sending-data-to-the-keyboard}
     25 
     26 To send data to the keyboard, you must first find a library for communicating with HID devices in the programming language of your choice. Here are some examples:
     27 
     28 * **Node.js:** [node-hid](https://github.com/node-hid/node-hid)
     29 * **C/C++:** [hidapi](https://github.com/libusb/hidapi)
     30 * **Java:** [purejavahidapi](https://github.com/nyholku/purejavahidapi) and [hid4java](https://github.com/gary-rowe/hid4java)
     31 * **Python:** [pyhidapi](https://pypi.org/project/hid/) and [pywinusb](https://pypi.org/project/pywinusb)
     32 
     33 Please refer to these libraries' own documentation for instructions on usage. Remember to close the device once you are finished with it!
     34 
     35 Next, you will need to know the USB Vendor and Product IDs of the device. These can easily be found by looking at your keyboard's `info.json`, under the `usb` object (alternatively, you can also use Device Manager on Windows, System Information on macOS, or `lsusb` on Linux). For example, the Vendor ID for the Planck Rev 6 is `0x03A8`, and the Product ID is `0xA4F9`.
     36 
     37 It's also a good idea to narrow down the list of potential HID devices the library may give you by filtering on the usage page and usage ID, to avoid accidentally opening the interface on the same device for the keyboard, or mouse, or media keys, etc.
     38 
     39 Once you are able to open the HID device and send reports to it, it's time to handle them on the keyboard side. Implement the following function in your `keymap.c` and start coding:
     40 
     41 ```c
     42 void raw_hid_receive(uint8_t *data, uint8_t length) {
     43     // Your code goes here
     44     // `data` is a pointer to the buffer containing the received HID report
     45     // `length` is the length of the report - always `RAW_EPSIZE`
     46 }
     47 ```
     48 
     49 ::: warning
     50 Because the HID specification does not support variable length reports, all reports in both directions must be exactly `RAW_EPSIZE` (currently 32) bytes long, regardless of actual payload length. However, variable length payloads can potentially be implemented on top of this by creating your own data structure that may span multiple reports.
     51 :::
     52 
     53 ## Receiving Data from the Keyboard {#receiving-data-from-the-keyboard}
     54 
     55 If you need the keyboard to send data back to the host, simply call the `raw_hid_send()` function. It requires two arguments - a pointer to a 32-byte buffer containing the data you wish to send, and the length (which should always be `RAW_EPSIZE`).
     56 
     57 The received report can then be handled in whichever way your HID library provides.
     58 
     59 ## Simple Example {#simple-example}
     60 
     61 The following example reads the first byte of the received report from the host, and if it is an ASCII "A", responds with "B". `memset()` is used to fill the response buffer (which could still contain the previous response) with null bytes.
     62 
     63 ```c
     64 void raw_hid_receive(uint8_t *data, uint8_t length) {
     65     uint8_t response[length];
     66     memset(response, 0, length);
     67     response[0] = 'B';
     68 
     69     if(data[0] == 'A') {
     70         raw_hid_send(response, length);
     71     }
     72 }
     73 ```
     74 
     75 On the host side (here we are using Python and the `pyhidapi` library), the HID device is opened by enumerating the interfaces on the USB device, then filtering on the usage page and usage ID. Then, a report containing a single ASCII "A" (hex `0x41`) is constructed and sent.
     76 
     77 For demonstration purposes, the manufacturer and product strings of the device, along with the request and response, are also printed.
     78 
     79 ```python
     80 import sys
     81 import hid
     82 
     83 vendor_id     = 0x4335
     84 product_id    = 0x0002
     85 
     86 usage_page    = 0xFF60
     87 usage         = 0x61
     88 report_length = 32
     89 
     90 def get_raw_hid_interface():
     91     device_interfaces = hid.enumerate(vendor_id, product_id)
     92     raw_hid_interfaces = [i for i in device_interfaces if i['usage_page'] == usage_page and i['usage'] == usage]
     93 
     94     if len(raw_hid_interfaces) == 0:
     95         return None
     96 
     97     interface = hid.Device(path=raw_hid_interfaces[0]['path'])
     98 
     99     print(f"Manufacturer: {interface.manufacturer}")
    100     print(f"Product: {interface.product}")
    101 
    102     return interface
    103 
    104 def send_raw_report(data):
    105     interface = get_raw_hid_interface()
    106 
    107     if interface is None:
    108         print("No device found")
    109         sys.exit(1)
    110 
    111     request_data = [0x00] * (report_length + 1) # First byte is Report ID
    112     request_data[1:len(data) + 1] = data
    113     request_report = bytes(request_data)
    114 
    115     print("Request:")
    116     print(request_report)
    117 
    118     try:
    119         interface.write(request_report)
    120 
    121         response_report = interface.read(report_length, timeout=1000)
    122 
    123         print("Response:")
    124         print(response_report)
    125     finally:
    126         interface.close()
    127 
    128 if __name__ == '__main__':
    129     send_raw_report([
    130         0x41
    131     ])
    132 ```
    133 
    134 ## API {#api}
    135 
    136 ### `void raw_hid_receive(uint8_t *data, uint8_t length)` {#api-raw-hid-receive}
    137 
    138 Callback, invoked when a raw HID report has been received from the host.
    139 
    140 #### Arguments {#api-raw-hid-receive-arguments}
    141 
    142  - `uint8_t *data`  
    143    A pointer to the received data. Always 32 bytes in length.
    144  - `uint8_t length`  
    145    The length of the buffer. Always 32.
    146 
    147 ---
    148 
    149 ### `void raw_hid_send(uint8_t *data, uint8_t length)` {#api-raw-hid-send}
    150 
    151 Send an HID report.
    152 
    153 #### Arguments {#api-raw-hid-send-arguments}
    154 
    155  - `uint8_t *data`  
    156    A pointer to the data to send. Must always be 32 bytes in length.
    157  - `uint8_t length`  
    158    The length of the buffer. Must always be 32.