Search code examples
cusblibusb

How do I prevent losing data in USB transfers?


I am writing a program that interacts directly with a USB peripheral via libusb. The device in question has (among other things) a button, with an LED on it. I read the state of the button via an asynchronous interrupt transfer, and then once a press is detected, I set the button's LED to on, until I detect that the button has been released. I make a new asynchronous interrupt transfer to read from the device every time I receive more data, so I can read multiple events from the device in a loop.

The problem with this is that I don't get data from the device unless I have a pending read operation on the device when the data is generated. That is, if I am not actively waiting on a read when the button is pressed or released, that data is simply lost. Because there is a window in between receiving data and making another asynchronous interrupt read request, sometimes data is lost and e.g. I will get the "button pressed" event, but not the "button released" event and the LED stays on even after I have stopped pressing the button.

Is there some other way to interact with the device (other than interrupt transfers in a loop) that can guarantee that no data is lost, even if I do not have a pending read operation at the time that the device generates the data? Or, is there a way to ensure there is no window where I am not reading from the device, and prevent data loss that way?


Solution

  • I fixed the problem by simply scheduling multiple interrupt transfers at once, so when one returned, there would still be another waiting for data. I was worried about what happens if the second returns before the first schedules another interrupt transfer, but in practice, that doesn't seem to happen for this device.