Skip to content

Commit

Permalink
Bugfix: reader has reference to readable so it can change (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
Jesper Lindstrøm Nielsen authored Oct 22, 2021
1 parent bdc425f commit 7bd3427
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 8 deletions.
6 changes: 3 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ export class EspLoader {
},
options || {}
);
this.reader = new Reader();
this.reader = new Reader(serialPort);
this.serialPort = serialPort;
}

Expand All @@ -121,7 +121,7 @@ export class EspLoader {
* ESP ROM bootloader, we will retry a few times
*/
async connect(retries = 7): Promise<void> {
this.reader.start(this.serialPort.readable);
this.reader.start();
let connected = false;
for (let i = 0; i < retries; i++) {
if (i > 0) {
Expand Down Expand Up @@ -420,7 +420,7 @@ export class EspLoader {

// Reopen the port and read loop
await this.serialPort.open({ baudRate: baud });
this.reader.start(this.serialPort.readable);
this.reader.start();
await sleep(50);
const wasSilent = await this.reader.waitSilent(10, 200);
if (!wasSilent) {
Expand Down
17 changes: 12 additions & 5 deletions src/reader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,28 +13,35 @@ import {

export type Unlisten = () => void;

export interface ReadableOwner {
readonly readable: ReadableStream<Uint8Array>;
}

export class Reader {
private buffer: Uint8Buffer;
private readableOwner: ReadableOwner;

private running = false;
private closing = false;

private reader: ReadableStreamDefaultReader<Uint8Array> | undefined = undefined;
private completer: Completer<void> | undefined = undefined;
private runPromise: Promise<void> | undefined = undefined;
private listenRef = 0;

public constructor() {
public constructor(readableOwner: ReadableOwner) {
this.buffer = new Uint8Buffer();
this.readableOwner = readableOwner;
}

public start(readable: ReadableStream<Uint8Array>): void {
public start(): void {
if (this.runPromise !== undefined) {
throw AlreadyRunningError;
}

this.buffer.reset();
this.closing = false;
this.runPromise = this.run(readable);
this.runPromise = this.run();
}

public async stop(): Promise<unknown> {
Expand All @@ -59,12 +66,12 @@ export class Reader {
}
}

private async run(readable: ReadableStream<Uint8Array>): Promise<void> {
private async run(): Promise<void> {
try {
this.running = true;
while (!this.closing) {
if (this.reader === undefined) {
this.reader = readable.getReader();
this.reader = this.readableOwner.readable.getReader();
}
const reader = this.reader;
try {
Expand Down

0 comments on commit 7bd3427

Please sign in to comment.