Skip to content

Commit

Permalink
Retry transient errors such as buffer overrun (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jesper Lindstrøm Nielsen authored Sep 30, 2021
1 parent 4cbb84c commit 696117c
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
24 changes: 22 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// found in the LICENSE file.

import { ESP32, Stub } from "./stubs";
import { sleep, toByteArray, toHex, Uint8Buffer, Uint8BufferSlipEncode } from "./util";
import { isTransientError, sleep, toByteArray, toHex, Uint8Buffer, Uint8BufferSlipEncode } from "./util";

export enum ChipFamily {
ESP32 = "esp32",
Expand Down Expand Up @@ -458,6 +458,26 @@ export class EspLoader {

private async readLoop() {
this.inputBuffer.reset();
try {
while (!this.closed) {
try {
await this.readLoopInner();
} catch (e) {
const rethrow = !isTransientError(e);
if (this.options.debug) {
this.logger.debug("readLoop error", e, "rethrow?", rethrow);
}
if (rethrow) {
throw e;
}
}
}
} finally {
this.closed = true;
}
}

private async readLoopInner() {
this.serialReader = this.serialPort.readable.getReader();
try {
while (!this.closed) {
Expand Down Expand Up @@ -511,7 +531,7 @@ export class EspLoader {
* ESP ROM bootloader, we will retry a few times
*/
async sync(): Promise<void> {
for (let i = 0; i < 5; i++) {
for (let i = 0; i < 10; i++) {
const response = await this._sync();
if (response) {
await sleep(100);
Expand Down
12 changes: 12 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -171,3 +171,15 @@ export function toByteArray(str: string): Uint8Array {
export function toHex(value: number, size = 2): string {
return "0x" + value.toString(16).toUpperCase().padStart(size, "0");
}

export function isTransientError(e: unknown): boolean {
if (e instanceof DOMException) {
return (
e.name === "BufferOverrunError" ||
e.name === "BreakError" ||
e.name === "FramingError" ||
e.name === "ParityError"
);
}
return false;
}

0 comments on commit 696117c

Please sign in to comment.