usb/sagas: Fix command response race condition

Fix a race condition where a response to a USB command could be missed
if it arrives before the USB transferOut() call returns. This is done
by using a channel to buffer incoming responses.

Fixes: https://github.com/pybricks/support/issues/2467
This commit is contained in:
David Lechner
2026-01-25 14:30:05 -06:00
parent fa275b8000
commit 457fa8b6b2
+7 -1
View File
@@ -454,6 +454,12 @@ function* handleUsbConnectPybricks(hotPlugDevice?: USBDevice): Generator {
writeCommand.matches(a),
);
// Response may come before request returns, so we need to buffer them
// in a channel to avoid missing responses.
const responseChannel = yield* actionChannel(
usbDidReceivePybricksMessageResponse,
);
for (;;) {
const action = yield* take(chan);
@@ -525,7 +531,7 @@ function* handleUsbConnectPybricks(hotPlugDevice?: USBDevice): Generator {
}
const { response, timeout } = yield* race({
response: take(usbDidReceivePybricksMessageResponse),
response: take(responseChannel),
timeout: delay(1000),
});