Search code examples
javascriptnode.jswebusbwebhid

Wait for WebHID response to be ready


I'm sending data to the target device using device.sendReport(reportID, dataBuffer) of WebHID, but trying to read the response before it gets ready (i.e) the response takes time to be generated.

For now by setting timeout for 10ms, I'm able to get the response. Would like to know if there are any better solution for this.


Solution

  • You haven't said how the device provides the response but I assume that it is in the form of an input report. In that case the Promise returned by sendReport() isn't particularly interesting but instead you want to listen for an inputreport event that will be fired at the HIDDevice. If you want you can turn this into a Promise like this,

    const response = new Promise((resolve) => {
      device.addEventListener('inputreport', resolve, { once: true });
    });
    await device.sendReport(...your data...);
    const { reportId, data } = await response;
    

    Once the response is received it will be stored in data.

    Note that this assumes that the device only generates input reports in response to a request. For a device with more complex communications you may want to have an inputreport event listener registered at all times and process input reports based on their report ID or other factors. HID does not support any backpressure so if you don't have an inputreport event listener registered when a report is sent by the device it will be discarded.