-
Notifications
You must be signed in to change notification settings - Fork 275
Expand file tree
/
Copy pathfromDevice.ts
More file actions
70 lines (64 loc) · 2.53 KB
/
fromDevice.ts
File metadata and controls
70 lines (64 loc) · 2.53 KB
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
import type { DeviceOutput } from "../../types.ts";
export const fromDeviceStream: () => TransformStream<Uint8Array, DeviceOutput> =
(
// onReleaseEvent: SimpleEventDispatcher<boolean>,
) => {
let byteBuffer = new Uint8Array([]);
const textDecoder = new TextDecoder();
return new TransformStream<Uint8Array, DeviceOutput>({
transform(raw: Uint8Array | ArrayBuffer, controller): void {
// onReleaseEvent.subscribe(() => {
// controller.terminate();
// });
let chunk = raw instanceof Uint8Array ? raw : new Uint8Array(raw);
byteBuffer = new Uint8Array([...byteBuffer, ...chunk]);
let processingExhausted = false;
while (byteBuffer.length !== 0 && !processingExhausted) {
const framingIndex = byteBuffer.indexOf(0x94);
const framingByte2 = byteBuffer[framingIndex + 1];
if (framingByte2 === 0xc3) {
if (byteBuffer.subarray(0, framingIndex).length) {
controller.enqueue({
type: "debug",
data: textDecoder.decode(byteBuffer.subarray(0, framingIndex)),
});
byteBuffer = byteBuffer.subarray(framingIndex);
}
const msb = byteBuffer[2];
const lsb = byteBuffer[3];
if (
msb !== undefined &&
lsb !== undefined &&
byteBuffer.length >= 4 + (msb << 8) + lsb
) {
const packet = byteBuffer.subarray(4, 4 + (msb << 8) + lsb);
const malformedDetectorIndex = packet.indexOf(0x94);
if (
malformedDetectorIndex !== -1 &&
packet[malformedDetectorIndex + 1] === 0xc3
) {
console.warn(
`⚠️ Malformed packet found, discarding: ${byteBuffer
.subarray(0, malformedDetectorIndex - 1)
.toString()}`,
);
byteBuffer = byteBuffer.subarray(malformedDetectorIndex);
} else {
byteBuffer = byteBuffer.subarray(3 + (msb << 8) + lsb + 1);
controller.enqueue({
type: "packet",
data: packet,
});
}
} else {
/** Only partioal message in buffer, wait for the rest */
processingExhausted = true;
}
} else {
/** Message not complete, only 1 byte in buffer */
processingExhausted = true;
}
}
},
});
};