Skip to content

Commit 7ef6c02

Browse files
afaragodlech
authored andcommitted
firmware/sagas: fix race condition in EV3 sendCommand()
Start listening for reply before sending command to avoid race condition of reply being received and action dispatched before we call take().
1 parent 4263051 commit 7ef6c02

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

src/firmware/sagas.ts

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import { eventChannel } from 'redux-saga';
2020
import { ActionPattern } from 'redux-saga/effects';
2121
import {
2222
SagaGenerator,
23+
actionChannel,
2324
all,
2425
call,
2526
cancel,
@@ -1116,8 +1117,11 @@ function* handleFlashEV3(action: ReturnType<typeof firmwareFlashEV3>): Generator
11161117
command: number,
11171118
payload?: Uint8Array,
11181119
): SagaGenerator<[DataView | undefined, Error | undefined]> {
1119-
console.debug(`EV3 send: command=${command}, payload=${payload}`);
1120+
// We need to start listing for reply before sending command in order
1121+
// to avoid race conditions.
1122+
const replyChannel = yield* actionChannel(firmwareDidReceiveEV3Reply);
11201123

1124+
// Send the command
11211125
const dataBuffer = new Uint8Array((payload?.byteLength ?? 0) + 6);
11221126
const data = new DataView(dataBuffer.buffer);
11231127

@@ -1130,15 +1134,18 @@ function* handleFlashEV3(action: ReturnType<typeof firmwareFlashEV3>): Generator
11301134
}
11311135

11321136
const [, sendError] = yield* call(() => maybe(hidDevice.sendReport(0, data)));
1133-
11341137
if (sendError) {
1138+
replyChannel.close();
11351139
return [undefined, sendError];
11361140
}
11371141

11381142
const { reply, timeout } = yield* race({
1139-
reply: take(firmwareDidReceiveEV3Reply),
1143+
reply: take(replyChannel),
11401144
timeout: delay(5000),
11411145
});
1146+
1147+
replyChannel.close();
1148+
11421149
if (timeout) {
11431150
return [undefined, new Error('Timeout waiting for EV3 reply')];
11441151
}

0 commit comments

Comments
 (0)