@@ -52,6 +52,7 @@ class SerialConnectionHandler {
52
52
this . timeout = timeout ;
53
53
this . currentPort = null ;
54
54
this . currentReader = null ;
55
+ this . readableStreamClosed = null ;
55
56
this . registerEvents ( ) ;
56
57
}
57
58
@@ -118,6 +119,7 @@ class SerialConnectionHandler {
118
119
const port = this . currentPort ;
119
120
this . currentPort = null ;
120
121
await this . currentReader ?. cancel ( ) ;
122
+ await this . readableStreamClosed . catch ( ( ) => { } ) ; // Ignores the error
121
123
await port . close ( ) ;
122
124
console . log ( '🔌 Disconnected from serial port.' ) ;
123
125
if ( this . onDisconnect ) this . onDisconnect ( ) ;
@@ -163,10 +165,12 @@ class SerialConnectionHandler {
163
165
return null ;
164
166
}
165
167
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 ( ) ;
170
174
this . currentReader = reader ;
171
175
let timeoutID = null ;
172
176
@@ -190,6 +194,7 @@ class SerialConnectionHandler {
190
194
} finally {
191
195
// console.log('🔓 Releasing reader lock...');
192
196
await reader ?. cancel ( ) ; // Discards any enqueued data
197
+ await this . readableStreamClosed . catch ( ( ) => { } ) ; // Ignores the error
193
198
reader ?. releaseLock ( ) ;
194
199
this . currentReader = null ;
195
200
}
0 commit comments