diff --git a/examples/bfb.ts b/examples/bfb.ts index e5f98fe..152c6bb 100644 --- a/examples/bfb.ts +++ b/examples/bfb.ts @@ -37,9 +37,6 @@ async function printValue(name: string, callback: () => Promise): Promi } } -port.on('error', (error) => console.error('Port error', error)); -port.on('close', () => console.error('Port close')); - try { await port.open(); console.log('Connecting...'); diff --git a/examples/bfc.ts b/examples/bfc.ts index 06e570e..8ec8d52 100644 --- a/examples/bfc.ts +++ b/examples/bfc.ts @@ -30,8 +30,6 @@ const port = await openPort(argv.port, 115200); await port.open(); const bus = new BFC(port); -port.on('error', (err) => console.error('Port error', err)); -port.on('close', () => console.error('Port close')); console.log('Connecting...'); await bus.connect(); diff --git a/examples/obex.ts b/examples/obex.ts index 7450280..6c74abd 100644 --- a/examples/obex.ts +++ b/examples/obex.ts @@ -53,8 +53,6 @@ const port = await openPort(argv.port, 115200); await port.open(); const obex = new OBEX(port); -port.on('error', (err) => console.error('Port error', err)); -port.on('close', () => console.error('Port close')); // A phone left in OBEX mode answers no AT commands until it is escaped or // power-cycled, so the session is ended on errors too diff --git a/examples/utils.ts b/examples/utils.ts index eccf7fd..3a5b3c5 100644 --- a/examples/utils.ts +++ b/examples/utils.ts @@ -1,21 +1,19 @@ import { AsyncSerialPort } from '@sie-js/serial'; -import { SerialPort } from "serialport"; -import { SerialPortStream } from '@serialport/stream'; -import { SocketBinding, SocketBindingInterface } from 'serialport-bindings-socket'; +import { autoDetect } from '@sie-js/node-serialport-bindings-cpp'; +import { SocketBinding } from 'serialport-bindings-socket'; export async function openPort(path: string, baudRate: number): Promise { if (path.match(/^(tcp|unix)/)) { - return new AsyncSerialPort(new SerialPortStream({ + return new AsyncSerialPort({ binding: SocketBinding, path, baudRate, - autoOpen: false - })); + }); } else { - return new AsyncSerialPort(new SerialPort({ + return new AsyncSerialPort({ + binding: autoDetect(), path, baudRate, - autoOpen: false - })); + }); } } diff --git a/package.json b/package.json index 8291c13..0569935 100644 --- a/package.json +++ b/package.json @@ -6,6 +6,16 @@ "types": "dist/src/index.d.ts", "exports": { ".": { + "browser": { + "source": "./src/index.ts", + "types": "./dist/src/index.d.ts", + "import": "./dist/src/index.js" + }, + "node": { + "source": "./src/index.node.ts", + "types": "./dist/src/index.node.d.ts", + "import": "./dist/src/index.node.js" + }, "source": "./src/index.ts", "types": "./dist/src/index.d.ts", "import": "./dist/src/index.js" @@ -43,20 +53,17 @@ "!dist/src/**/*.test.*" ], "dependencies": { + "@serialport/bindings-interface": "^1.2.2", + "@sie-js/node-serialport-bindings-cpp": "^0.0.2", "sprintf-js": "^1.1.3" }, "devDependencies": { - "@serialport/binding-mock": "^10.2.2", - "@serialport/bindings-interface": "^1.2.2", - "@serialport/stream": "^13.0.0", "@sie-js/creampie": "^1.0.3", - "@sie-js/node-serialport-bindings-cpp": "^0.0.2", "@types/debug": "^4.1.13", "@types/node": "^22.20.4", "@types/sprintf-js": "^1.1.4", "@types/throttle-debounce": "^5.0.2", "debug": "^4.4.3", - "serialport": "^13.0.0", "serialport-bindings-socket": "^1.0.4", "tsx": "^4.23.15", "typescript": "^7.0.2", @@ -64,7 +71,6 @@ }, "packageManager": "pnpm@12.7.0+sha512.9c56477e360068d6e9dca6a92efb4e46b3dc5a52fcebf3d84d78b9736c0ded589a561621a52f68219a7a39facc63cdc079c3226ef9c9d5f02b79f74e69a807b6", "peerDependencies": { - "@serialport/stream": "^13.0.0", "debug": "^4.4.3" } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index d9b7bc0..3b07119 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -162,9 +162,6 @@ settings: autoInstallPeers: true excludeLinksFromLockfile: false -overrides: - '@serialport/bindings-cpp': npm:@sie-js/node-serialport-bindings-cpp - patchedDependencies: '@serialport/bindings-interface': 23303df39a158977b3a3d4663860e68d1bfed71932bb1c9e14cb16f119e81329 @@ -172,25 +169,19 @@ importers: .: dependencies: + '@serialport/bindings-interface': + specifier: ^1.2.2 + version: 1.2.2(patch_hash=23303df39a158977b3a3d4663860e68d1bfed71932bb1c9e14cb16f119e81329) + '@sie-js/node-serialport-bindings-cpp': + specifier: ^0.0.2 + version: 0.0.2 sprintf-js: specifier: ^1.1.3 version: 1.1.3 devDependencies: - '@serialport/binding-mock': - specifier: ^10.2.2 - version: 10.2.2 - '@serialport/bindings-interface': - specifier: ^1.2.2 - version: 1.2.2(patch_hash=23303df39a158977b3a3d4663860e68d1bfed71932bb1c9e14cb16f119e81329) - '@serialport/stream': - specifier: ^13.0.0 - version: 13.0.0 '@sie-js/creampie': specifier: ^1.0.3 version: 1.0.3 - '@sie-js/node-serialport-bindings-cpp': - specifier: ^0.0.2 - version: 0.0.2 '@types/debug': specifier: ^4.1.13 version: 4.1.13 @@ -206,9 +197,6 @@ importers: debug: specifier: ^4.4.3 version: 4.4.3 - serialport: - specifier: ^13.0.0 - version: 13.0.0 serialport-bindings-socket: specifier: ^1.0.4 version: 1.0.4 @@ -492,58 +480,18 @@ packages: '@rolldown/pluginutils@1.0.1': resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} - '@serialport/binding-mock@10.2.2': - resolution: {integrity: sha512-HAFzGhk9OuFMpuor7aT5G1ChPgn5qSsklTFOTUX72Rl6p0xwcSVsRtG/xaGp6bxpN7fI9D/S8THLBWbBgS6ldw==} - engines: {node: '>=12.0.0'} - '@serialport/bindings-interface@1.2.2': resolution: {integrity: sha512-CJaUd5bLvtM9c5dmO9rPBHPXTa9R2UwpkJ0wdh9JCYcbrPWsKz+ErvR0hBLeo7NPeiFdjFO4sonRljiw4d2XiA==} engines: {node: ^12.22 || ^14.13 || >=16} - '@serialport/parser-byte-length@13.0.0': - resolution: {integrity: sha512-32yvqeTAqJzAEtX5zCrN1Mej56GJ5h/cVFsCDPbF9S1ZSC9FWjOqNAgtByseHfFTSTs/4ZBQZZcZBpolt8sUng==} - engines: {node: '>=20.0.0'} - - '@serialport/parser-cctalk@13.0.0': - resolution: {integrity: sha512-RErAe57g9gvnlieVYGIn1xymb1bzNXb2QtUQd14FpmbQQYlcrmuRnJwKa1BgTCujoCkhtaTtgHlbBWOxm8U2uA==} - engines: {node: '>=20.0.0'} - '@serialport/parser-delimiter@13.0.0': resolution: {integrity: sha512-Qqyb0FX1avs3XabQqNaZSivyVbl/yl0jywImp7ePvfZKLwx7jBZjvL+Hawt9wIG6tfq6zbFM24vzCCK7REMUig==} engines: {node: '>=20.0.0'} - '@serialport/parser-inter-byte-timeout@13.0.0': - resolution: {integrity: sha512-a0w0WecTW7bD2YHWrpTz1uyiWA2fDNym0kjmPeNSwZ2XCP+JbirZt31l43m2ey6qXItTYVuQBthm75sPVeHnGA==} - engines: {node: '>=20.0.0'} - - '@serialport/parser-packet-length@13.0.0': - resolution: {integrity: sha512-60ZDDIqYRi0Xs2SPZUo4Jr5LLIjtb+rvzPKMJCohrO6tAqSDponcNpcB1O4W21mKTxYjqInSz+eMrtk0LLfZIg==} - engines: {node: '>=8.6.0'} - '@serialport/parser-readline@13.0.0': resolution: {integrity: sha512-dov3zYoyf0dt1Sudd1q42VVYQ4WlliF0MYvAMA3MOyiU1IeG4hl0J6buBA2w4gl3DOCC05tGgLDN/3yIL81gsA==} engines: {node: '>=20.0.0'} - '@serialport/parser-ready@13.0.0': - resolution: {integrity: sha512-JNUQA+y2Rfs4bU+cGYNqOPnNMAcayhhW+XJZihSLQXOHcZsFnOa2F9YtMg9VXRWIcnHldHYtisp62Etjlw24bw==} - engines: {node: '>=20.0.0'} - - '@serialport/parser-regex@13.0.0': - resolution: {integrity: sha512-m7HpIf56G5XcuDdA3DB34Z0pJiwxNRakThEHjSa4mG05OnWYv0IG8l2oUyYfuGMowQWaVnQ+8r+brlPxGVH+eA==} - engines: {node: '>=20.0.0'} - - '@serialport/parser-slip-encoder@13.0.0': - resolution: {integrity: sha512-fUHZEExm6izJ7rg0A1yjXwu4sOzeBkPAjDZPfb+XQoqgtKAk+s+HfICiYn7N2QU9gyaeCO8VKgWwi+b/DowYOg==} - engines: {node: '>=20.0.0'} - - '@serialport/parser-spacepacket@13.0.0': - resolution: {integrity: sha512-DoXJ3mFYmyD8X/8931agJvrBPxqTaYDsPoly9/cwQSeh/q4EjQND9ySXBxpWz5WcpyCU4jOuusqCSAPsbB30Eg==} - engines: {node: '>=20.0.0'} - - '@serialport/stream@13.0.0': - resolution: {integrity: sha512-F7xLJKsjGo2WuEWMSEO1SimRcOA+WtWICsY13r0ahx8s2SecPQH06338g28OT7cW7uRXI7oEQAk62qh5gHJW3g==} - engines: {node: '>=20.0.0'} - '@sie-js/creampie@1.0.3': resolution: {integrity: sha512-NwJzIvCVXxbGuBlnNIqq3PVzmCznaow8LSWFDDfMnW9L8UhfSiNeZY7HBapc3PZzu8sD3aBDzwHCLwD+Mg7Tmg==} @@ -884,10 +832,6 @@ packages: serialport-bindings-socket@1.0.4: resolution: {integrity: sha512-IsUwMFOIa7iNrqJz5KHesv94HlRejIhjAdz6any9s/YIJ7imxLyYPok2AzCslKbg9cY0kXLWE7og4hSTiitktw==} - serialport@13.0.0: - resolution: {integrity: sha512-PHpnTd8isMGPfFTZNCzOZp9m4mAJSNWle9Jxu6BPTcWq7YXl5qN7tp8Sgn0h+WIGcD6JFz5QDgixC2s4VW7vzg==} - engines: {node: '>=20.0.0'} - source-map-js@1.2.1: resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} engines: {node: '>=0.10.0'} @@ -1150,44 +1094,14 @@ snapshots: '@rolldown/pluginutils@1.0.1': {} - '@serialport/binding-mock@10.2.2': - dependencies: - '@serialport/bindings-interface': 1.2.2(patch_hash=23303df39a158977b3a3d4663860e68d1bfed71932bb1c9e14cb16f119e81329) - debug: 4.4.3 - transitivePeerDependencies: - - supports-color - '@serialport/bindings-interface@1.2.2(patch_hash=23303df39a158977b3a3d4663860e68d1bfed71932bb1c9e14cb16f119e81329)': {} - '@serialport/parser-byte-length@13.0.0': {} - - '@serialport/parser-cctalk@13.0.0': {} - '@serialport/parser-delimiter@13.0.0': {} - '@serialport/parser-inter-byte-timeout@13.0.0': {} - - '@serialport/parser-packet-length@13.0.0': {} - '@serialport/parser-readline@13.0.0': dependencies: '@serialport/parser-delimiter': 13.0.0 - '@serialport/parser-ready@13.0.0': {} - - '@serialport/parser-regex@13.0.0': {} - - '@serialport/parser-slip-encoder@13.0.0': {} - - '@serialport/parser-spacepacket@13.0.0': {} - - '@serialport/stream@13.0.0': - dependencies: - '@serialport/bindings-interface': 1.2.2(patch_hash=23303df39a158977b3a3d4663860e68d1bfed71932bb1c9e14cb16f119e81329) - debug: 4.4.0 - transitivePeerDependencies: - - supports-color - '@sie-js/creampie@1.0.3': {} '@sie-js/node-serialport-bindings-cpp@0.0.2': @@ -1448,25 +1362,6 @@ snapshots: serialport-bindings-socket@1.0.4: {} - serialport@13.0.0: - dependencies: - '@serialport/binding-mock': 10.2.2 - '@serialport/bindings-cpp': '@sie-js/node-serialport-bindings-cpp@0.0.2' - '@serialport/parser-byte-length': 13.0.0 - '@serialport/parser-cctalk': 13.0.0 - '@serialport/parser-delimiter': 13.0.0 - '@serialport/parser-inter-byte-timeout': 13.0.0 - '@serialport/parser-packet-length': 13.0.0 - '@serialport/parser-readline': 13.0.0 - '@serialport/parser-ready': 13.0.0 - '@serialport/parser-regex': 13.0.0 - '@serialport/parser-slip-encoder': 13.0.0 - '@serialport/parser-spacepacket': 13.0.0 - '@serialport/stream': 13.0.0 - debug: 4.4.0 - transitivePeerDependencies: - - supports-color - source-map-js@1.2.1: {} sprintf-js@1.1.3: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 187b9c4..e92fa32 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -4,9 +4,6 @@ packages: patchedDependencies: '@serialport/bindings-interface': patches/@serialport__bindings-interface.patch -overrides: - '@serialport/bindings-cpp': 'npm:@sie-js/node-serialport-bindings-cpp' - allowBuilds: '@sie-js/node-serialport-bindings-cpp': true esbuild: true diff --git a/src/AsyncSerialPort.node.ts b/src/AsyncSerialPort.node.ts new file mode 100644 index 0000000..fb121fe --- /dev/null +++ b/src/AsyncSerialPort.node.ts @@ -0,0 +1,19 @@ +import { autoDetect } from '@sie-js/node-serialport-bindings-cpp'; +import type { BindingInterface } from '@serialport/bindings-interface'; +import { + AsyncSerialPort as BaseAsyncSerialPort, + type AsyncSerialPortOptions as BaseAsyncSerialPortOptions, +} from './AsyncSerialPort.js'; + +export { SerialReadTimeoutError } from './AsyncSerialPort.js'; + +export type AsyncSerialPortOptions = Omit & { + binding?: BindingInterface; +}; + +export class AsyncSerialPort extends BaseAsyncSerialPort { + constructor(options: AsyncSerialPortOptions) { + const { binding = autoDetect(), ...openOptions } = options; + super({ binding, ...openOptions }); + } +} diff --git a/src/AsyncSerialPort.test.ts b/src/AsyncSerialPort.test.ts new file mode 100644 index 0000000..1ad06b4 --- /dev/null +++ b/src/AsyncSerialPort.test.ts @@ -0,0 +1,408 @@ +import { BindingInterface, BindingPortInterface, OpenOptions, PortStatus, SetOptions, UpdateOptions } from '@serialport/bindings-interface'; +import { describe, expect, test } from 'vitest'; +import { AsyncSerialPort, SerialReadTimeoutError } from './AsyncSerialPort.js'; + +class TestPortBinding implements BindingPortInterface { + readonly openOptions: Required; + isOpen = true; + readCalls = 0; + writeCalls = 0; + drainCalls = 0; + maxParallelWrites = 0; + private activeWrites = 0; + private received = Buffer.alloc(0); + private pendingRead?: { + buffer: Buffer; + offset: number; + length: number; + resolve: (result: { buffer: Buffer; bytesRead: number }) => void; + reject: (error: Error) => void; + }; + private releaseWrite?: () => void; + + constructor(options: OpenOptions) { + this.openOptions = { + dataBits: 8, + lock: true, + stopBits: 1, + parity: 'none', + rtscts: false, + xon: false, + xoff: false, + xany: false, + hupcl: true, + ...options, + }; + } + + emit(data: Buffer): void { + this.received = Buffer.concat([this.received, data]); + this.completeRead(); + } + + unblockWrite(): void { + this.releaseWrite?.(); + this.releaseWrite = undefined; + } + + failRead(error: Error): void { + this.pendingRead?.reject(error); + this.pendingRead = undefined; + } + + async close(): Promise { + this.isOpen = false; + this.pendingRead?.reject(Object.assign(new Error('Port closed'), { canceled: true })); + this.pendingRead = undefined; + } + + read(buffer: Buffer, offset: number, length: number): Promise<{ buffer: Buffer; bytesRead: number }> { + this.readCalls++; + if (!this.isOpen) + return Promise.reject(new Error('Port is not open')); + if (this.pendingRead) + return Promise.reject(new Error('Overlapping read')); + return new Promise((resolve, reject) => { + this.pendingRead = { buffer, offset, length, resolve, reject }; + this.completeRead(); + }); + } + + async write(): Promise { + this.writeCalls++; + this.activeWrites++; + this.maxParallelWrites = Math.max(this.maxParallelWrites, this.activeWrites); + if (this.writeCalls == 1) + await new Promise((resolve) => this.releaseWrite = resolve); + this.activeWrites--; + } + + async update(options: UpdateOptions): Promise { + this.openOptions.baudRate = options.baudRate; + } + + async set(_options: SetOptions): Promise {} + + async get(): Promise { + return { cts: true, dsr: false, dcd: true }; + } + + async getBaudRate(): Promise<{ baudRate: number }> { + return { baudRate: this.openOptions.baudRate }; + } + + async flush(): Promise { + this.received = Buffer.alloc(0); + } + + async drain(): Promise { + this.drainCalls++; + } + + private completeRead(): void { + const read = this.pendingRead; + if (!read || !this.received.length) + return; + this.pendingRead = undefined; + const bytesRead = Math.min(read.length, this.received.length); + this.received.copy(read.buffer, read.offset, 0, bytesRead); + this.received = this.received.subarray(bytesRead); + read.resolve({ buffer: read.buffer, bytesRead }); + } +} + +async function openTestPort(): Promise<{ + port: AsyncSerialPort; + bindingPort: TestPortBinding; + bindingPorts: TestPortBinding[]; +}> { + let bindingPort: TestPortBinding | undefined; + const bindingPorts: TestPortBinding[] = []; + const binding: BindingInterface = { + list: async () => [], + open: async (options) => { + bindingPort = new TestPortBinding(options); + bindingPorts.push(bindingPort); + return bindingPort; + }, + }; + const port = new AsyncSerialPort({ binding, path: 'test', baudRate: 115200 }); + await port.open(); + return { port, bindingPort: bindingPort!, bindingPorts }; +} + +const nextTurn = () => new Promise((resolve) => setImmediate(resolve)); + +describe('AsyncSerialPort', () => { + test('exposes the open binding port', async () => { + const { port, bindingPort } = await openTestPort(); + expect(port.getBindingPort()).toBe(bindingPort); + await port.close(); + expect(() => port.getBindingPort()).toThrow('Port is not open'); + }); + + test('keeps unread bytes buffered while the read pump continues', async () => { + const { port, bindingPort } = await openTestPort(); + await nextTurn(); + expect(bindingPort.readCalls).toBe(1); + bindingPort.emit(Buffer.from([1, 2, 3])); + await nextTurn(); + expect(bindingPort.readCalls).toBe(2); + expect(await port.read(2, 100)).toEqual(Buffer.from([1, 2])); + expect(await port.readNextChunk()).toEqual(Buffer.from([3])); + await port.close(); + }); + + test('wraps the read buffer without overwriting unread bytes', async () => { + const { port, bindingPort } = await openTestPort(); + const initial = Buffer.alloc(64 * 1024, 0x11); + bindingPort.emit(initial); + await nextTurn(); + expect(bindingPort.readCalls).toBe(1); + + expect(await port.read(48 * 1024)).toEqual(initial.subarray(0, 48 * 1024)); + await nextTurn(); + expect(bindingPort.readCalls).toBe(2); + + const wrapped = Buffer.alloc(32 * 1024, 0x22); + bindingPort.emit(wrapped); + expect(await port.read(48 * 1024)).toEqual(Buffer.concat([ + initial.subarray(48 * 1024), + wrapped, + ])); + await port.close(); + }); + + test('preserves a native read that completes after a timeout', async () => { + const { port, bindingPort } = await openTestPort(); + const first = port.read(2, 20); + await nextTurn(); + bindingPort.emit(Buffer.from([1])); + expect(await first).toEqual(Buffer.from([1])); + + const late = port.read(1, 100); + bindingPort.emit(Buffer.from([2])); + expect(await late).toEqual(Buffer.from([2])); + await port.close(); + }); + + test('reads directly into a caller buffer at an offset', async () => { + const { port, bindingPort } = await openTestPort(); + bindingPort.emit(Buffer.from([1, 2, 3])); + await nextTurn(); + + const target = Buffer.alloc(5, 0xFF); + expect(await port.readInto(target, 1, 3)).toBe(3); + expect(target).toEqual(Buffer.from([0xFF, 1, 2, 3, 0xFF])); + await port.close(); + }); + + test('returns the number of bytes written by readInto on timeout', async () => { + const { port, bindingPort } = await openTestPort(); + const target = Buffer.alloc(4, 0xFF); + const read = port.readInto(target, 1, 3, 20); + bindingPort.emit(Buffer.from([1, 2])); + + expect(await read).toBe(2); + expect(target).toEqual(Buffer.from([0xFF, 1, 2, 0xFF])); + await port.close(); + }); + + test('reads an exact number of bytes across binding reads', async () => { + const { port, bindingPort } = await openTestPort(); + const read = port.readExact(3); + bindingPort.emit(Buffer.from([1])); + await nextTurn(); + bindingPort.emit(Buffer.from([2, 3])); + + expect(await read).toEqual(Buffer.from([1, 2, 3])); + await port.close(); + }); + + test('throws when readExactInto times out before filling the buffer', async () => { + const { port, bindingPort } = await openTestPort(); + const target = Buffer.alloc(4, 0xFF); + const read = port.readExactInto(target, 1, 3, 20); + bindingPort.emit(Buffer.from([1, 2])); + + await expect(read).rejects.toBeInstanceOf(SerialReadTimeoutError); + await expect(read).rejects.toThrow('Serial receive timeout.'); + expect(target).toEqual(Buffer.from([0xFF, 1, 2, 0xFF])); + await port.close(); + }); + + test('readExactInto throws the abort reason', async () => { + const { port } = await openTestPort(); + const controller = new AbortController(); + const reason = new Error('Cancelled'); + const read = port.readExactInto(Buffer.alloc(1), 0, 1, 0, controller.signal); + controller.abort(reason); + + await expect(read).rejects.toBe(reason); + await port.close(); + }); + + test('aborts a read without consuming subsequent data', async () => { + const { port, bindingPort } = await openTestPort(); + const controller = new AbortController(); + const abandoned = port.read(1, 0, controller.signal); + await nextTurn(); + controller.abort(); + expect(await abandoned).toBeUndefined(); + + const next = port.read(1); + bindingPort.emit(Buffer.from([0x55])); + expect(await next).toEqual(Buffer.from([0x55])); + await port.close(); + }); + + test('returns bytes already read when readInto is aborted', async () => { + const { port, bindingPort } = await openTestPort(); + const controller = new AbortController(); + const target = Buffer.alloc(2); + const read = port.readInto(target, 0, 2, 0, controller.signal); + bindingPort.emit(Buffer.from([0x55])); + await nextTurn(); + controller.abort(); + + expect(await read).toBe(1); + expect(target[0]).toBe(0x55); + await port.close(); + }); + + test('hands an aborted chunk read to the next reader', async () => { + const { port, bindingPort } = await openTestPort(); + const controller = new AbortController(); + const abandoned = port.readNextChunk(controller.signal); + await nextTurn(); + controller.abort(); + expect(await abandoned).toBeUndefined(); + + const next = port.readNextChunk(); + bindingPort.emit(Buffer.from([0x55])); + expect(await next).toEqual(Buffer.from([0x55])); + await port.close(); + }); + + test('does not consume buffered data after a chunk read is aborted', async () => { + const { port, bindingPort } = await openTestPort(); + const controller = new AbortController(); + const abandoned = port.readNextChunk(controller.signal); + await nextTurn(); + bindingPort.emit(Buffer.from([0x55])); + queueMicrotask(() => controller.abort()); + + expect(await abandoned).toBeUndefined(); + expect(await port.readNextChunk()).toEqual(Buffer.from([0x55])); + await port.close(); + }); + + test('does not return buffered data after the binding read fails', async () => { + const { port, bindingPort } = await openTestPort(); + bindingPort.emit(Buffer.from([0x55])); + await nextTurn(); + bindingPort.failRead(new Error('Read failed')); + await nextTurn(); + + await expect(port.readNextChunk()).rejects.toThrow('Read failed'); + }); + + test('keeps queued reads ordered when data is already buffered', async () => { + const { port, bindingPort } = await openTestPort(); + const first = port.read(2); + bindingPort.emit(Buffer.from([1])); + await nextTurn(); + + const second = port.readByte(); + bindingPort.emit(Buffer.from([2, 3])); + expect(await first).toEqual(Buffer.from([1, 2])); + expect(await second).toBe(3); + await port.close(); + }); + + test('serializes writes for bindings that reject overlap', async () => { + const { port, bindingPort } = await openTestPort(); + const first = port.write(Buffer.from([1])); + const second = port.write(Buffer.from([2])); + await nextTurn(); + expect(bindingPort.writeCalls).toBe(1); + bindingPort.unblockWrite(); + await Promise.all([first, second]); + expect(bindingPort.writeCalls).toBe(2); + expect(bindingPort.maxParallelWrites).toBe(1); + await port.close(); + }); + + test('does not send a queued write through a reopened port', async () => { + const { port, bindingPort, bindingPorts } = await openTestPort(); + const active = port.write(Buffer.from([1])); + const stale = port.write(Buffer.from([2])); + await nextTurn(); + await port.close(); + await port.open(); + + bindingPort.unblockWrite(); + await active; + await expect(stale).rejects.toThrow('Port is not open'); + expect(bindingPorts[1].writeCalls).toBe(0); + await port.close(); + }); + + test('drains writes queued before it', async () => { + const { port, bindingPort } = await openTestPort(); + const write = port.write(Buffer.from([1])); + const drain = port.drain(); + await nextTurn(); + expect(bindingPort.drainCalls).toBe(0); + + bindingPort.unblockWrite(); + await Promise.all([write, drain]); + expect(bindingPort.drainCalls).toBe(1); + await port.close(); + }); + + test('flushes the binding and discards buffered input', async () => { + const { port, bindingPort } = await openTestPort(); + bindingPort.emit(Buffer.from([1, 2])); + await nextTurn(); + await port.flush(); + expect(await port.read(1, 20)).toBeUndefined(); + + bindingPort.emit(Buffer.from([3])); + expect(await port.readByte(100)).toBe(3); + await port.close(); + }); + + test('discards a requested number of bytes without allocating a result', async () => { + const { port, bindingPort } = await openTestPort(); + bindingPort.emit(Buffer.from([1, 2])); + const discard = port.discard(3, 100); + bindingPort.emit(Buffer.from([3, 4])); + + expect(await discard).toBe(3); + expect(await port.readByte(100)).toBe(4); + await port.close(); + }); + + test('returns the number of bytes discarded on timeout', async () => { + const { port, bindingPort } = await openTestPort(); + const discard = port.discard(3, 20); + bindingPort.emit(Buffer.from([1, 2])); + + expect(await discard).toBe(2); + await port.close(); + }); + + test('discards buffered and incoming data until the port is idle', async () => { + const { port, bindingPort } = await openTestPort(); + bindingPort.emit(Buffer.from([1])); + const discard = port.discardUntilIdle(20, 200); + setTimeout(() => bindingPort.emit(Buffer.from([2, 3])), 10); + await discard; + + expect(await port.read(1, 20)).toBeUndefined(); + bindingPort.emit(Buffer.from([4])); + expect(await port.readByte(100)).toBe(4); + await port.close(); + }); +}); diff --git a/src/AsyncSerialPort.ts b/src/AsyncSerialPort.ts index 8a5d947..e76eba5 100644 --- a/src/AsyncSerialPort.ts +++ b/src/AsyncSerialPort.ts @@ -1,196 +1,504 @@ -import { SerialPortStream } from "@serialport/stream"; -import { BindingInterface, SetOptions } from "@serialport/bindings-interface"; +import type { + BindingInterface, + BindingPortInterface, + OpenOptions, + PortStatus, + SetOptions, + UpdateOptions, +} from '@serialport/bindings-interface'; -type PortSignals = { - cts: boolean - dsr: boolean - dcd: boolean -} | undefined; +const READ_BUFFER_SIZE = 64 * 1024; -export class AsyncSerialPort { - private readonly port: SerialPortStream; +export type AsyncSerialPortOptions = OpenOptions & { + binding: BindingInterface; +}; - constructor(port: SerialPortStream) { - this.port = port; +export class SerialReadTimeoutError extends Error { + constructor() { + super('Serial receive timeout.'); + this.name = 'SerialReadTimeoutError'; } +} - on(event: string | symbol, listener: (...args: any[]) => void) { - return this.port.on(event, listener); - } +export class AsyncSerialPort { + private readonly binding: BindingInterface; + private readonly openOptions: OpenOptions; + private port?: BindingPortInterface; + private opening?: Promise; + private readError?: unknown; + private readonly readBuffer = Buffer.allocUnsafe(READ_BUFFER_SIZE); + private readBufferStart = 0; + private readBufferLength = 0; + private readonly dataWaiters = new Set<() => void>(); + private readonly spaceWaiters = new Set<() => void>(); + private readQueueTail: Promise = Promise.resolve(); + private pendingReadCount = 0; + private writeQueueTail: Promise = Promise.resolve(); - off(event: string | symbol, listener: (...args: any[]) => void) { - return this.port.off(event, listener); + constructor(options: AsyncSerialPortOptions) { + const { binding, ...openOptions } = options; + this.binding = binding; + this.openOptions = openOptions; } get isOpen(): boolean { - return this.port.isOpen; + return this.port?.isOpen ?? false; } get baudRate(): number { - return this.port.baudRate; + return this.openOptions.baudRate; } - async open(): Promise { - if (this.port.isOpen) - return; - return new Promise((resolve, reject) => { - this.port.open((err) => { - if (err) { - reject(err); - } else { - resolve(); - } - }); + getBindingPort(): BindingPortInterface { + return this.getOpenPort(); + } + + open(): Promise { + if (this.isOpen) + return Promise.resolve(); + if (this.opening) + return this.opening; + + const opening = this.binding.open(this.openOptions).then((port) => { + this.port = port; + this.readError = undefined; + this.readBufferStart = 0; + this.readBufferLength = 0; + void this.pump(port); }); + this.opening = opening; + const clearOpening = () => { + if (this.opening == opening) + this.opening = undefined; + }; + void opening.then(clearOpening, clearOpening); + return opening; } async close(): Promise { - if (!this.port.isOpen) + if (this.opening) + await this.opening; + const port = this.port; + if (!port) return; - return new Promise((resolve, reject) => { - this.port.close((err) => { - if (err) { - reject(err); - } else { - resolve(); - } - }); + + this.port = undefined; + this.readError = new Error('Port is not open'); + this.readBufferStart = 0; + this.readBufferLength = 0; + this.notify(this.dataWaiters); + this.notify(this.spaceWaiters); + if (port.isOpen) + await port.close(); + } + + readByte(timeout = 0, signal?: AbortSignal): Promise { + if (signal?.aborted) + return Promise.resolve(-1); + if (!this.pendingReadCount && !this.readError && this.port?.isOpen && this.readBufferLength) + return Promise.resolve(this.takeBufferedByte()); + return this.queueRead(() => this.readByteOrTimeout(timeout, signal)); + } + + read(size: number, timeout = 0, signal?: AbortSignal): Promise { + if (!Number.isSafeInteger(size) || size < 0) + return Promise.reject(new RangeError('Read size must be a non-negative safe integer.')); + if (signal?.aborted) + return Promise.resolve(undefined); + if (!this.pendingReadCount && !this.readError && this.port?.isOpen && this.readBufferLength >= size) + return Promise.resolve(this.takeBuffered(size)); + return this.queueRead(() => this.readOrTimeout(size, timeout, signal)); + } + + readExact(size: number, timeout = 0, signal?: AbortSignal): Promise { + if (!Number.isSafeInteger(size) || size < 0) + return Promise.reject(new RangeError('Read size must be a non-negative safe integer.')); + if (signal?.aborted) + return Promise.reject(signal.reason); + if (!this.pendingReadCount && !this.readError && this.port?.isOpen && this.readBufferLength >= size) + return Promise.resolve(this.takeBuffered(size)); + return this.queueRead(async () => { + const result = Buffer.allocUnsafe(size); + await this.readExactIntoOrThrow(result, 0, size, timeout, signal); + return result; }); } - async readByte(timeout = 0): Promise { - const byte = await this.read(1, timeout); - return byte == null ? -1 : byte[0]; + readInto(buffer: Buffer, offset = 0, length?: number, timeout = 0, signal?: AbortSignal): Promise { + if (!Buffer.isBuffer(buffer)) + return Promise.reject(new TypeError('Read buffer must be a Buffer.')); + if (!Number.isSafeInteger(offset) || offset < 0 || offset > buffer.length) + return Promise.reject(new RangeError('Read offset is outside the buffer.')); + length ??= buffer.length - offset; + if (!Number.isSafeInteger(length) || length < 0 || length > buffer.length - offset) + return Promise.reject(new RangeError('Read length is outside the buffer.')); + if (!length) + return Promise.resolve(0); + if (signal?.aborted) + return Promise.resolve(0); + if (!this.pendingReadCount && !this.readError && this.port?.isOpen && this.readBufferLength >= length) { + this.consumeBuffered(buffer, offset, length); + return Promise.resolve(length); + } + return this.queueRead(() => this.readIntoOrTimeout(buffer, offset, length, timeout, signal)); } - async read(size: number, timeout?: number): Promise { - if (!this.port.isOpen) - throw new Error("Port is not open"); + readExactInto(buffer: Buffer, offset = 0, length?: number, timeout = 0, signal?: AbortSignal): Promise { + if (!Buffer.isBuffer(buffer)) + return Promise.reject(new TypeError('Read buffer must be a Buffer.')); + if (!Number.isSafeInteger(offset) || offset < 0 || offset > buffer.length) + return Promise.reject(new RangeError('Read offset is outside the buffer.')); + length ??= buffer.length - offset; + if (!Number.isSafeInteger(length) || length < 0 || length > buffer.length - offset) + return Promise.reject(new RangeError('Read length is outside the buffer.')); + if (signal?.aborted) + return Promise.reject(signal.reason); + if (!this.pendingReadCount && !this.readError && this.port?.isOpen && this.readBufferLength >= length) { + this.consumeBuffered(buffer, offset, length); + return Promise.resolve(); + } + return this.queueRead(() => this.readExactIntoOrThrow(buffer, offset, length, timeout, signal)); + } - if (this.port.readableLength >= size) - return this.port.read(size); + discard(size: number, timeout = 0, signal?: AbortSignal): Promise { + if (!Number.isSafeInteger(size) || size < 0) + return Promise.reject(new RangeError('Discard size must be a non-negative safe integer.')); + if (!size || signal?.aborted) + return Promise.resolve(0); + if (!this.pendingReadCount && !this.readError && this.port?.isOpen && this.readBufferLength >= size) { + this.discardBuffered(size); + return Promise.resolve(size); + } + return this.queueRead(() => this.discardOrTimeout(size, timeout, signal)); + } - return new Promise((resolve, reject) => { - let result: Buffer | undefined; - let bytesRead = 0; - let timeoutTimer: NodeJS.Timeout | undefined; - - const removeListeners = () => { - this.port.removeListener("close", onClose); - this.port.removeListener("end", onEnd); - this.port.removeListener("error", onError); - this.port.removeListener("readable", onReadable); - - if (timeoutTimer) { - clearTimeout(timeoutTimer); - timeoutTimer = undefined; - } - }; - const onTimeout = () => { - removeListeners(); - resolve(result?.subarray(0, bytesRead)); - }; - const onClose = () => { - removeListeners(); - resolve(result?.subarray(0, bytesRead)); - }; - const onEnd = () => { - removeListeners(); - resolve(result?.subarray(0, bytesRead)); - }; - const onError = (err: Error) => { - removeListeners(); - reject(err); - }; - const onReadable = () => { - const bytesToRead = Math.min(size - bytesRead, this.port.readableLength); - if (bytesToRead == 0) - return; - - const chunk = this.port.read(bytesToRead); - if (!result) - result = Buffer.alloc(size); - chunk.copy(result, bytesRead); - bytesRead += chunk.length - - if (bytesRead == size) { - removeListeners(); - resolve(result?.subarray(0, bytesRead)); - } - }; - - if (this.port.readableLength > 0) - onReadable(); - if (bytesRead == size) - return; - - this.port.on("close", onClose); - this.port.on("end", onEnd); - this.port.on("error", onError); - this.port.on("readable", onReadable); - - if (timeout) - timeoutTimer = setTimeout(onTimeout, timeout); + readNextChunk(abortSignal?: AbortSignal): Promise { + if (abortSignal?.aborted) + return Promise.resolve(undefined); + if (!this.pendingReadCount && !this.readError && this.port?.isOpen && this.readBufferLength) + return Promise.resolve(this.takeBuffered(this.readBufferLength)); + return this.queueRead(async () => { + if (abortSignal?.aborted) + return undefined; + this.throwReadError(); + while (!this.readBufferLength) { + if (!await this.wait(this.dataWaiters, 0, abortSignal)) + return undefined; + this.throwReadError(); + } + if (abortSignal?.aborted) + return undefined; + return this.takeBuffered(this.readBufferLength); }); } - async write(data: any): Promise { - return new Promise((resolve, reject) => { - if (!this.port.isOpen) - throw new Error("Port is not open"); - this.port.write(data, (err) => { - if (err) { - reject(err); - } else { - resolve(); - } - }); - }); + discardUntilIdle( + idleTimeout: number, + maxTimeout = Math.max(3000, idleTimeout * 10), + signal?: AbortSignal, + ): Promise { + if (!Number.isSafeInteger(idleTimeout) || idleTimeout < 1) + return Promise.reject(new RangeError('Idle timeout must be a positive safe integer.')); + if (!Number.isSafeInteger(maxTimeout) || maxTimeout < idleTimeout) + return Promise.reject(new RangeError('Maximum timeout must be at least the idle timeout.')); + return this.queueRead(() => this.discardUntilIdleInternal(idleTimeout, maxTimeout, signal)); } - async getSignals(): Promise { - return new Promise((resolve, reject) => { - if (!this.port.isOpen) - reject(new Error("Port is not open")); - this.port.get((err, signals) => { - if (err) { - reject(err); - } else { - resolve(signals); - } - }); + write(data: Buffer | string): Promise { + let port: BindingPortInterface; + try { + port = this.getOpenPort(); + } catch (error) { + return Promise.reject(error); + } + const buffer = Buffer.isBuffer(data) ? data : Buffer.from(data); + const write = this.writeQueueTail.then(async () => { + if (this.port != port || !port.isOpen) + throw new Error('Port is not open'); + try { + await port.write(buffer); + } catch (error) { + await this.disconnect(port, error); + throw error; + } }); + this.writeQueueTail = write.catch(() => {}); + return write; + } + + async drain(): Promise { + const port = this.getOpenPort(); + const writes = this.writeQueueTail; + await writes; + if (this.port != port || !port.isOpen) + throw new Error('Port is not open'); + try { + await port.drain(); + } catch (error) { + await this.disconnect(port, error); + throw error; + } + } + + async flush(): Promise { + const port = this.getOpenPort(); + const writes = this.writeQueueTail; + await writes; + if (this.port != port || !port.isOpen) + throw new Error('Port is not open'); + try { + await port.flush(); + } catch (error) { + await this.disconnect(port, error); + throw error; + } + + this.discardBuffered(this.readBufferLength); + } + + async getSignals(): Promise { + return this.getOpenPort().get(); } async setSignals(signals: SetOptions): Promise { - return new Promise((resolve, reject) => { - if (!this.port.isOpen) - reject(new Error("Port is not open")); - this.port.set(signals, (err) => { - if (err) { - reject(err); - } else { - resolve(); + await this.getOpenPort().set(signals); + } + + async update(settings: UpdateOptions): Promise { + await this.getOpenPort().update(settings); + this.openOptions.baudRate = settings.baudRate; + } + + private async pump(port: BindingPortInterface): Promise { + try { + while (this.port == port && port.isOpen) { + while (this.readBufferLength == this.readBuffer.length) { + if (this.port != port) + return; + await this.wait(this.spaceWaiters); } - }); + + const writeOffset = (this.readBufferStart + this.readBufferLength) % this.readBuffer.length; + const writeLength = Math.min( + this.readBuffer.length - this.readBufferLength, + this.readBuffer.length - writeOffset, + ); + const { bytesRead } = await port.read(this.readBuffer, writeOffset, writeLength); + if (!bytesRead) + throw new Error('Serial port closed.'); + if (this.port != port) + return; + this.readBufferLength += bytesRead; + this.notify(this.dataWaiters); + } + } catch (error) { + await this.disconnect(port, error); + } + } + + private queueRead(action: () => Promise): Promise { + this.pendingReadCount++; + const result = this.readQueueTail.then(action); + this.readQueueTail = result.then( + () => { this.pendingReadCount--; }, + () => { this.pendingReadCount--; }, + ); + return result; + } + + private async readByteOrTimeout(timeout: number, signal?: AbortSignal): Promise { + if (signal?.aborted) + return -1; + this.throwReadError(); + if (this.readBufferLength) + return this.takeBufferedByte(); + if (!await this.wait(this.dataWaiters, timeout, signal) || signal?.aborted) + return -1; + this.throwReadError(); + return this.readBufferLength ? this.takeBufferedByte() : -1; + } + + private async readOrTimeout(size: number, timeout: number, signal?: AbortSignal): Promise { + if (size == 0) + return Buffer.alloc(0); + + const result = Buffer.allocUnsafe(size); + const bytesRead = await this.readIntoOrTimeout(result, 0, size, timeout, signal); + return bytesRead ? result.subarray(0, bytesRead) : undefined; + } + + private async readIntoOrTimeout( + target: Buffer, + targetOffset: number, + size: number, + timeout: number, + signal?: AbortSignal, + ): Promise { + this.throwReadError(); + + let bytesRead = 0; + const deadline = timeout ? Date.now() + timeout : 0; + while (bytesRead < size) { + if (signal?.aborted) + break; + if (this.readBufferLength) { + const chunkSize = Math.min(size - bytesRead, this.readBufferLength); + this.consumeBuffered(target, targetOffset + bytesRead, chunkSize); + bytesRead += chunkSize; + continue; + } + + this.throwReadError(); + if (deadline && Date.now() >= deadline) + break; + const remainingTime = deadline ? Math.max(1, deadline - Date.now()) : 0; + if (!await this.wait(this.dataWaiters, remainingTime, signal)) + break; + } + + return bytesRead; + } + + private async readExactIntoOrThrow( + target: Buffer, + targetOffset: number, + size: number, + timeout: number, + signal?: AbortSignal, + ): Promise { + const bytesRead = await this.readIntoOrTimeout(target, targetOffset, size, timeout, signal); + signal?.throwIfAborted(); + if (bytesRead != size) + throw new SerialReadTimeoutError(); + } + + private async discardOrTimeout(size: number, timeout: number, signal?: AbortSignal): Promise { + this.throwReadError(); + + let bytesDiscarded = 0; + const deadline = timeout ? Date.now() + timeout : 0; + while (bytesDiscarded < size) { + if (signal?.aborted) + break; + if (this.readBufferLength) { + const chunkSize = Math.min(size - bytesDiscarded, this.readBufferLength); + this.discardBuffered(chunkSize); + bytesDiscarded += chunkSize; + continue; + } + + this.throwReadError(); + if (deadline && Date.now() >= deadline) + break; + const remainingTime = deadline ? Math.max(1, deadline - Date.now()) : 0; + if (!await this.wait(this.dataWaiters, remainingTime, signal)) + break; + } + + return bytesDiscarded; + } + + private async discardUntilIdleInternal(idleTimeout: number, maxTimeout: number, signal?: AbortSignal): Promise { + const deadline = Date.now() + maxTimeout; + while (true) { + signal?.throwIfAborted(); + this.throwReadError(); + this.discardBuffered(this.readBufferLength); + + const remainingTime = deadline - Date.now(); + if (remainingTime <= 0) + return; + if (!await this.wait(this.dataWaiters, Math.min(idleTimeout, remainingTime), signal)) { + signal?.throwIfAborted(); + return; + } + } + } + + private takeBuffered(size: number): Buffer { + const result = Buffer.allocUnsafe(size); + this.consumeBuffered(result, 0, size); + return result; + } + + private takeBufferedByte(): number { + const byte = this.readBuffer[this.readBufferStart]; + this.readBufferStart++; + if (this.readBufferStart == this.readBuffer.length) + this.readBufferStart = 0; + this.readBufferLength--; + this.notify(this.spaceWaiters); + return byte; + } + + private consumeBuffered(target: Buffer, targetOffset: number, size: number): void { + const firstSize = Math.min(size, this.readBuffer.length - this.readBufferStart); + this.readBuffer.copy(target, targetOffset, this.readBufferStart, this.readBufferStart + firstSize); + if (firstSize < size) + this.readBuffer.copy(target, targetOffset + firstSize, 0, size - firstSize); + this.readBufferStart = (this.readBufferStart + size) % this.readBuffer.length; + this.readBufferLength -= size; + this.notify(this.spaceWaiters); + } + + private discardBuffered(size: number): void { + this.readBufferStart = (this.readBufferStart + size) % this.readBuffer.length; + this.readBufferLength -= size; + this.notify(this.spaceWaiters); + } + + private wait(waiters: Set<() => void>, timeout = 0, signal?: AbortSignal): Promise { + if (signal?.aborted) + return Promise.resolve(false); + + return new Promise((resolve) => { + let timer: ReturnType | undefined; + const finish = (ready: boolean) => { + waiters.delete(onReady); + if (timer) + clearTimeout(timer); + if (signal) + signal.removeEventListener('abort', onAbort); + resolve(ready); + }; + const onReady = () => finish(true); + const onAbort = () => finish(false); + waiters.add(onReady); + if (timeout) + timer = setTimeout(() => finish(false), timeout); + if (signal) + signal.addEventListener('abort', onAbort, { once: true }); }); } - update(settings: { baudRate: number }): Promise { - return new Promise((resolve, reject) => { - if (!this.port.isOpen) - reject(new Error("Port is not open")); - this.port.update(settings, (err) => { - if (err) { - reject(err); - } else { - resolve(); - } - }); - }); + private notify(waiters: Set<() => void>): void { + for (const wake of waiters) + wake(); } - getParentPort(): SerialPortStream { + private throwReadError(): void { + if (this.readError) + throw this.readError; + this.getOpenPort(); + } + + private getOpenPort(): BindingPortInterface { + if (!this.port?.isOpen) + throw new Error('Port is not open'); return this.port; } + + private async disconnect(port: BindingPortInterface, error: unknown): Promise { + if (this.port != port) + return; + this.port = undefined; + this.readError = error; + this.notify(this.dataWaiters); + this.notify(this.spaceWaiters); + if (port.isOpen) { + try { + await port.close(); + } catch {} + } + } } diff --git a/src/at/AtChannel.ts b/src/at/AtChannel.ts index b169c17..790d77d 100644 --- a/src/at/AtChannel.ts +++ b/src/at/AtChannel.ts @@ -26,8 +26,10 @@ export type AtUnsolicitedHandler = { export class AtChannel extends BaseSerialProtocol { private buffer = Buffer.alloc(0); + private lastDataAt = 0; private unsolicitedHandlers: AtUnsolicitedHandler[] = []; private paused = true; + private receiveController?: AbortController; private currentCommand: { lines: string[]; prefix: string; @@ -39,14 +41,12 @@ export class AtChannel extends BaseSerialProtocol { resolve: (value: AtCommandResponse) => void; reject: (e: Error) => void; } | undefined; - private readonly handleSerialDataCallback = this.handleSerialData.bind(this); - private readonly handleSerialCloseCallback = this.handleSerialClose.bind(this); - private handleSerialClose() { this.stop(); } private handleSerialData(data: Buffer) { + this.lastDataAt = Date.now(); const cmd = this.currentCommand; if (cmd && cmd.type == 'BINARY') { const chunkSize = Math.min(data.length, cmd.buffer!.length - cmd.binaryOffset); @@ -174,8 +174,9 @@ export class AtChannel extends BaseSerialProtocol { start() { if (this.paused) { this.paused = false; - this.port.on('data', this.handleSerialDataCallback); - this.port.on('close', this.handleSerialCloseCallback); + const controller = new AbortController(); + this.receiveController = controller; + void this.receive(controller); } } @@ -191,8 +192,30 @@ export class AtChannel extends BaseSerialProtocol { private pause() { this.paused = true; - this.port.off('data', this.handleSerialDataCallback); - this.port.off('close', this.handleSerialCloseCallback); + this.receiveController?.abort(); + this.receiveController = undefined; + } + + private async receive(controller: AbortController): Promise { + try { + while (!controller.signal.aborted) { + const data = await this.port.readNextChunk(controller.signal); + if (controller.signal.aborted) + break; + if (data) + this.handleSerialData(data); + } + } catch { + if (!controller.signal.aborted && this.receiveController == controller) + this.handleSerialClose(); + } + } + + async drain(quiet: number, maxTime = 10 * quiet): Promise { + const deadline = Date.now() + maxTime; + this.lastDataAt = Date.now(); + while (Date.now() - this.lastDataAt < quiet && Date.now() < deadline) + await delay(quiet - (Date.now() - this.lastDataAt)); } private async sendRawCommand(type: AtCommandType, cmd: string, prefix: string, { timeout, binarySize }: AtCommandOptions): Promise { @@ -289,14 +312,14 @@ export class AtChannel extends BaseSerialProtocol { async connectPPP(cmd: string, timeout = 180 * 1000): Promise { const ppp = new PPP(this.port); - ppp.start(); const response = await this.sendRawCommand('PPP', cmd, '', { timeout }); if (!response.success) { - ppp.stop(); throw new Error(`Unable to enter PPP mode: ${response.status}`); } + const initialData = this.buffer; this.buffer = Buffer.alloc(0); + ppp.start(initialData); return ppp; } diff --git a/src/bfb/BFB.ts b/src/bfb/BFB.ts index b94ae3f..34aacac 100644 --- a/src/bfb/BFB.ts +++ b/src/bfb/BFB.ts @@ -427,13 +427,11 @@ export class BfbCommandTimeoutError extends Error { export class BFB extends BaseSerialProtocol { private mode = BfbTransportMode.NONE; - private buffer = Buffer.alloc(0); private frames: BfbFrame[] = []; private frameQueueChannel?: number; private frameReceiver?: BfbFrameReceiver; private readonly frameHandlers = new Map(); - private readonly handleSerialDataCallback = this.handleSerialData.bind(this); - private readonly handleSerialCloseCallback = this.handleSerialClose.bind(this); + private receiveController?: AbortController; private readonly atc = new AtChannel(this.port); private setTransportMode(mode: BfbTransportMode): void { @@ -444,10 +442,8 @@ export class BFB extends BaseSerialProtocol { switch (mode) { case BfbTransportMode.NONE: debug('Mode: NONE'); - this.port.off('data', this.handleSerialDataCallback); - this.port.off('close', this.handleSerialCloseCallback); + this.stopReceiver(); this.atc.stop(); - this.buffer = Buffer.alloc(0); this.frames = []; this.frameQueueChannel = undefined; this.frameHandlers.clear(); @@ -455,10 +451,8 @@ export class BFB extends BaseSerialProtocol { case BfbTransportMode.AT: debug('Mode: AT'); - this.port.off('data', this.handleSerialDataCallback); - this.port.off('close', this.handleSerialCloseCallback); + this.stopReceiver(); this.atc.start(); - this.buffer = Buffer.alloc(0); this.frames = []; this.frameQueueChannel = undefined; break; @@ -466,12 +460,48 @@ export class BFB extends BaseSerialProtocol { case BfbTransportMode.BFB: debug('Mode: BFB'); this.atc.stop(); - this.port.on('data', this.handleSerialDataCallback); - this.port.on('close', this.handleSerialCloseCallback); + this.startReceiver(); break; } } + private startReceiver(): void { + const controller = new AbortController(); + this.receiveController = controller; + void this.receive(controller); + } + + private stopReceiver(): void { + this.receiveController?.abort(); + this.receiveController = undefined; + } + + private async receive(controller: AbortController): Promise { + const header = Buffer.allocUnsafe(3); + const signal = controller.signal; + try { + while (!signal.aborted) { + await this.port.readExactInto(header, 0, header.length, 0, signal); + + while (header[2] != (header[0] ^ header[1]) || header[1] > BFB_MAX_PAYLOAD_SIZE) { + header.copyWithin(0, 1); + await this.port.readExactInto(header, 2, 1, 0, signal); + } + + const frame: BfbFrame = { channel: header[0], data: Buffer.allocUnsafe(header[1]) }; + await this.port.readExactInto(frame.data, 0, frame.data.length, 0, signal); + try { + this.handleBfbFrame(frame); + } catch (error) { + debug('BFB event callback failed: %O', error); + } + } + } catch { + if (!signal.aborted && this.receiveController == controller) + this.handleSerialClose(); + } + } + private async findOpenedBfb(): Promise { this.setTransportMode(BfbTransportMode.BFB); for (const baudRate of Object.keys(BFB_BAUD_RATES).map(Number).sort((a, b) => b - a)) { @@ -550,27 +580,6 @@ export class BFB extends BaseSerialProtocol { this.setTransportMode(BfbTransportMode.NONE); } - private handleSerialData(data: Buffer): void { - this.buffer = Buffer.concat([this.buffer, data]); - while (this.buffer.length >= 3) { - const channel = this.buffer[0]; - const length = this.buffer[1]; - if (this.buffer[2] != (channel ^ length) || length > BFB_MAX_PAYLOAD_SIZE) { - this.buffer = this.buffer.subarray(1); - continue; - } - if (this.buffer.length < 3 + length) - break; - const frame = { channel, data: Buffer.from(this.buffer.subarray(3, 3 + length)) }; - this.buffer = this.buffer.subarray(3 + length); - try { - this.handleBfbFrame(frame); - } catch (error) { - debug('BFB event callback failed: %O', error); - } - } - } - private handleBfbFrame(frame: BfbFrame): void { if (debugTrx.enabled) debugTrx(sprintf('RX CH=%02X %s', frame.channel, frame.data.toString('hex'))); diff --git a/src/bfc/BFC.ts b/src/bfc/BFC.ts index 2256533..fb9cf56 100644 --- a/src/bfc/BFC.ts +++ b/src/bfc/BFC.ts @@ -128,9 +128,7 @@ export class BFC extends BaseSerialProtocol { private mode = BfcTransportMode.NONE; private authCache: Record = {}; private frameReceivers: Record = {}; - private buffer = Buffer.alloc(0); - private readonly handleSerialDataCallback = this.handleSerialData.bind(this); - private readonly handleSerialCloseCallback = this.handleSerialClose.bind(this); + private receiveController?: AbortController; private readonly atc = new AtChannel(this.port); private setTransportMode(mode: BfcTransportMode): void { @@ -141,29 +139,60 @@ export class BFC extends BaseSerialProtocol { switch (mode) { case BfcTransportMode.NONE: debug(`Mode: NONE`); - this.port.off('data', this.handleSerialDataCallback); - this.port.off('close', this.handleSerialCloseCallback); + this.stopReceiver(); this.atc.stop(); - this.buffer = Buffer.alloc(0); break; case BfcTransportMode.AT: debug(`Mode: AT`); - this.port.off('data', this.handleSerialDataCallback); - this.port.off('close', this.handleSerialCloseCallback); + this.stopReceiver(); this.atc.start(); - this.buffer = Buffer.alloc(0); break; case BfcTransportMode.BFC: debug(`Mode: BFC`); - this.port.on('data', this.handleSerialDataCallback); - this.port.on('close', this.handleSerialCloseCallback); this.atc.stop(); + this.startReceiver(); break; } } + private startReceiver(): void { + const controller = new AbortController(); + this.receiveController = controller; + void this.receive(controller); + } + + private stopReceiver(): void { + this.receiveController?.abort(); + this.receiveController = undefined; + } + + private async receive(controller: AbortController): Promise { + const header = Buffer.allocUnsafe(6); + const signal = controller.signal; + try { + while (!signal.aborted) { + await this.port.readExactInto(header, 0, header.length, 0, signal); + + while ((header[0] ^ header[1] ^ header[2] ^ header[3] ^ header[4]) != header[5]) { + header.copyWithin(0, 1); + await this.port.readExactInto(header, 5, 1, 0, signal); + } + + const payloadLength = header.readUInt16BE(2); + const packetLength = header.length + payloadLength + ((header[4] & BfcFrameFlags.CRC) ? 2 : 0); + const packet = Buffer.allocUnsafe(packetLength); + header.copy(packet); + await this.port.readExactInto(packet, header.length, packetLength - header.length, 0, signal); + void this.handleBfcPacket(packet); + } + } catch { + if (!signal.aborted && this.receiveController == controller) + this.handleSerialClose(); + } + } + private async findOpenedBfc(): Promise { this.setTransportMode(BfcTransportMode.BFC); for (const baudRate of SERIAL_BAUDRATES) { @@ -275,32 +304,6 @@ export class BFC extends BaseSerialProtocol { this.setTransportMode(BfcTransportMode.NONE); } - private handleSerialData(data: Buffer): void { - this.buffer = Buffer.concat([this.buffer, data]); - - while (this.buffer.length >= 6) { - let pktStart = findPacketStartInBuffer(this.buffer); - if (pktStart == null) { - this.buffer = this.buffer.subarray(this.buffer.length - 5); // trim noise - continue; - } - - if (pktStart > 0) { // trim noise - this.buffer = this.buffer.subarray(pktStart); - pktStart = 0; - } - - const pktLen = calcTotalPacketSize(this.buffer); - if (this.buffer.length < pktLen) - break; - - const pkt = this.buffer.subarray(0, pktLen); - this.buffer = this.buffer.subarray(pktLen); - - void this.handleBfcPacket(pkt); - } - } - private async handleBfcPacket(pkt: Buffer): Promise { const dst = pkt[0]; const src = pkt[1]; @@ -752,27 +755,9 @@ export class BFC extends BaseSerialProtocol { } } -function findPacketStartInBuffer(buffer: Buffer): number | undefined { - let i = 0; - while (buffer.length - i >= 6) { - const chk = buffer[i] ^ buffer[i + 1] ^ buffer[i + 2] ^ buffer[i + 3] ^ buffer[i + 4]; - if (chk == buffer[i + 5]) - return i; - i++; - } - return undefined; -} - function checkPacketChecksum(pkt: Buffer): boolean { const payloadLen = pkt.readUInt16BE(2); const pktCRC = pkt.readUInt16BE(6 + payloadLen); const realCRC = crc16(pkt, 0, payloadLen + 6); return pktCRC == realCRC; } - -function calcTotalPacketSize(pkt: Buffer): number { - let len = pkt.readUInt16BE(2) + 6; - if ((pkt[4] & BfcFrameFlags.CRC)) - len += 2; - return len; -} diff --git a/src/boot/ChaosLoader.ts b/src/boot/ChaosLoader.ts index c9f9de8..0576001 100644 --- a/src/boot/ChaosLoader.ts +++ b/src/boot/ChaosLoader.ts @@ -132,11 +132,7 @@ export class ChaosLoader extends BaseSerialProtocol { await this.port.write(Buffer.from([CMD.GET_INFO])); - const response = await this.port.read(128, 1000); - if (!response) - throw new ChaosLoaderError(`ERROR: Can't get phone info! (timeout)`); - if (response.length != 128) - throw new ChaosLoaderError(`ERROR: Can't get phone info! (invalid response, ${response.length} != 128)`); + const response = await this.port.readExact(128, 1000); const info: Partial = {}; let offset = 0; @@ -310,12 +306,7 @@ export class ChaosLoader extends BaseSerialProtocol { await this.port.write(cmd); - const response = await this.port.read(2, WRITE_PAGE_TIMEOUT); - if (!response) { - throw new ChaosLoaderError(`Memory write timeout!`); - } else if (response.length != 2) { - throw new ChaosLoaderError(`Received unexpected bytes count (expected: 2, received: ${response.length})`); - } + const response = await this.port.readExact(2, WRITE_PAGE_TIMEOUT); const status = response.readUInt16LE(0); if (status == RESPONSES.CHECKSUM_ERROR) { @@ -362,12 +353,7 @@ export class ChaosLoader extends BaseSerialProtocol { cmd.writeUInt32BE(size, 5); await this.port.write(cmd); - const response = await this.port.read(size + 4, READ_PAGE_TIMEOUT); - if (!response) { - throw new ChaosLoaderError(`Flash read timeout!`); - } else if (response.length != size + 4) { - throw new ChaosLoaderError(`Received unexpected bytes count (expected: ${size + 5}, received: ${response.length})`); - } + const response = await this.port.readExact(size + 4, READ_PAGE_TIMEOUT); const status = response.readUInt16LE(size); const receivedChk = response.readUInt16LE(size + 2); diff --git a/src/boot/EBL.ts b/src/boot/EBL.ts index c2c838c..51cc90c 100644 --- a/src/boot/EBL.ts +++ b/src/boot/EBL.ts @@ -57,9 +57,7 @@ export class EBL extends BaseSerialProtocol { debug("Waiting response from EBL..."); - const response = await this.port.read(76, 100); - if (!response) - throw new EBLError("No response from EBL! (ebl info)"); + const response = await this.port.readExact(76, 100); const mode = response.readUInt32LE(0); const major = response.readUInt32LE(4); @@ -140,9 +138,7 @@ export class EBL extends BaseSerialProtocol { } private async recvPacket(fromCmd: number): Promise { - const header = await this.port.read(6, 1000); - if (!header) - throw new EBLError("No response from EBL! (pkt header)"); + const header = await this.port.readExact(6, 1000); const pktStartToken = header.readUInt16LE(0); const cmd = header.readUInt16LE(2); const size = header.readUInt16LE(4); @@ -153,9 +149,7 @@ export class EBL extends BaseSerialProtocol { if (pktStartToken != 2) throw new EBLError("Invalid packet, pktStartToken=%02X", pktStartToken); - const body = await this.port.read(size + 4, 1000); - if (!body) - throw new EBLError("No response from EBL! (pkt body)"); + const body = await this.port.readExact(size + 4, 1000); const chk = body.readUInt16LE(size); const pktEndToken = body.readUInt16LE(size + 2); diff --git a/src/dwd/DWD.ts b/src/dwd/DWD.ts index b038b1b..c42a86e 100644 --- a/src/dwd/DWD.ts +++ b/src/dwd/DWD.ts @@ -477,9 +477,7 @@ export class DWD extends BaseSerialProtocol { if (expectedResponseLength == -1) { return Buffer.alloc(0); } else if (expectedResponseLength == 0) { - const frameHeader = await this.port.read(4, timeout); - if (!frameHeader) - throw new DWDTimeoutError("DWD command timeout! (header)"); + const frameHeader = await this.port.readExact(4, timeout); const receivedResponseFrameId = frameHeader.readUInt16LE(0); if (receivedResponseFrameId != responseFrameId) { @@ -489,9 +487,7 @@ export class DWD extends BaseSerialProtocol { } const expectedResponseLength = frameHeader.readUInt16LE(2); - const frameBody = await this.port.read(expectedResponseLength, timeout); - if (!frameBody) - throw new DWDTimeoutError("DWD command (%04X) timeout! (body)", requestFrameId); + const frameBody = await this.port.readExact(expectedResponseLength, timeout); debugTrx.enabled && debugTrx(sprintf(`[RX] %s %s`, hexdump(frameHeader), hexdump(frameBody))); if (frameBody.length != expectedResponseLength) { @@ -501,9 +497,7 @@ export class DWD extends BaseSerialProtocol { return Buffer.concat([frameHeader, frameBody]); } else { - const response = await this.port.read(expectedResponseLength, timeout); - if (!response) - throw new DWDTimeoutError("DWD command (%04X) timeout! (body)", requestFrameId); + const response = await this.port.readExact(expectedResponseLength, timeout); debugTrx.enabled && debugTrx(sprintf(`[RX] %s`, hexdump(response))); const receivedResponseFrameId = response.readUInt16LE(0); diff --git a/src/index.node.ts b/src/index.node.ts new file mode 100644 index 0000000..75e191e --- /dev/null +++ b/src/index.node.ts @@ -0,0 +1,2 @@ +export * from './index.shared.js'; +export * from './AsyncSerialPort.node.js'; diff --git a/src/index.shared.ts b/src/index.shared.ts new file mode 100644 index 0000000..28180e9 --- /dev/null +++ b/src/index.shared.ts @@ -0,0 +1,16 @@ +export * from './at/AtChannel.js'; +export * from './ppp/PPP.js'; +export * from './ppp/ICMP.js'; +export * from './ppp/IPv4.js'; +export * from './ppp/TCP.js'; +export * from './ppp/UDP.js'; +export * from './bfc/BFC.js'; +export * from './bfb/BFB.js'; +export * from './cgsn/CGSN.js'; +export * from './boot/BSL.js'; +export * from './dwd/DWD.js'; +export * from './boot/EBL.js'; +export * from './obex/OBEX.js'; +export * from './boot/ChaosLoader.js'; +export * from './io.js'; +export { delay, getUSBDeviceName, retryAsyncOnError } from './utils.js'; diff --git a/src/index.ts b/src/index.ts index 13359ba..761b927 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,17 +1,2 @@ -export * from './at/AtChannel.js'; -export * from './ppp/PPP.js'; -export * from './ppp/ICMP.js'; -export * from './ppp/IPv4.js'; -export * from './ppp/TCP.js'; -export * from './ppp/UDP.js'; -export * from './bfc/BFC.js'; -export * from './bfb/BFB.js'; -export * from './cgsn/CGSN.js'; -export * from './boot/BSL.js'; -export * from './dwd/DWD.js'; -export * from './boot/EBL.js'; -export * from './obex/OBEX.js'; -export * from './boot/ChaosLoader.js'; +export * from './index.shared.js'; export * from './AsyncSerialPort.js'; -export * from './io.js'; -export { delay, getUSBDeviceName, retryAsyncOnError } from './utils.js'; diff --git a/src/obex/OBEX.session.test.ts b/src/obex/OBEX.session.test.ts index 73d1554..e15f7dc 100644 --- a/src/obex/OBEX.session.test.ts +++ b/src/obex/OBEX.session.test.ts @@ -879,11 +879,9 @@ describe.concurrent('OBEX: session recovery', { timeout: 20000 }, () => { expect(phone.writes).toBe(writes); }); - // SerialPortStream closes the port on a failed write, and emits the error for the - // program to listen for, like examples/obex.ts does + // AsyncSerialPort closes the binding on a failed write test('a failed write closes the port and is reported', async () => { const phone = await fakePhone(); - phone.port.on('error', () => {}); const obex = await connected(phone); phone.failNextWrite(); diff --git a/src/obex/OBEX.ts b/src/obex/OBEX.ts index 07b89fc..e5ef0ed 100644 --- a/src/obex/OBEX.ts +++ b/src/obex/OBEX.ts @@ -1,10 +1,10 @@ import createDebug from 'debug'; -import { AsyncSerialPort } from '#src/AsyncSerialPort.js'; +import { AsyncSerialPort, SerialReadTimeoutError } from '#src/AsyncSerialPort.js'; import { AtChannel } from '#src/at/AtChannel.js'; import { BFC } from '#src/bfc/BFC.js'; import { BaseSerialProtocol } from '#src/BaseSerialProtocol.js'; import { ObexBfbLink, BfbTimeouts } from './ObexBfbLink.js'; -import { delay, flushInput, readExact, trySetBaudRate } from '#src/utils.js'; +import { delay } from '#src/utils.js'; const debug = createDebug('obex'); const debugTrx = createDebug('obex:trx'); @@ -388,13 +388,13 @@ interface ObexLink { // with a second of silence on both sides. An AT command inside the second after // it would cancel the escape. async function escapeToAt(port: AsyncSerialPort, delays: ObexDelays): Promise { - await flushInput(port, delays.flush); + await port.discardUntilIdle(delays.flush, Math.max(delays.flush, delays.abort)); await port.write(Buffer.from([ObexOpcode.DISCONNECT, 0x00, 0x03])); - await flushInput(port, delays.flush); + await port.discardUntilIdle(delays.flush, Math.max(delays.flush, delays.abort)); await delay(delays.escape); await port.write('+++'); await delay(delays.escape); - await flushInput(port, delays.flush); + await port.discardUntilIdle(delays.flush, Math.max(delays.flush, delays.abort)); } // OBEX packets as they are on the wire, after AT^SQWE=3 or its BFC tunneled twin @@ -422,9 +422,10 @@ class RawObexLink implements ObexLink { let opcode = -1; while (Date.now() < deadline) { throwIfDisconnected(signal); - const byte = await this.port.readByte(Math.max(1, Math.min(deadline - Date.now(), 250))); + const byte = await this.port.readByte(Math.max(1, deadline - Date.now()), signal); + throwIfDisconnected(signal); if (byte == -1) - continue; + break; if (isObexResponseCode(byte)) { opcode = byte; break; @@ -434,12 +435,21 @@ class RawObexLink implements ObexLink { if (opcode == -1) throw new Error('OBEX response timeout.'); - const lenBytes = await readExact(this.port, 2, deadline, signal); - const totalLen = lenBytes.readUInt16BE(0); - if (totalLen < 3) - throw new Error(`Invalid OBEX packet length: ${totalLen}.`); - const rest = await readExact(this.port, totalLen - 3, deadline, signal); - return Buffer.concat([Buffer.from([opcode]), lenBytes, rest]); + try { + const lenBytes = await this.port.readExact(2, Math.max(1, deadline - Date.now()), signal); + throwIfDisconnected(signal); + const totalLen = lenBytes.readUInt16BE(0); + if (totalLen < 3) + throw new Error(`Invalid OBEX packet length: ${totalLen}.`); + const rest = await this.port.readExact(totalLen - 3, Math.max(1, deadline - Date.now()), signal); + throwIfDisconnected(signal); + return Buffer.concat([Buffer.from([opcode]), lenBytes, rest]); + } catch (error) { + throwIfDisconnected(signal); + if (error instanceof SerialReadTimeoutError) + throw new Error('OBEX response timeout.'); + throw error; + } } async close(): Promise { @@ -647,7 +657,11 @@ export class OBEX extends BaseSerialProtocol { for (const [i, speed] of speeds.entries()) { throwIfDisconnected(signal); debug(`Probing AT handshake at ${speed} baud...`); - if (!await trySetBaudRate(this.port, speed)) { + try { + await this.port.update({ baudRate: speed }); + } catch (error) { + if (!this.port.isOpen) + throw error; if (baudRate) throw new Error(`The serial port refuses ${baudRate} baud.`); debug(`The port refuses ${speed} baud`); @@ -677,16 +691,7 @@ export class OBEX extends BaseSerialProtocol { // being taken for the next command's private async drainAt(): Promise { const quiet = 3 * AT_PROBE_TIMEOUT; - const deadline = Date.now() + 10 * quiet; - let last = Date.now(); - const onData = () => last = Date.now(); - this.port.on('data', onData); - try { - while (Date.now() - last < quiet && Date.now() < deadline) - await delay(quiet - (Date.now() - last)); - } finally { - this.port.off('data', onData); - } + await this.atc.drain(quiet); } private async readAtDeviceName(): Promise { @@ -760,11 +765,18 @@ export class OBEX extends BaseSerialProtocol { // escaped for a full handshake, without it the session goes on in OBEX mode. private async reopenObexMode(baudRate: number, signal: AbortSignal): Promise { const speed = baudRate || this.obexSpeed; - if (speed && !await trySetBaudRate(this.port, speed)) - return false; + if (speed) { + try { + await this.port.update({ baudRate: speed }); + } catch (error) { + if (!this.port.isOpen) + throw error; + return false; + } + } const escapes = await this.escapes(); const link = new RawObexLink(this.port, this.delays, escapes); - await flushInput(this.port, this.delays.flush); + await this.port.discardUntilIdle(this.delays.flush, Math.max(this.delays.flush, this.delays.abort)); await this.port.write(Buffer.from([ObexOpcode.ABORT, 0x00, 0x03])); try { await link.receive(OBEX_MODE_CHECK_TIMEOUT, signal); @@ -844,8 +856,13 @@ export class OBEX extends BaseSerialProtocol { for (const speed of speeds) { throwIfDisconnected(signal); debug(`No BFC either, escaping at ${speed} baud in case the phone is still in raw OBEX mode...`); - if (!await trySetBaudRate(this.port, speed)) + try { + await this.port.update({ baudRate: speed }); + } catch (error) { + if (!this.port.isOpen) + throw error; continue; + } await escapeToAt(this.port, this.delays); const atSpeed = await this.findAtSpeed(speed, signal); if (atSpeed) @@ -989,7 +1006,7 @@ export class OBEX extends BaseSerialProtocol { // Not through request(): a disconnect() has aborted the session. And the // rest of an interrupted exchange goes first, it would pass for the answer. try { - await flushInput(this.port, this.delays.flush); + await this.port.discardUntilIdle(this.delays.flush, Math.max(this.delays.flush, this.delays.abort)); const done = new AbortController(); await link.send(data, done.signal); await link.receive(this.delays.abort, done.signal); diff --git a/src/obex/ObexBfbLink.ts b/src/obex/ObexBfbLink.ts index be60eaa..cbf59d8 100644 --- a/src/obex/ObexBfbLink.ts +++ b/src/obex/ObexBfbLink.ts @@ -2,7 +2,6 @@ import createDebug from 'debug'; import { AsyncSerialPort } from '#src/AsyncSerialPort.js'; import { BFB_MAX_PAYLOAD_SIZE, BfbChannel, BfbCoreOpcode, encodeBfbFrame } from '#src/bfb/BFB.js'; import { crc16 } from '#src/crc16.js'; -import { flushInput, readExact, trySetBaudRate } from '#src/utils.js'; const debug = createDebug('obex'); @@ -81,12 +80,16 @@ export class ObexBfbLink { static async open(port: AsyncSerialPort, timeouts: BfbTimeouts): Promise { for (const baudRate of BFB_SPEEDS) { - if (!await trySetBaudRate(port, baudRate)) { + try { + await port.update({ baudRate }); + } catch (error) { + if (!port.isOpen) + throw error; debug(`The port refuses ${baudRate} baud`); continue; } for (let i = 0; i < 2; i++) { - await flushInput(port, timeouts.flush); + await port.discardUntilIdle(timeouts.flush); await port.write(HELLO); if ((await port.read(HELLO_ANSWER.length, timeouts.hello))?.equals(HELLO_ANSWER)) { debug(`BFB link at ${baudRate} baud.`); @@ -101,11 +104,15 @@ export class ObexBfbLink { // killed program left behind static async leave(port: AsyncSerialPort, timeouts: BfbTimeouts): Promise { for (const baudRate of BFB_SPEEDS) { - if (!await trySetBaudRate(port, baudRate)) + try { + await port.update({ baudRate }); + } catch (error) { + if (!port.isOpen) + throw error; continue; + } await port.write(LEAVE); - // Also lets the frame leave the wire before the next speed change - await flushInput(port, timeouts.flush); + await port.discardUntilIdle(timeouts.flush); } } @@ -121,7 +128,7 @@ export class ObexBfbLink { // Like siefs, acknowledge again first: the phone may still be resending a // packet of its own because our acknowledgement of it got lost if (attempt > 0) { - await flushInput(this.port, this.timeouts.flush); + await this.port.discardUntilIdle(this.timeouts.flush); await this.port.write(ACK); } await this.port.write(wire); @@ -167,7 +174,7 @@ export class ObexBfbLink { if (!this.port.isOpen) return; await this.port.write(LEAVE); - await flushInput(this.port, this.timeouts.flush); + await this.port.discardUntilIdle(this.timeouts.flush); } // The payload of the next SERVICE_STREAM frame, skipping frames of other @@ -178,16 +185,22 @@ export class ObexBfbLink { this.answerFrame = undefined; return answerFrame; } - let header = await readExact(this.port, 3, deadline, signal); + const header = Buffer.allocUnsafe(3); + await this.port.readExactInto(header, 0, header.length, Math.max(1, deadline - Date.now()), signal); + signal?.throwIfAborted(); while (true) { if ((header[0] ^ header[1]) != header[2] || header[1] > BFB_MAX_PAYLOAD_SIZE) { - header = Buffer.concat([header.subarray(1), await readExact(this.port, 1, deadline, signal)]); + header.copyWithin(0, 1); + await this.port.readExactInto(header, 2, 1, Math.max(1, deadline - Date.now()), signal); + signal?.throwIfAborted(); continue; } - const payload = await readExact(this.port, header[1], deadline, signal); + const payload = await this.port.readExact(header[1], Math.max(1, deadline - Date.now()), signal); + signal?.throwIfAborted(); if (header[0] == BfbChannel.SERVICE_STREAM) return payload; - header = await readExact(this.port, 3, deadline, signal); + await this.port.readExactInto(header, 0, header.length, Math.max(1, deadline - Date.now()), signal); + signal?.throwIfAborted(); } } } diff --git a/src/ppp/PPP.ts b/src/ppp/PPP.ts index a03bfb9..e0e26ae 100644 --- a/src/ppp/PPP.ts +++ b/src/ppp/PPP.ts @@ -121,8 +121,7 @@ export class PPP extends BaseSerialProtocol { private readonly packetHandlers = new Set(); private configuredAddress: Buffer | undefined; private readonly icmp = new ICMP(this); - private readonly handleSerialDataCallback = this.handleSerialData.bind(this); - private readonly handleSerialCloseCallback = this.handleSerialClose.bind(this); + private receiveController?: AbortController; private handleSerialClose() { this.stop(); @@ -219,10 +218,11 @@ export class PPP extends BaseSerialProtocol { this.packets = []; this.configuredAddress = undefined; this.running = true; - this.port.on('data', this.handleSerialDataCallback); - this.port.on('close', this.handleSerialCloseCallback); if (initialData?.length) this.handleSerialData(initialData); + const controller = new AbortController(); + this.receiveController = controller; + void this.receive(controller); } stop() { @@ -235,8 +235,8 @@ export class PPP extends BaseSerialProtocol { this.chapUsername = undefined; this.chapPassword = undefined; this.chapChallengeIdentifier = undefined; - this.port.off('data', this.handleSerialDataCallback); - this.port.off('close', this.handleSerialCloseCallback); + this.receiveController?.abort(); + this.receiveController = undefined; this.frame = []; this.packets = []; this.packetHandlers.clear(); @@ -249,6 +249,21 @@ export class PPP extends BaseSerialProtocol { } } + private async receive(controller: AbortController): Promise { + try { + while (!controller.signal.aborted) { + const data = await this.port.readNextChunk(controller.signal); + if (controller.signal.aborted) + break; + if (data) + this.handleSerialData(data); + } + } catch { + if (!controller.signal.aborted && this.receiveController == controller) + this.handleSerialClose(); + } + } + onPacket(callback: PppPacketHandler): () => void { this.packetHandlers.add(callback); return () => this.packetHandlers.delete(callback); diff --git a/src/utils.test.ts b/src/utils.test.ts index 02968f8..a67c56a 100644 --- a/src/utils.test.ts +++ b/src/utils.test.ts @@ -1,20 +1,8 @@ -import { describe, expect, test } from 'vitest'; -import { AsyncSerialPort } from './AsyncSerialPort.js'; -import { decodeCString, flushInput } from './utils.js'; +import { expect, test } from 'vitest'; +import { decodeCString } from './utils.js'; test('decodeCString stops at the first NUL', () => { expect(decodeCString(Buffer.from([0, 65]))).toBe(''); expect(decodeCString(Buffer.from('abc\0tail'))).toBe('abc'); expect(decodeCString(Buffer.from('abc'))).toBe('abc'); }); - -describe('flushInput', () => { - // e.g. a BFB phone resending its packet faster than the flush timeout - test('gives up on a line that never goes quiet', async () => { - const chatty = { read: async () => Buffer.from([0x55]) } as unknown as AsyncSerialPort; - const started = Date.now(); - - await flushInput(chatty, 50, 200); - expect(Date.now() - started).toBeLessThan(1000); - }); -}); diff --git a/src/utils.ts b/src/utils.ts index c02e305..1df9728 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,5 +1,4 @@ import { sprintf } from "sprintf-js"; -import { AsyncSerialPort } from "./AsyncSerialPort.js"; const USB_DEVICES: Record = { "067B:2303": "PL2303", @@ -70,52 +69,6 @@ export async function retryAsyncOnError(callback: () => Promise, options: throw lastError; } -// Reads exactly size bytes, or fails once the deadline (a Date.now() timestamp) passes -// or signal is aborted -export async function readExact(port: AsyncSerialPort, size: number, deadline: number, signal?: AbortSignal): Promise { - const chunks: Buffer[] = []; - let remaining = size; - while (remaining > 0) { - if (signal?.aborted) - throw new Error("Serial receive cancelled."); - const left = deadline - Date.now(); - if (left <= 0) - throw new Error("Serial receive timeout."); - // Short waits with a signal, so that an abort ends the read soon - const chunk = await port.read(remaining, Math.min(left, signal ? 250 : 2000)); - if (!chunk?.length) - continue; - chunks.push(chunk); - remaining -= chunk.length; - } - return Buffer.concat(chunks); -} - -// Drops input until the line has been quiet for timeout ms, but for maxTime ms at -// most: a line that never goes quiet must not keep it forever -export async function flushInput(port: AsyncSerialPort, timeout: number, maxTime = Math.max(3000, timeout * 10)): Promise { - // A read without a timeout waits for the next byte, however long that takes - timeout = Math.max(timeout, 1); - const deadline = Date.now() + maxTime; - let chunk: Buffer | undefined; - do { - chunk = await port.read(1, timeout); - } while (chunk?.length && Date.now() < deadline); -} - -// Switches the port to baudRate, false when the port refuses that rate: legacy -// Windows COM ports refuse anything above 115200 -export async function trySetBaudRate(port: AsyncSerialPort, baudRate: number): Promise { - try { - await port.update({ baudRate }); - return true; - } catch (e) { - if (!port.isOpen) - throw e; - return false; - } -} - export function hexdump(buffer: Buffer) { const str: string[] = []; for (const byte of buffer) diff --git a/tests/obex/README.md b/tests/obex/README.md index 2ded4c6..6604736 100644 --- a/tests/obex/README.md +++ b/tests/obex/README.md @@ -116,7 +116,7 @@ fullflash has to stay byte-identical for other projects' tests. while the line is still busy. With it the EL71 and the S75 take 4 KiB writes ten times in a row; without it they die on the first one. * **The host baud rate is meaningless, but the guest's is not.** It is a TCP - chardev, so whatever `SerialPort` is opened with is ignored — but the firmware + chardev, so whatever `AsyncSerialPort` is opened with is ignored — but the firmware programs USART0 itself, and the emulator paces delivery to *that*: ~691 kbaud on the x75 phones. * **Every emulated phone loses a command every 30–40 s.** Pinged with `AT` diff --git a/tests/obex/emulator.ts b/tests/obex/emulator.ts index 62ae9c8..adc35f0 100644 --- a/tests/obex/emulator.ts +++ b/tests/obex/emulator.ts @@ -1,7 +1,7 @@ // Runs an emulated Siemens phone for the e2e tests. // // pmb887x-emu boots a real fullflash and exposes the phone's USART0 as a QEMU -// TCP chardev, which serialport reaches through serialport-bindings-socket. The +// TCP chardev, which AsyncSerialPort reaches through serialport-bindings-socket. The // firmware that answers on it is the phone's own, so the tests talk to a real // AT interpreter and a real FlexMem OBEX server - see tests/obex/README.md for what // the emulator can and cannot do. @@ -13,8 +13,7 @@ import os from 'node:os'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { setTimeout as delay } from 'node:timers/promises'; -import { SerialPortStream } from '@serialport/stream'; -import { SocketBinding, SocketBindingInterface } from 'serialport-bindings-socket'; +import { SocketBinding } from 'serialport-bindings-socket'; import { AsyncSerialPort, PhonePlatform } from '../../src/index.js'; import { PhoneTarget, RECONNECT_WAIT_MS, RunningTarget } from './target.js'; @@ -237,12 +236,11 @@ async function startPhone(phone: EmulatedPhone): Promise { // The host baud rate is meaningless on a TCP chardev; the firmware pins // USART0 at 115200 either way - const port = new AsyncSerialPort(new SerialPortStream({ + const port = new AsyncSerialPort({ binding: SocketBinding, path: `tcp://127.0.0.1:${tcpPort}`, baudRate: 115200, - autoOpen: false, - })); + }); await port.open(); return { port, log, stop }; } catch (e) { diff --git a/tests/obex/obexSuite.ts b/tests/obex/obexSuite.ts index fcff59b..0bd2546 100644 --- a/tests/obex/obexSuite.ts +++ b/tests/obex/obexSuite.ts @@ -41,17 +41,18 @@ function joinPath(dir: string, name: string): string { // How much of what the phone sent is kept for the panic check const RECEIVED_TAIL_SIZE = 4096; -// The last bytes the phone sent, tapped below the stream so that the protocols see -// the port unchanged. A phone that panics writes ">>EXIT<< ... FILE: ..." to its +// The last bytes the phone sent, tapped at the port so that the protocols see the +// data unchanged. A phone that panics writes ">>EXIT<< ... FILE: ..." to its // serial line and never answers again (see README.md); the OBEX client skips that // text as garbage, so only this tail says why the phone went quiet. function tapReceived(port: AsyncSerialPort): () => Buffer { - const binding = (port.getParentPort() as any).port; - const read = binding.read; + const binding = port.getBindingPort(); + const read = binding.read.bind(binding); let tail = Buffer.alloc(0); - binding.read = async (buffer: Buffer, offset: number, length: number) => { - const result = await read.call(binding, buffer, offset, length); - tail = Buffer.concat([tail, buffer.subarray(offset, offset + result.bytesRead)]).subarray(-RECEIVED_TAIL_SIZE); + binding.read = async (buffer, offset, length) => { + const result = await read(buffer, offset, length); + const data = result.buffer.subarray(offset, offset + result.bytesRead); + tail = Buffer.concat([tail, data]).subarray(-RECEIVED_TAIL_SIZE); return result; }; return () => tail; diff --git a/tests/obex/phones/fakePhone.ts b/tests/obex/phones/fakePhone.ts index 9387bb4..8e54b9f 100644 --- a/tests/obex/phones/fakePhone.ts +++ b/tests/obex/phones/fakePhone.ts @@ -1,10 +1,9 @@ // A phone that behaves the way a database entry (db/*.json) says: an AT interpreter, // BFC mode on a service cable, raw OBEX after AT^SQWE=3 or BFB frames after // AT^SBFB=1, and a FlexMem server with the entry's folders, response codes and file -// semantics. openFakePhonePort() puts it behind the real SerialPortStream, where it +// semantics. openFakePhonePort() puts it behind the real AsyncSerialPort, where it // sees the baud rate the client sets and answers only at the entry's speeds. -import { SerialPortStream } from '@serialport/stream'; import { BindingInterface, BindingPortInterface, OpenOptions, PortStatus, UpdateOptions } from '@serialport/bindings-interface'; import { AsyncSerialPort } from '#src/AsyncSerialPort.js'; import { BfbChannel, BfbCoreOpcode } from '#src/bfb/BFB.js'; @@ -724,7 +723,7 @@ export interface SerialDevice { refusedBaudRates?: number[]; } -// The serial port a device sits on, a binding of its own for SerialPortStream +// The serial port a device sits on, exposed as a binding to AsyncSerialPort class DevicePortBinding implements BindingPortInterface { readonly openOptions: Required; isOpen = true; @@ -793,14 +792,13 @@ class DevicePortBinding implements BindingPortInterface { async drain(): Promise {} } -// A device behind the real SerialPortStream + AsyncSerialPort, the way the client -// sees a phone on a cable +// A device behind the real AsyncSerialPort, the way the client sees a phone on a cable export async function openDevicePort(device: SerialDevice, name = 'device'): Promise { const binding: BindingInterface = { list: async () => [], open: async (options) => new DevicePortBinding(device, options), }; - const port = new AsyncSerialPort(new SerialPortStream({ binding, path: `fake:${name}`, baudRate: 115200, autoOpen: false })); + const port = new AsyncSerialPort({ binding, path: `fake:${name}`, baudRate: 115200 }); await port.open(); return port; } diff --git a/tests/obex/phones/probe.ts b/tests/obex/phones/probe.ts index 3dd6828..88fd637 100644 --- a/tests/obex/phones/probe.ts +++ b/tests/obex/phones/probe.ts @@ -133,13 +133,12 @@ class Wire { // Whatever arrives within ms, or until done() says the answer is complete async read(ms: number, done?: (data: Buffer) => boolean): Promise { const deadline = Date.now() + ms; - const stream = this.port.getParentPort(); let data = Buffer.alloc(0); while (Date.now() < deadline && !done?.(data)) { const first = await this.port.read(1, Math.max(1, deadline - Date.now())); if (!first?.length) break; - const rest = stream.readableLength ? await this.port.read(stream.readableLength, 1) : undefined; + const rest = await this.port.readNextChunk(AbortSignal.timeout(1)); const chunk = Buffer.concat([first, rest ?? Buffer.alloc(0)]); this.log('RX', chunk); data = Buffer.concat([data, chunk]);