0

This function goes through all the matrices of a keyboard, asks the keyboard for the keycode in each place and pushes it to the layerKeycodes array.

The problem is that device.read() is asynchronous and I couldn't find a way to make it synchronous without having super messy code.

The problem is that the console.log() at the end (which will be return in production) gets fired before the keyboard replies and sends back the keycodes. I know that device.readSync() exists, but the documentation of node-hid (USB-HID device access from Node.js) is bad, and I couldn't find out how to use it.

const getLayerKeycodes = (keyboard, layer, rows, columns) => {
    // Array that stores all the keycodes according to their order
    let layerKeycodes = [];

    // Rows and columns start the count at 0 in low level, so we need to decrease one from the actual number.
    columns --;
    rows --;

    // Loop that asks about all the keycodes in a layer
    const dataReceived = (err, data) => {
        if(err) {
            return err;
        }
        // Push the current keycode to the array
        // The keycode is always returned as the fifth object.
        layerKeycodes.push(data[5]);
        console.log(layerKeycodes);
    };

    for (let r = 0, c = 0; c <= columns; r ++) {
        // Callback to fire once data is receieved back from the keyboard.
        if(r > rows) {
            c++;
            // 'r' will turn to 0 once the continue fires and the loop executes again
            r = -1;
            continue;
        }
        // Start listening and call dataReceived when data is received
        keyboard[0].read(dataReceived);

        // Ask keyboard for information about keycode
        // [always 0 (first byte is ignored), always 0x04 (get_keycode), layer requested, row being checked, column being checked]
        keyboard[0].write([0x01, 0x04, layer, r, c]);
    }
    console.log(layerKeycodes);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

0 Answers0