From a73eb786a53aba16d17ae2c7b9efe57bbf0ce0de Mon Sep 17 00:00:00 2001 From: Kirill Zhumarin Date: Mon, 4 Aug 2025 12:17:15 +0000 Subject: [PATCH] Optimize AsyncSerialPort --- src/AsyncSerialPort.ts | 27 +++++++++++++-------------- src/DWD.ts | 2 +- src/io.ts | 2 +- 3 files changed, 15 insertions(+), 16 deletions(-) diff --git a/src/AsyncSerialPort.ts b/src/AsyncSerialPort.ts index 63cec93..fd63fe7 100644 --- a/src/AsyncSerialPort.ts +++ b/src/AsyncSerialPort.ts @@ -58,6 +58,12 @@ export class AsyncSerialPort { } async read(size: number, timeout?: number): Promise { + if (!this.port.isOpen) + throw new Error("Port is not open"); + + if (this.port.readableLength >= size) + return this.port.read(size); + return new Promise((resolve, reject) => { let result: Buffer | undefined; let bytesRead = 0; @@ -107,8 +113,10 @@ export class AsyncSerialPort { } }; - if (!this.port.isOpen) - reject(new Error("Port is not open")); + if (this.port.readableLength > 0) + onReadable(); + if (bytesRead == size) + return; this.port.on("close", onClose); this.port.on("end", onEnd); @@ -121,18 +129,9 @@ export class AsyncSerialPort { } async write(data: any): Promise { - return new Promise((resolve, reject) => { - if (!this.port.isOpen) - reject(new Error("Port is not open")); - this.port.write(data); - this.port.drain((err) => { - if (err) { - reject(err); - } else { - resolve(); - } - }); - }); + if (!this.port.isOpen) + throw new Error("Port is not open"); + this.port.write(data); } async getSignals(): Promise { diff --git a/src/DWD.ts b/src/DWD.ts index 354efdb..385084a 100644 --- a/src/DWD.ts +++ b/src/DWD.ts @@ -247,7 +247,7 @@ export class DWD extends BaseSerialProtocol { return ioWriteMemory({ debug, align: 4, - pageSize: 128, + pageSize: MAX_MEMORY_WRITE_CHUNK, maxRetries: 3, write: this.writeMemoryChunk.bind(this) }, address, buffer, options); diff --git a/src/io.ts b/src/io.ts index 4b9abae..807ddae 100644 --- a/src/io.ts +++ b/src/io.ts @@ -124,7 +124,7 @@ export function ioProgressTracker(options: IoProgressOptions) { lastSpeedCheck = Date.now(); } - if (!options.progressInterval || (Date.now() - lastProgressCalled > options.progressInterval && cursor > 0)) { + if (!options.progressInterval || (Date.now() - lastProgressCalled >= options.progressInterval && cursor > 0)) { reportProgressDirect(); progressCalled = true; } else {