From 2fd6503e3b6fff47fe9a9dfea50dc4f09033f264 Mon Sep 17 00:00:00 2001 From: Jesse Vincent Date: Mon, 5 Feb 2024 16:32:42 -0800 Subject: [PATCH] bullet proofing on focus port closing --- src/api/flash/AVR109Flasher.js | 4 ++++ src/api/focus.js | 33 ++++++++++++++++++++++++++------- 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/src/api/flash/AVR109Flasher.js b/src/api/flash/AVR109Flasher.js index 2efe863a7..c8191e3b1 100644 --- a/src/api/flash/AVR109Flasher.js +++ b/src/api/flash/AVR109Flasher.js @@ -14,6 +14,8 @@ * along with this program. If not, see . */ +import Focus from "@api/focus"; + import { parseIntelHex } from "./IntelHexParser"; const AVR109_RESPONSE_OK = "\r"; @@ -41,6 +43,7 @@ const flash = async (port, filecontents) => { var enc = new TextDecoder("utf-8"); console.log("filecontents"); console.log(filecontents); + const focus = new Focus(); var hexAsText = enc.decode(filecontents); return new Promise((resolve, reject) => { @@ -52,6 +55,7 @@ const flash = async (port, filecontents) => { // Wait for the serial port to open. // Wait for the serial port to open. + await focus.closePort(); try { if (!port.readable && !port.writable) { await port.open({ baudRate: 57600 }); diff --git a/src/api/focus.js b/src/api/focus.js index d4557cd16..2fd8fa69d 100644 --- a/src/api/focus.js +++ b/src/api/focus.js @@ -151,6 +151,29 @@ class Focus { return true; } + async closePort() { + // Attempt to cancel and release any existing reader locks + if (this._port.readable && this._port.readable.locked) { + const reader = this._port.readable.getReader(); + await reader.cancel(); + reader.releaseLock(); + } + + // Attempt to close and release any existing writer locks + if (this._port.writable && this._port.writable.locked) { + console.log("close writer?"); + const writer = this._port.writable.getWriter(); + await writer.close(); + writer.releaseLock(); + } + + try { + await this._port.close(); + } catch (error) { + console.error("Failed to safely close the port:", error); + } + } + async reboot(withDeviceReset) { const port = this._port; @@ -160,9 +183,7 @@ class Focus { const baudUpdate = async () => { console.debug("reboot: baud update"); - if (port.readable || port.writable) { - await port.close(); - } + await this.closePort(); await port.open({ baudRate: 1200 }); await delay(timeouts.dtrToggle); @@ -286,10 +307,8 @@ class Focus { return this._port; } - close() { - if ((this._port !== null && this._port.readable) || this._port.writable) { - this._port.close(); - } + async close() { + await this.closePort(); this._port = null; this._parser = null; this.focusDeviceDescriptor = null;