-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathot-rcp-parser.ts
63 lines (44 loc) · 1.7 KB
/
ot-rcp-parser.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
import { Transform, type TransformCallback, type TransformOptions } from "node:stream";
import { HdlcReservedByte } from "../spinel/hdlc.js";
import { logger } from "../utils/logger.js";
const NS = "ot-rcp-driver:parser";
export class OTRCPParser extends Transform {
#buffer: Buffer;
public constructor(opts?: TransformOptions) {
super(opts);
this.#buffer = Buffer.alloc(0);
}
override _transform(chunk: Buffer, _encoding: BufferEncoding, cb: TransformCallback): void {
let data = Buffer.concat([this.#buffer, chunk]);
if (data[0] !== HdlcReservedByte.FLAG) {
// discard data before FLAG
data = data.subarray(data.indexOf(HdlcReservedByte.FLAG));
}
let position: number = data.indexOf(HdlcReservedByte.FLAG, 1);
while (position !== -1) {
const endPosition = position + 1;
// ignore repeated successive flags
if (position > 1) {
const frame = data.subarray(0, endPosition);
logger.debug(() => `<<< FRAME[${frame.toString("hex")}]`, NS);
this.push(frame);
// remove the frame from internal buffer (set below)
data = data.subarray(endPosition);
} else {
data = data.subarray(position);
}
position = data.indexOf(HdlcReservedByte.FLAG, 1);
}
this.#buffer = data;
cb();
}
/* v8 ignore start */
override _flush(cb: TransformCallback): void {
if (this.#buffer.byteLength > 0) {
this.push(this.#buffer);
this.#buffer = Buffer.alloc(0);
}
cb();
}
/* v8 ignore stop */
}