@@ -51,8 +51,10 @@ if (!globalThis.getPorts) {
5151}
5252
5353class SerialPort {
54- readable ?: ReadableStream < Uint8Array > = undefined
55- writable ?: WritableStream < Uint8Array > = undefined
54+ private active = false
55+ private activeReadable ?: ReadableStream < Uint8Array > = undefined
56+ private activeWritable ?: WritableStream < Uint8Array > = undefined
57+
5658 vendorId = 0x0403
5759 productId = 0x6001
5860
@@ -65,30 +67,51 @@ class SerialPort {
6567 if ( err instanceof Error ) throw err
6668
6769 await globalThis . readPort ( port )
68- this . readable = new ReadableStream ( {
70+ this . active = true
71+ }
72+
73+ get readable ( ) {
74+ if ( ! this . active ) return
75+ if ( this . activeReadable ) return this . activeReadable
76+
77+ this . activeReadable = new ReadableStream ( {
6978 type : 'bytes' ,
7079 async pull ( controller ) {
7180 globalThis . readCallback = ( data : number [ ] ) => {
7281 try {
7382 controller . enqueue ( new Uint8Array ( data ) )
7483 } catch { }
7584 }
85+ } ,
86+ cancel : ( ) => {
87+ this . activeReadable = undefined
7688 }
7789 } , {
7890 highWaterMark : 512 ,
7991 } )
80- this . writable = new WritableStream ( {
81- async write ( chunk ) {
82- const err = await globalThis . writePort ( port , Array . from ( chunk . values ( ) ) )
92+
93+ return this . activeReadable
94+ }
95+
96+ get writable ( ) {
97+ if ( ! this . active ) return
98+ if ( this . activeWritable ) return this . activeWritable
99+
100+ this . activeWritable = new WritableStream ( {
101+ write : async ( chunk ) => {
102+ const err = await globalThis . writePort ( this . id , Array . from ( chunk . values ( ) ) )
83103 if ( err instanceof Error ) throw err
104+ } ,
105+ close : ( ) => {
106+ this . activeWritable = undefined
84107 }
85108 } )
109+ return this . activeWritable
86110 }
87111
88112 async close ( ) {
89113 const err = await globalThis . closePort ( this . id )
90- this . readable = undefined
91- this . writable = undefined
114+ this . active = false
92115 if ( err ) throw err
93116 }
94117
0 commit comments