-
Notifications
You must be signed in to change notification settings - Fork 0
/
serialstream.ts
426 lines (364 loc) · 16 KB
/
serialstream.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
import { ByteParser } from '../util/ByteParser';
//Joshua Brewster. LGPL v3.0
import '../hacktimer/HackTimer.min' //prevents timer lock on tab content loss
//Wrapper for
//https://developer.mozilla.org/en-US/docs/Web/API/Web_Serial_API
export type SerialPortOptions = {
baudRate?:number,
stopBits?:1|2|number,
parity?:'none'|'even'|'odd'|ParityType,
bufferSize?:number,
flowControl?:'none'|'hardware'|FlowControlType,
onconnect?:(port:SerialPort)=>void,
beforedisconnect?:(client:WebSerial,port:SerialPort)=>void,
ondisconnect?:(ev)=>void
}
export type SerialStreamProps = {
_id?:string,
port:SerialPort,
settings:SerialPortOptions,
frequency:number,
ondata:(value:any)=>void,
transforms?:{
[key:string]:{
transform:TransformerTransformCallback<DataView, any>,
start?:TransformerStartCallback<any>,
flush?:TransformerFlushCallback<any>,
writableStrategy?:QueuingStrategy<DataView>,
readableStrategy?:QueuingStrategy<DataView>,
streamPipeOptions?:StreamPipeOptions
}|TransformStream
},
buffering?:{ //if defined the data will be buffered and a search applied to pass differentiable lines to ondata e.g. \r\n
searchBytes?:Uint8Array, //
buffer?:any[], //byte buffer
locked?:boolean, //locked on to search byte intervals?
lockIdx?:number //first found search buffer to lock onto stream
}|boolean
}
export type SerialStreamInfo = {
_id:string,
port:SerialPort,
settings:SerialPortOptions,
info:Partial<SerialPortInfo>,
reader:ReadableStreamDefaultReader<any>,
//writer:WritableStreamDefaultWriter<any>,
transforms?:{
[key:string]:{
transform:TransformerTransformCallback<DataView, any>,
start?:TransformerStartCallback<any>,
flush?:TransformerFlushCallback<any>,
writableStrategy?:QueuingStrategy<DataView>,
readableStrategy?:QueuingStrategy<DataView>,
streamPipeOptions?:StreamPipeOptions
}|TransformStream
},
buffering?:{ //if defined the data will be buffered and a search applied to pass differentiable lines to ondata e.g. \r\n
searchBytes?:Uint8Array, //
buffer?:any[], //byte buffer
locked?:boolean, //locked on to search byte intervals?
lockIdx?:number //first found search buffer to lock onto stream
}
frequency:number, //read frequency, just a setTimeout after every read finishes to allow coroutines to do their thing as the .read call will await to receive and block the app if not on its own thread
ondata:(value:any)=>void,
running:boolean,
[key:string]:any
}
export class WebSerial extends ByteParser {
streams:{[key:string]:SerialStreamInfo} = {}
getPorts() {
return navigator.serial.getPorts();
}
requestPort(
usbVendorId?:number,
usbProductId?:number,
) {
let options:any = {}
if(usbVendorId) {
options.usbVendorId = usbVendorId;
}
if(usbProductId) {
options.usbProductId = usbProductId;
}
if(options.usbVendorId)
return navigator.serial.requestPort({filters:[options]})
else
return navigator.serial.requestPort()
}
openPort(
port:SerialPort,
options?:SerialPortOptions
) {
if(options) options = Object.assign({},options);
if((options as any)?.ondisconnect) {
port.ondisconnect = (options as any).ondisconnect;
delete (options as any).ondisconnect;
}
return port.open(options as SerialOptions).then(()=>{
if(options?.onconnect) options.onconnect(port);
});
}
//https://wicg.github.io/serial/#readable-attribute
async readWithTimeout(port:SerialPort, timeout:number) {
const reader = port.readable.getReader();
const timer = setTimeout(() => {
reader.releaseLock();
}, timeout);
const result = await reader.read();
clearTimeout(timer);
reader.releaseLock();
return result;
}
//write a port with a one-off writer.
async writePort(port:SerialPort,message:any, chunkSize?:number) {
const writer = port.writable.getWriter();
if(chunkSize) {
const view = WebSerial.toDataView(message);
const len = view.buffer.byteLength;
for(let i = 0; i < len; i += chunkSize) {
let endIdx = i+chunkSize; if(endIdx > len) endIdx = len;
const slice = new DataView(view.buffer.slice(i,endIdx));
await writer.write(slice);
}
} else {
await writer.write(WebSerial.toDataView(message));
}
writer.releaseLock();
return true;
}
//new functionality
getSignals(port:SerialPort) {
return (port as any).getSignals()
}
setSignals(port:SerialPort, signals:any) {
return (port as any).setSignals(signals);
}
//get the readable/writable streams from the ports and set up optional transforms
createStream = (
options:SerialStreamProps
) => {
let stream:any = {
_id:options._id ? options._id : `stream${Math.floor(Math.random()*1000000000000000)}`,
info:options.port.getInfo(),
running:false,
...options
} as SerialStreamInfo;
if(options.port?.readable) {
if(options.transforms) {
stream.reader = WebSerial.setStreamTransforms(options.port.readable, options.transforms).getReader();
}
else {
stream.reader = options.port.readable.getReader();
}
}
// if(options.port?.writable) {
// stream.writer = options.port.writable.getWriter();
// }
this.streams[stream._id] = stream;
return stream as SerialStreamInfo;
}
readStream(
stream:SerialStreamInfo
) {
if(stream.reader && !stream.running) {
let reader = stream.reader;
if(stream.buffering) {
if(typeof stream.buffering !== 'object') stream.buffering = {};
if(!stream.buffering.buffer) { stream.buffering.buffer = []; }
if(!stream.buffering.searchBytes) stream.buffering.searchBytes = new Uint8Array([0x0D,0x0A]); // \r\n default newline
}
let readLoop = () => {
if(stream.port.readable && stream.running) {
reader.read().then((result:ReadableStreamReadResult<any>) => {
if(result.done) reader.releaseLock() //enables port closing
else {
if(stream.buffering) { //perform a boyer moore search to lock onto newlines or stop codes or whatever pattern buffer provided
stream.buffering.buffer.push(...result.value); //could be faster to concat typed arrays? else they require fixed sizes so not great for dynamic buffering, but maybe better to limit memory use (need to bench) //https://www.voidcanvas.com/javascript-array-evolution-performance/
const needle = stream.buffering.searchBytes
const haystack = stream.buffering.buffer;
const search = WebSerial.boyerMoore(needle);
const skip = search.byteLength;
let nextIndex = -1;
let used = stream.buffering.lockIdx ?? 0
for (var i = search(haystack); i !== -1; i = search(haystack, i + skip)) {
if(!stream.buffering.locked && !('lockIdx' in stream.buffering)) used = stream.buffering.lockIdx = i;
else {
nextIndex = i;
if(nextIndex >= 0) {
const len = nextIndex - used;
if(!stream.buffering.locked) {
const line = stream.buffering.buffer.splice(stream.buffering.lockIdx, len)
const data = new Uint8Array(line.slice(stream.buffering.searchBytes.length))
stream.ondata(data);
stream.buffering.locked = true;
}
else if(len > 0) {
const line = stream.buffering.buffer.splice(stream.buffering.lockIdx, len)
const data = new Uint8Array(line.slice(stream.buffering.searchBytes.length))
stream.ondata(new Uint8Array(data));
}
used = nextIndex;
}
}
}
} else stream.ondata(result.value);
setTimeout(()=> {
readLoop();
},stream.frequency);
}
}).catch((er:Error) => {
console.error(stream._id, ' Read error:', er)
if(er.message.includes('overrun') || er.message.includes('framing')) {
delete stream.reader;
this.reconnect(stream);
}
})
} else if (!stream.running && stream.port.readable) {
try{
reader.releaseLock();
} catch(er){
console.error(er);
}
}
}
stream.running = true;
readLoop(); //start reading
return stream;
} return undefined;
}
//use this on an active stream instead of writePort
async writeStream(stream:SerialStreamInfo|string, message:string | number | DataView | ArrayBufferLike, chunkSize?:number) {
if(typeof stream === 'string') stream = this.streams[stream];
if(stream.port.writable) {
let writer = stream.port.writable.getWriter();
if(chunkSize) {
const view = WebSerial.toDataView(message);
const len = view.buffer.byteLength;
for(let i = 0; i < len; i += chunkSize) {
let endIdx = i+chunkSize; if(endIdx > len) endIdx = len;
const slice = new DataView(view.buffer.slice(i,endIdx));
await writer.write(slice);
}
} else {
await writer.write(WebSerial.toDataView(message));
}
writer.releaseLock();
return true;
} return undefined;
}
closeStream(
stream:SerialStreamInfo|string,
onclose?:(info:SerialStreamInfo)=>void
):Promise<boolean> {
if(typeof stream === 'string') stream = this.streams[stream] as SerialStreamInfo;
stream.running = false;
return new Promise((res,rej) => {
if((stream as SerialStreamInfo).settings.beforedisconnect) {
(stream as SerialStreamInfo).settings.beforedisconnect(this,(stream as SerialStreamInfo).port);
}
setTimeout(async ()=>{
if((stream as SerialStreamInfo).port.readable && (stream as SerialStreamInfo).reader) {
try {
(stream as SerialStreamInfo).reader.releaseLock()
} catch(er) {console.error(er)}
if((stream as SerialStreamInfo).transforms) try {
await (stream as SerialStreamInfo).reader.cancel()
} catch(err) {console.error(err)}
}
// if((stream as StreamInfo).port.writable && (stream as StreamInfo).writer) {
// try {
// (stream as StreamInfo).writer.releaseLock();
// await (stream as StreamInfo).writer.close()
// } catch(er) {}
// }
try {
await (stream as SerialStreamInfo).port.close().then(()=>{
if(onclose) onclose(this.streams[(stream as SerialStreamInfo)._id])}
);
delete this.streams[(stream as SerialStreamInfo)._id];
res(true);
} catch(er) {
rej(er);
}
},
300
);
})
}
//reconnect to a stream using existing options
reconnect(
stream:SerialStreamInfo|string,
options?:SerialStreamProps
):Promise<SerialStreamInfo> {
if(typeof stream === 'string') stream = this.streams[stream];
return new Promise((res,rej) => {
if(typeof stream !== 'object') {
rej(undefined);
return;
}
let info = stream.port.getInfo();
this.closeStream(stream._id).then((closed) => {
setTimeout(() => {
this.getPorts().then((ports) => {
for(let i = 0; i < ports.length; i++) {
if(ports[i].getInfo().usbVendorId === info.usbVendorId && ports[i].getInfo().usbProductId === info.usbProductId) {
if(!options) options = stream as any;
else options._id = (stream as SerialStreamInfo)._id;
delete options.port;
this.openPort(ports[i], options.settings).then(() => {
const stream = this.createStream(
{
...options,
port:ports[i]
}
);
this.readStream(stream);
res(stream);
}).catch(rej)
}
}
}).catch(rej);
},100);
})
});
}
static setStreamTransforms(
stream:ReadableStream,
transforms:{
[key:string]:{
transform:TransformerTransformCallback<DataView, any>,
start?:TransformerStartCallback<any>,
flush?:TransformerFlushCallback<any>,
writableStrategy?:QueuingStrategy<DataView>,
readableStrategy?:QueuingStrategy<DataView>,
streamPipeOptions?:StreamPipeOptions
}|TransformStream
}
) {
let transform:TransformStream[] = [];
Object.keys(transforms).forEach((t:string) => {
let opt = (transforms as any)[t];
if(opt instanceof TransformStream) {
transform.push(opt)
} else {
if(!opt.start) opt.start = function start() {};
if(!opt.flush) opt.flush = function flush() {};
let transformer = new TransformStream(
{
start:opt.start,
transform:opt.transform,
flush:opt.flush
},
opt.writableStrategy,
opt.readableStrategy
);
transform.push(transformer);
}
});
let str = stream;
transform.forEach((transform) => {
str = str.pipeThrough(transform);
});
return str;
}
}