@@ -52,6 +52,7 @@ class SerialConnectionHandler {
5252 this . timeout = timeout ;
5353 this . currentPort = null ;
5454 this . currentReader = null ;
55+ this . readableStreamClosed = null ;
5556 this . registerEvents ( ) ;
5657 }
5758
@@ -118,6 +119,7 @@ class SerialConnectionHandler {
118119 const port = this . currentPort ;
119120 this . currentPort = null ;
120121 await this . currentReader ?. cancel ( ) ;
122+ await this . readableStreamClosed . catch ( ( ) => { } ) ; // Ignores the error
121123 await port . close ( ) ;
122124 console . log ( '🔌 Disconnected from serial port.' ) ;
123125 if ( this . onDisconnect ) this . onDisconnect ( ) ;
@@ -163,10 +165,12 @@ class SerialConnectionHandler {
163165 return null ;
164166 }
165167
166- const transformer = new BytesWaitTransformer ( numBytes ) ;
167- const transformStream = new TransformStream ( transformer ) ;
168- const pipedStream = this . currentPort . readable . pipeThrough ( transformStream ) ;
169- const reader = pipedStream . getReader ( ) ;
168+ const transformStream = new TransformStream ( new BytesWaitTransformer ( numBytes ) ) ;
169+ // pipeThrough() cannot be used because we need a promise that resolves when the stream is closed
170+ // to be able to close the port. pipeTo() returns such a promise.
171+ // SEE: https://stackoverflow.com/questions/71262432/how-can-i-close-a-web-serial-port-that-ive-piped-through-a-transformstream
172+ this . readableStreamClosed = this . currentPort . readable . pipeTo ( transformStream . writable ) ;
173+ const reader = transformStream . readable . getReader ( ) ;
170174 this . currentReader = reader ;
171175 let timeoutID = null ;
172176
@@ -190,6 +194,7 @@ class SerialConnectionHandler {
190194 } finally {
191195 // console.log('🔓 Releasing reader lock...');
192196 await reader ?. cancel ( ) ; // Discards any enqueued data
197+ await this . readableStreamClosed . catch ( ( ) => { } ) ; // Ignores the error
193198 reader ?. releaseLock ( ) ;
194199 this . currentReader = null ;
195200 }
0 commit comments