Skip to content

Commit 29a4e07

Browse files
Retry memory reads as they fail just after flash
It's common to flash a program and then attempt to connect
1 parent 4cb6952 commit 29a4e07

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

lib/usb-device-wrapper.ts

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,10 +118,33 @@ export class DAPWrapper {
118118
});
119119
}
120120

121+
// https://support.microbit.org/support/solutions/articles/19000067679-how-to-find-the-name-of-your-micro-bit
122+
// We wait on errors as immediately after flash the micro:bit won't be ready to respond
123+
this._deviceId = await this.readMem32WaitOnError(FICR.DEVICE_ID_1);
124+
121125
this._pageSize = await this.cortexM.readMem32(FICR.CODEPAGESIZE);
122126
this._numPages = await this.cortexM.readMem32(FICR.CODESIZE);
123-
// https://support.microbit.org/support/solutions/articles/19000067679-how-to-find-the-name-of-your-micro-bit
124-
this._deviceId = await this.cortexM.readMem32(FICR.DEVICE_ID_1);
127+
}
128+
129+
async readMem32WaitOnError(register: number): Promise<number> {
130+
let retries = 0;
131+
let lastError: Error | undefined;
132+
while (retries < 10) {
133+
try {
134+
return await this.cortexM.readMem32(register);
135+
} catch (e) {
136+
if (e instanceof Error) {
137+
lastError = e;
138+
if (/^Transfer/.test(e.message)) {
139+
retries++;
140+
await new Promise((resolve) => setTimeout(resolve, 10));
141+
} else {
142+
throw e;
143+
}
144+
}
145+
}
146+
}
147+
throw lastError;
125148
}
126149

127150
async startSerial(listener: (data: string) => void): Promise<void> {

0 commit comments

Comments
 (0)