@@ -51,8 +51,10 @@ if (!globalThis.getPorts) {
51
51
}
52
52
53
53
class 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
+
56
58
vendorId = 0x0403
57
59
productId = 0x6001
58
60
@@ -65,30 +67,51 @@ class SerialPort {
65
67
if ( err instanceof Error ) throw err
66
68
67
69
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 ( {
69
78
type : 'bytes' ,
70
79
async pull ( controller ) {
71
80
globalThis . readCallback = ( data : number [ ] ) => {
72
81
try {
73
82
controller . enqueue ( new Uint8Array ( data ) )
74
83
} catch { }
75
84
}
85
+ } ,
86
+ cancel : ( ) => {
87
+ this . activeReadable = undefined
76
88
}
77
89
} , {
78
90
highWaterMark : 512 ,
79
91
} )
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 ( ) ) )
83
103
if ( err instanceof Error ) throw err
104
+ } ,
105
+ close : ( ) => {
106
+ this . activeWritable = undefined
84
107
}
85
108
} )
109
+ return this . activeWritable
86
110
}
87
111
88
112
async close ( ) {
89
113
const err = await globalThis . closePort ( this . id )
90
- this . readable = undefined
91
- this . writable = undefined
114
+ this . active = false
92
115
if ( err ) throw err
93
116
}
94
117
0 commit comments