Skip to content

Commit

Permalink
bullet proofing on focus port closing
Browse files Browse the repository at this point in the history
  • Loading branch information
obra committed Feb 6, 2024
1 parent 6304fba commit 2fd6503
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 7 deletions.
4 changes: 4 additions & 0 deletions src/api/flash/AVR109Flasher.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

import Focus from "@api/focus";

import { parseIntelHex } from "./IntelHexParser";

const AVR109_RESPONSE_OK = "\r";
Expand Down Expand Up @@ -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) => {
Expand All @@ -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 });
Expand Down
33 changes: 26 additions & 7 deletions src/api/focus.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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);
Expand Down Expand Up @@ -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;
Expand Down

0 comments on commit 2fd6503

Please sign in to comment.