@astm-e1394/serial 0.0.0-stage → 1.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Panates
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,78 @@
1
- # Temporary Holding Version
1
+ # @astm-e1394/serial
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Connects to laboratory instruments over serial ports for ASTM E1394 messages.
4
+
5
+ [![NPM Version][npm-image]][npm-url]
6
+ [![NPM Downloads][downloads-image]][downloads-url]
7
+ [![CI Tests][ci-test-image]][ci-test-url]
8
+ [![Test Coverage][coveralls-image]][coveralls-url]
9
+
10
+ [npm-image]: https://img.shields.io/npm/v/@astm-e1394/serial
11
+ [npm-url]: https://npmjs.org/package/@astm-e1394/serial
12
+ [downloads-image]: https://img.shields.io/npm/dm/@astm-e1394/serial.svg
13
+ [downloads-url]: https://npmjs.org/package/@astm-e1394/serial
14
+ [ci-test-image]: https://github.com/panates/astm-e1394/actions/workflows/test.yml/badge.svg
15
+ [ci-test-url]: https://github.com/panates/astm-e1394/actions/workflows/test.yml
16
+ [coveralls-image]: https://img.shields.io/coveralls/panates/astm-e1394/dev.svg
17
+ [coveralls-url]: https://coveralls.io/r/panates/astm-e1394
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ npm install @astm-e1394/core@beta @astm-e1394/serial@beta
23
+ ```
24
+
25
+ A serial port connection for [`@astm-e1394/core`](https://www.npmjs.com/package/@astm-e1394/core)'s `AstmLink`, which runs the ASTM E1381 (LIS1-A) protocol and the message handlers. The core README describes the link, its handlers and its options. The port is opened with the [serialport](https://www.npmjs.com/package/serialport) package, which comes with prebuilt binaries for the common platforms.
26
+
27
+ ## Usage
28
+
29
+ ```typescript
30
+ import { AstmLink } from '@astm-e1394/core';
31
+ import { SerialConnection } from '@astm-e1394/serial';
32
+
33
+ const link = new AstmLink(
34
+ new SerialConnection({
35
+ path: 'COM3', // or '/dev/ttyUSB0'
36
+ baudRate: 9600,
37
+ dataBits: 8,
38
+ parity: 'none',
39
+ stopBits: 1,
40
+ }),
41
+ { role: 'host' },
42
+ );
43
+ link.use('result', async req => store(req.message));
44
+ link.on('error', err => console.error(err));
45
+ await link.open();
46
+ ```
47
+
48
+ | Option | Default | What it is |
49
+ | --- | --- | --- |
50
+ | `path` | | The port |
51
+ | `baudRate` | 9600 | |
52
+ | `dataBits` | 8 | 5, 6, 7 or 8 |
53
+ | `parity` | `'none'` | `'none'`, `'even'`, `'odd'`, `'mark'` or `'space'` |
54
+ | `stopBits` | 1 | 1, 1.5 or 2 |
55
+ | `rtscts` | `false` | Hardware flow control |
56
+ | `xonxoff` | `false` | Software flow control |
57
+ | `reconnectDelay` | 5000 | The wait in ms before opening the port again when it closes on its own, such as a USB adapter unplugged, or an attempt fails; 0 turns this off |
58
+
59
+ `write()` resolves once the bytes have left the port, so the link's delays (`ackDelay`, `frameDelay`) are counted from the wire.
60
+
61
+ ## A port of your own
62
+
63
+ Given a port made elsewhere - a `SerialPort` of the serialport package, open or not - the connection uses that port as it is:
64
+
65
+ ```typescript
66
+ import { SerialPort } from 'serialport';
67
+
68
+ const port = new SerialPort({ path: 'COM3', baudRate: 9600 });
69
+ const link = new AstmLink(new SerialConnection(port));
70
+ ```
71
+
72
+ - `open()` opens the port when it is closed, or waits while its owner opens it.
73
+ - The port's own `open`, `close` and `data` go to the link, also when its owner closes or opens it.
74
+ - The connection never makes another port, and does not open this one again on its own.
75
+
76
+ ## License
77
+
78
+ [MIT](https://github.com/panates/astm-e1394/blob/main/LICENSE)
package/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './serial-connection.js';
package/index.js ADDED
@@ -0,0 +1 @@
1
+ export * from './serial-connection.js';
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "@astm-e1394/serial",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "description": "Connects to laboratory instruments over serial ports for ASTM E1394 messages.",
4
+ "version": "1.0.0-beta.0",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./index.d.ts",
10
+ "default": "./index.js"
11
+ },
12
+ "./package.json": "./package.json"
13
+ },
14
+ "engines": {
15
+ "node": ">=22"
16
+ },
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/panates/astm-e1394.git",
20
+ "directory": "packages/core/serial"
21
+ },
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "dependencies": {
26
+ "@astm-e1394/core": "^1.0.0-beta.0",
27
+ "serialport": "^13.0.0"
28
+ }
6
29
  }
@@ -0,0 +1,82 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import type { AstmConnection, AstmConnectionEvents } from '@astm-e1394/core';
3
+ export interface SerialConnectionOptions {
4
+ /** The port: "COM3", "/dev/ttyUSB0" */
5
+ path: string;
6
+ /** Default 9600, the speed most instruments start at */
7
+ baudRate?: number;
8
+ /** Default 8 */
9
+ dataBits?: 5 | 6 | 7 | 8;
10
+ /** Default 'none' */
11
+ parity?: 'none' | 'even' | 'odd' | 'mark' | 'space';
12
+ /** Default 1 */
13
+ stopBits?: 1 | 1.5 | 2;
14
+ /** Hardware flow control (RTS/CTS). Default false. */
15
+ rtscts?: boolean;
16
+ /** Software flow control (XON/XOFF), both ways. Default false. */
17
+ xonxoff?: boolean;
18
+ /**
19
+ * The wait in ms before opening the port again after it closes on its own
20
+ * - a USB adapter unplugged - or an attempt fails; 0 turns this off.
21
+ * Default 5 s.
22
+ */
23
+ reconnectDelay?: number;
24
+ }
25
+ /** What SerialConnection needs of a port: a SerialPort, or a mock in tests */
26
+ export interface SerialPortLike extends EventEmitter {
27
+ readonly isOpen: boolean;
28
+ /** True while an open is in progress, as SerialPort has it */
29
+ readonly opening?: boolean;
30
+ readonly path?: string;
31
+ open(callback: (err: Error | null) => void): void;
32
+ close(callback?: (err: Error | null) => void): void;
33
+ write(data: Buffer): boolean;
34
+ drain(callback: (err: Error | null) => void): void;
35
+ }
36
+ /**
37
+ * A serial port to an instrument, through the serialport package.
38
+ *
39
+ * Given options, the connection makes the port and opens it. Given a port
40
+ * made elsewhere - a SerialPort, open or not - it uses that port as it is:
41
+ * open() opens it when it is closed, the port's own events are passed on,
42
+ * and the connection never makes another port or opens it again on its
43
+ * own.
44
+ *
45
+ * open() resolves once the port is open. When the first attempt fails it
46
+ * rejects; with reopening on, the connection keeps trying in the background
47
+ * and emits 'open' when it gets through. Failed attempts after the first
48
+ * are emitted as 'error'. close() stops reopening.
49
+ */
50
+ export declare class SerialConnection extends EventEmitter<AstmConnectionEvents> implements AstmConnection {
51
+ readonly options: Readonly<SerialConnectionOptions>;
52
+ readonly description: string;
53
+ protected _port?: SerialPortLike;
54
+ /** Between open() and close(): the port is to be kept open */
55
+ protected _wanted: boolean;
56
+ protected _opening?: Promise<void>;
57
+ protected _reconnectTimer?: NodeJS.Timeout;
58
+ /** The port given to the constructor, used as it is */
59
+ protected _given?: SerialPortLike;
60
+ constructor(options: SerialConnectionOptions);
61
+ constructor(port: SerialPortLike);
62
+ /** The port in use, while there is one; a given port always */
63
+ get port(): SerialPortLike | undefined;
64
+ get isOpen(): boolean;
65
+ get reconnectDelay(): number;
66
+ open(): Promise<void>;
67
+ close(): Promise<void>;
68
+ /** Resolves once the bytes have gone out of the port */
69
+ write(data: Buffer): Promise<void>;
70
+ /** Makes the port, not yet open; tests give a mock here */
71
+ protected _createPort(): SerialPortLike;
72
+ protected _open(): Promise<void>;
73
+ /** A given port: its 'open' event becomes the connection's */
74
+ protected _openGiven(port: SerialPortLike): Promise<void>;
75
+ /** A given port is the connection's for good: its events are passed on */
76
+ protected _attachGiven(port: SerialPortLike): void;
77
+ protected _attach(port: SerialPortLike): void;
78
+ protected _scheduleReconnect(): void;
79
+ protected _clearReconnect(): void;
80
+ /** 'error' without a listener would throw in the port's callback */
81
+ protected _emitError(error: Error): void;
82
+ }
@@ -0,0 +1,205 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import { SerialPort } from 'serialport';
3
+ /**
4
+ * A serial port to an instrument, through the serialport package.
5
+ *
6
+ * Given options, the connection makes the port and opens it. Given a port
7
+ * made elsewhere - a SerialPort, open or not - it uses that port as it is:
8
+ * open() opens it when it is closed, the port's own events are passed on,
9
+ * and the connection never makes another port or opens it again on its
10
+ * own.
11
+ *
12
+ * open() resolves once the port is open. When the first attempt fails it
13
+ * rejects; with reopening on, the connection keeps trying in the background
14
+ * and emits 'open' when it gets through. Failed attempts after the first
15
+ * are emitted as 'error'. close() stops reopening.
16
+ */
17
+ export class SerialConnection extends EventEmitter {
18
+ options;
19
+ description;
20
+ _port;
21
+ /** Between open() and close(): the port is to be kept open */
22
+ _wanted = false;
23
+ _opening;
24
+ _reconnectTimer;
25
+ /** The port given to the constructor, used as it is */
26
+ _given;
27
+ constructor(arg) {
28
+ super();
29
+ if (isPort(arg)) {
30
+ this._given = arg;
31
+ this.options = { path: arg.path || '', reconnectDelay: 0 };
32
+ this.description = `serial:${arg.path || 'port'}`;
33
+ this._attachGiven(arg);
34
+ return;
35
+ }
36
+ this.options = { ...arg };
37
+ this.description = `serial:${arg.path}`;
38
+ }
39
+ /** The port in use, while there is one; a given port always */
40
+ get port() {
41
+ return this._port;
42
+ }
43
+ get isOpen() {
44
+ return !!this._port?.isOpen;
45
+ }
46
+ get reconnectDelay() {
47
+ if (this._given)
48
+ return 0;
49
+ return this.options.reconnectDelay ?? 5000;
50
+ }
51
+ async open() {
52
+ this._wanted = true;
53
+ if (this.isOpen)
54
+ return;
55
+ this._clearReconnect();
56
+ try {
57
+ await this._open();
58
+ }
59
+ catch (e) {
60
+ this._scheduleReconnect();
61
+ throw e;
62
+ }
63
+ }
64
+ async close() {
65
+ this._wanted = false;
66
+ this._clearReconnect();
67
+ const opening = this._opening;
68
+ if (opening)
69
+ await opening.catch(() => undefined);
70
+ const port = this._port;
71
+ if (!port?.isOpen)
72
+ return;
73
+ await new Promise(resolve => {
74
+ port.once('close', () => resolve());
75
+ port.close(err => err && resolve());
76
+ });
77
+ }
78
+ /** Resolves once the bytes have gone out of the port */
79
+ write(data) {
80
+ const port = this._port;
81
+ if (!port?.isOpen) {
82
+ return Promise.reject(new Error(`${this.description} is not open`));
83
+ }
84
+ return new Promise((resolve, reject) => {
85
+ port.write(data);
86
+ port.drain(err => (err ? reject(err) : resolve()));
87
+ });
88
+ }
89
+ /** Makes the port, not yet open; tests give a mock here */
90
+ _createPort() {
91
+ const o = this.options;
92
+ return new SerialPort({
93
+ path: o.path,
94
+ baudRate: o.baudRate ?? 9600,
95
+ dataBits: o.dataBits ?? 8,
96
+ parity: o.parity ?? 'none',
97
+ stopBits: o.stopBits ?? 1,
98
+ rtscts: !!o.rtscts,
99
+ xon: !!o.xonxoff,
100
+ xoff: !!o.xonxoff,
101
+ autoOpen: false,
102
+ });
103
+ }
104
+ _open() {
105
+ if (this._opening)
106
+ return this._opening;
107
+ if (this._given)
108
+ return this._openGiven(this._given);
109
+ const promise = new Promise((resolve, reject) => {
110
+ const port = this._createPort();
111
+ port.open(err => {
112
+ if (err)
113
+ return reject(err);
114
+ if (!this._wanted) {
115
+ /* close() was called while opening */
116
+ port.close();
117
+ return resolve();
118
+ }
119
+ this._attach(port);
120
+ resolve();
121
+ this.emit('open');
122
+ });
123
+ });
124
+ this._opening = promise;
125
+ const done = () => {
126
+ if (this._opening === promise)
127
+ this._opening = undefined;
128
+ };
129
+ promise.then(done, done);
130
+ return promise;
131
+ }
132
+ /** A given port: its 'open' event becomes the connection's */
133
+ _openGiven(port) {
134
+ const promise = new Promise((resolve, reject) => {
135
+ if (port.opening) {
136
+ const onError = (err) => {
137
+ port.removeListener('open', onOpen);
138
+ reject(err);
139
+ };
140
+ const onOpen = () => {
141
+ port.removeListener('error', onError);
142
+ resolve();
143
+ };
144
+ port.once('open', onOpen);
145
+ port.once('error', onError);
146
+ return;
147
+ }
148
+ port.open(err => (err ? reject(err) : resolve()));
149
+ });
150
+ this._opening = promise;
151
+ const done = () => {
152
+ if (this._opening === promise)
153
+ this._opening = undefined;
154
+ };
155
+ promise.then(done, done);
156
+ return promise;
157
+ }
158
+ /** A given port is the connection's for good: its events are passed on */
159
+ _attachGiven(port) {
160
+ this._port = port;
161
+ port.on('open', () => this.emit('open'));
162
+ port.on('data', (data) => this.emit('data', data));
163
+ port.on('error', (err) => this._emitError(err));
164
+ port.on('close', () => this.emit('close'));
165
+ }
166
+ _attach(port) {
167
+ this._port = port;
168
+ port.on('data', (data) => this.emit('data', data));
169
+ port.on('error', (err) => this._emitError(err));
170
+ port.once('close', () => {
171
+ port.removeAllListeners('data');
172
+ if (this._port === port)
173
+ this._port = undefined;
174
+ this.emit('close');
175
+ this._scheduleReconnect();
176
+ });
177
+ }
178
+ _scheduleReconnect() {
179
+ const delay = this.reconnectDelay;
180
+ if (!this._wanted || delay <= 0 || this._reconnectTimer)
181
+ return;
182
+ this._reconnectTimer = setTimeout(() => {
183
+ this._reconnectTimer = undefined;
184
+ if (!this._wanted || this.isOpen)
185
+ return;
186
+ this._open().catch(err => {
187
+ this._emitError(err);
188
+ this._scheduleReconnect();
189
+ });
190
+ }, delay);
191
+ }
192
+ _clearReconnect() {
193
+ if (this._reconnectTimer)
194
+ clearTimeout(this._reconnectTimer);
195
+ this._reconnectTimer = undefined;
196
+ }
197
+ /** 'error' without a listener would throw in the port's callback */
198
+ _emitError(error) {
199
+ if (this.listenerCount('error'))
200
+ this.emit('error', error);
201
+ }
202
+ }
203
+ function isPort(arg) {
204
+ return typeof arg.open === 'function';
205
+ }