Skip to content

Commit

Permalink
fix: recreate readable/writable when cancelled
Browse files Browse the repository at this point in the history
  • Loading branch information
sverben committed Jan 26, 2025
1 parent 0f02bc0 commit 65202c4
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 9 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@leaphy-robotics/playwright-arduino",
"version": "1.0.5",
"version": "1.0.6",
"license": "LGPL-3.0-only",
"main": "./dist/index.js",
"type": "module",
Expand Down
39 changes: 31 additions & 8 deletions src/page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,10 @@ if (!globalThis.getPorts) {
}

class SerialPort {
readable?: ReadableStream<Uint8Array> = undefined
writable?: WritableStream<Uint8Array> = undefined
private active = false
private activeReadable?: ReadableStream<Uint8Array> = undefined
private activeWritable?: WritableStream<Uint8Array> = undefined

vendorId = 0x0403
productId = 0x6001

Expand All @@ -65,30 +67,51 @@ class SerialPort {
if (err instanceof Error) throw err

await globalThis.readPort(port)
this.readable = new ReadableStream({
this.active = true
}

get readable() {
if (!this.active) return
if (this.activeReadable) return this.activeReadable

this.activeReadable = new ReadableStream({
type: 'bytes',
async pull(controller) {
globalThis.readCallback = (data: number[]) => {
try {
controller.enqueue(new Uint8Array(data))
} catch { }
}
},
cancel: () => {
this.activeReadable = undefined
}
}, {
highWaterMark: 512,
})
this.writable = new WritableStream({
async write(chunk) {
const err = await globalThis.writePort(port, Array.from(chunk.values()))

return this.activeReadable
}

get writable() {
if (!this.active) return
if (this.activeWritable) return this.activeWritable

this.activeWritable = new WritableStream({
write: async (chunk) => {
const err = await globalThis.writePort(this.id, Array.from(chunk.values()))
if (err instanceof Error) throw err
},
close: () => {
this.activeWritable = undefined
}
})
return this.activeWritable
}

async close() {
const err = await globalThis.closePort(this.id)
this.readable = undefined
this.writable = undefined
this.active = false
if (err) throw err
}

Expand Down

0 comments on commit 65202c4

Please sign in to comment.