mirror of
https://github.com/siemens-mobile-hacks/node-serialport-bindings-cpp.git
synced 2026-11-25 18:37:19 +00:00
feat: migrate to typescript (#3)
This change migrates to typescript. The tests have been modified to conform to typescript and to cleanup cases when they weren't actually working (only one or two cases). I've defined the existing bindings interface for all platforms. There are changes I'd love to make but didn't here (update/set/get/getBaudRate etc are messy). This should in theory be a drop in for the existing bindings. If there are bugs I imagine they're type related not functionality. I dropped abstract bindings as having it a separate package didn't make sense during the refactor. I'd like to iterate on the design a bit more before returning to that class. Mockbinding may also now be drifted slightly from this package. I'll clean those inconsistencies up when I upgrade the main repo.
This commit is contained in:
parent
06aba3a283
commit
2a93f48ee6
47 changed files with 2280 additions and 2385 deletions
61
.eslintrc
61
.eslintrc
|
|
@ -1,61 +0,0 @@
|
|||
{
|
||||
"extends": [
|
||||
"eslint:recommended",
|
||||
"plugin:node/recommended",
|
||||
"plugin:mocha/recommended"
|
||||
],
|
||||
"plugins": [
|
||||
"prettier",
|
||||
"node",
|
||||
"mocha"
|
||||
],
|
||||
"env": {
|
||||
"node": true,
|
||||
"mocha": true,
|
||||
"es6": true
|
||||
},
|
||||
"parserOptions": {
|
||||
"ecmaVersion": 2018,
|
||||
"ecmaFeatures": {
|
||||
"jsx": true
|
||||
}
|
||||
},
|
||||
"globals": {
|
||||
"assert": false,
|
||||
"makeTestFeature": false,
|
||||
"shouldReject": false
|
||||
},
|
||||
"rules": {
|
||||
"no-extra-semi": "off",
|
||||
"no-process-exit": "off",
|
||||
"no-unused-vars": [ "error", { "vars": "all", "args": "after-used" }],
|
||||
"no-var": "error",
|
||||
"node/no-extraneous-require": "off",
|
||||
"node/no-unpublished-require": "off",
|
||||
"node/no-unsupported-features/es-builtins": "error",
|
||||
"node/no-unsupported-features/es-syntax": "error",
|
||||
"node/no-unsupported-features/node-builtins": "error",
|
||||
"node/shebang": "off",
|
||||
"object-shorthand": "error",
|
||||
"prefer-arrow-callback": "error",
|
||||
"prefer-const": "error",
|
||||
"prefer-template": "error",
|
||||
"prettier/prettier": [
|
||||
"error",
|
||||
{
|
||||
"singleQuote": true,
|
||||
"trailingComma": "es5",
|
||||
"semi": false,
|
||||
"printWidth": 150,
|
||||
"arrowParens": "avoid"
|
||||
}
|
||||
],
|
||||
"mocha/no-exclusive-tests": "error",
|
||||
"mocha/no-hooks-for-single-case": "off",
|
||||
"mocha/no-mocha-arrows": "off",
|
||||
"mocha/no-pending-tests": "error",
|
||||
"mocha/no-setup-in-describe": "off",
|
||||
"strict": [ "error", "never" ],
|
||||
"valid-jsdoc": "off"
|
||||
}
|
||||
}
|
||||
43
.eslintrc.js
Normal file
43
.eslintrc.js
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
module.exports = {
|
||||
env: {
|
||||
es2021: true,
|
||||
node: true,
|
||||
},
|
||||
extends: [
|
||||
'eslint:recommended',
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
],
|
||||
parser: '@typescript-eslint/parser',
|
||||
parserOptions: {
|
||||
ecmaVersion: 12,
|
||||
sourceType: 'module',
|
||||
},
|
||||
plugins: [
|
||||
'@typescript-eslint',
|
||||
],
|
||||
rules: {
|
||||
indent: [
|
||||
'error',
|
||||
2,
|
||||
],
|
||||
'linebreak-style': [
|
||||
'error',
|
||||
'unix',
|
||||
],
|
||||
quotes: [
|
||||
'error',
|
||||
'single',
|
||||
],
|
||||
semi: [
|
||||
'error',
|
||||
'never',
|
||||
],
|
||||
'quote-props': ['error', 'as-needed'],
|
||||
'no-param-reassign': 'error',
|
||||
'comma-dangle': ['error', 'always-multiline'],
|
||||
'space-infix-ops': ['error'],
|
||||
'no-multi-spaces': ['error'],
|
||||
'@typescript-eslint/no-empty-function': ['off'],
|
||||
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
|
||||
},
|
||||
}
|
||||
1
.github/workflows/test.yml
vendored
1
.github/workflows/test.yml
vendored
|
|
@ -12,6 +12,7 @@ jobs:
|
|||
node-version: 14
|
||||
- run: npm ci
|
||||
- run: npm run lint
|
||||
- run: npm run typecheck
|
||||
test:
|
||||
runs-on: ${{ matrix.config.os }}
|
||||
strategy:
|
||||
|
|
|
|||
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -4,3 +4,5 @@ coverage
|
|||
node_modules
|
||||
npm-debug.log
|
||||
prebuilds
|
||||
.tool-versions
|
||||
dist
|
||||
|
|
|
|||
|
|
@ -1,5 +0,0 @@
|
|||
module.exports = {
|
||||
bail: true,
|
||||
require: ['./test/initializers'],
|
||||
'spec': ['lib/**/*.test.js'],
|
||||
}
|
||||
|
|
@ -13,3 +13,7 @@ coverage
|
|||
lib/mocks
|
||||
npm-debug.log
|
||||
test
|
||||
lib/*
|
||||
tsconfig-build.json
|
||||
tsconfig.json
|
||||
.tool-versions
|
||||
|
|
|
|||
42
lib/binding-interface.test.ts
Normal file
42
lib/binding-interface.test.ts
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
import { BindingInterface, OpenOptions, PortStatus, SetOptions, UpdateOptions } from './binding-interface'
|
||||
import { shouldReject } from '../test/assert'
|
||||
|
||||
class Mock extends BindingInterface {
|
||||
isOpen: boolean
|
||||
open(_path: string, _options?: OpenOptions): Promise<void> {
|
||||
throw new Error('Method not implemented.')
|
||||
}
|
||||
close(): Promise<void> {
|
||||
throw new Error('Method not implemented.')
|
||||
}
|
||||
read(_buffer: Buffer, _offset: number, _length: number): Promise<{ buffer: Buffer; bytesRead: number }> {
|
||||
throw new Error('Method not implemented.')
|
||||
}
|
||||
write(_buffer: Buffer): Promise<void> {
|
||||
throw new Error('Method not implemented.')
|
||||
}
|
||||
update(_options: UpdateOptions): Promise<void> {
|
||||
throw new Error('Method not implemented.')
|
||||
}
|
||||
set(_options: SetOptions): Promise<void> {
|
||||
throw new Error('Method not implemented.')
|
||||
}
|
||||
get(): Promise<PortStatus> {
|
||||
throw new Error('Method not implemented.')
|
||||
}
|
||||
getBaudRate(): Promise<{ baudRate: number }> {
|
||||
throw new Error('Method not implemented.')
|
||||
}
|
||||
flush(): Promise<void> {
|
||||
throw new Error('Method not implemented.')
|
||||
}
|
||||
drain(): Promise<void> {
|
||||
throw new Error('Method not implemented.')
|
||||
}
|
||||
}
|
||||
|
||||
describe('BindingInterface', () => {
|
||||
it('throws on unimplemented list', async () => {
|
||||
await shouldReject(Mock.list(), Error, 'List should throw if not implemented')
|
||||
})
|
||||
})
|
||||
135
lib/binding-interface.ts
Normal file
135
lib/binding-interface.ts
Normal file
|
|
@ -0,0 +1,135 @@
|
|||
/**
|
||||
Serial port info with metadata. Only the `path` is guaranteed. If unavailable the other fields will be undefined. The `path` is either the path or an identifier (eg `COM1`) used to open the SerialPort.
|
||||
|
||||
We make an effort to identify the hardware attached and have consistent results between systems. Linux and OS X are mostly consistent. Windows relies on 3rd party device drivers for the information and is unable to guarantee the information. On windows If you have a USB connected device can we provide a serial number otherwise it will be `undefined`. The `pnpId` and `locationId` are not the same or present on all systems. The examples below were run with the same Arduino Uno.
|
||||
*/
|
||||
export interface PortInfo {
|
||||
path: string
|
||||
manufacturer: string | undefined
|
||||
serialNumber: string | undefined
|
||||
pnpId: string | undefined
|
||||
locationId: string | undefined
|
||||
productId: string | undefined
|
||||
vendorId: string | undefined
|
||||
}
|
||||
|
||||
export interface OpenOptions {
|
||||
/** The baud rate of the port to be opened. This should match one of the commonly available baud rates, such as 110, 300, 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, or 115200. Custom rates are supported best effort per platform. The device connected to the serial port is not guaranteed to support the requested baud rate, even if the port itself supports that baud rate. */
|
||||
baudRate: number
|
||||
/** Must be one of these: 8, 7, 6, or 5 */
|
||||
dataBits: 8 | 7 | 6 | 5
|
||||
/** Prevent other processes from opening the port. Windows does not currently support `false`. */
|
||||
lock: boolean
|
||||
stopBits: 1 | 2
|
||||
parity: 'none' | 'event' | 'mark' | 'odd' | 'space'
|
||||
/** Flow control Setting */
|
||||
rtscts: boolean
|
||||
/** Flow control Setting */
|
||||
xon: boolean
|
||||
/** Flow control Setting */
|
||||
xoff: boolean
|
||||
/** Flow control Setting */
|
||||
xany: boolean
|
||||
/** drop DTR on close */
|
||||
hupcl: boolean
|
||||
}
|
||||
|
||||
export interface UpdateOptions {
|
||||
/** If provided a baud rate that the bindings do not support, it should reject */
|
||||
baudRate: number
|
||||
}
|
||||
|
||||
export interface SetOptions {
|
||||
brk?: boolean
|
||||
cts?: boolean
|
||||
dsr?: boolean
|
||||
dtr?: boolean
|
||||
rts?: boolean
|
||||
}
|
||||
|
||||
export interface PortStatus {
|
||||
cts: boolean
|
||||
dsr: boolean
|
||||
dcd: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* You never have to use `Binding` objects directly. SerialPort uses them to access the underlying hardware. This documentation is geared towards people who are making bindings for different platforms. This interface is implemented in all bindings.
|
||||
*/
|
||||
export abstract class BindingInterface {
|
||||
/**
|
||||
Retrieves a list of available serial ports with metadata. The `path` must be guaranteed, and all other fields should be undefined if unavailable. The `path` is either the path or an identifier (eg `COM1`) used to open the serialport.
|
||||
*/
|
||||
static async list(): Promise<PortInfo[]> {
|
||||
throw new Error('Method not implemented.')
|
||||
}
|
||||
|
||||
/**
|
||||
* Required property. `true` if the port is open, `false` otherwise. Should be read-only.
|
||||
*/
|
||||
abstract isOpen: boolean
|
||||
|
||||
/**
|
||||
* Opens a connection to the serial port referenced by the path.
|
||||
*/
|
||||
abstract open(path: string, options?: OpenOptions): Promise<void>
|
||||
|
||||
/**
|
||||
* Closes an open connection
|
||||
*/
|
||||
abstract close(): Promise<void>
|
||||
|
||||
/**
|
||||
Request a number of bytes from the SerialPort. This function is similar to Node's [`fs.read`](http://nodejs.org/api/fs.html#fs_fs_read_fd_buffer_offset_length_position_callback) except it will always return at least one byte.
|
||||
|
||||
The in progress reads must error when the port is closed with an error object that has the property `canceled` equal to `true`. Any other error will cause a disconnection.
|
||||
|
||||
* @param offset The offset in the buffer to start writing at.
|
||||
* @param length Specifies the maximum number of bytes to read.
|
||||
* @returns {Promise} Resolves with the number of bytes read after a read operation.
|
||||
*/
|
||||
abstract read(buffer: Buffer, offset: number, length: number): Promise<{ buffer: Buffer; bytesRead: number }>
|
||||
|
||||
/**
|
||||
Write bytes to the SerialPort. Only called when there is no pending write operation.
|
||||
|
||||
The in progress writes must error when the port is closed with an error object that has the property `canceled` equal to `true`. Any other error will cause a disconnection.
|
||||
|
||||
Resolves after the data is passed to the operating system for writing.
|
||||
*/
|
||||
abstract write(buffer: Buffer): Promise<void>
|
||||
|
||||
/**
|
||||
Changes connection settings on an open port.
|
||||
*/
|
||||
abstract update(options: UpdateOptions): Promise<void>
|
||||
|
||||
/**
|
||||
* Set control flags on an open port.
|
||||
* All options are operating system default when the port is opened. Every flag is set on each call to the provided or default values.
|
||||
*/
|
||||
abstract set(options: SetOptions): Promise<void>
|
||||
|
||||
/**
|
||||
* Get the control flags (CTS, DSR, DCD) on the open port.
|
||||
*/
|
||||
abstract get(): Promise<PortStatus>
|
||||
|
||||
/**
|
||||
* Get the OS reported baud rate for the open port.
|
||||
* Used mostly for debugging custom baud rates.
|
||||
*/
|
||||
abstract getBaudRate(): Promise<{ baudRate: number }>
|
||||
|
||||
/**
|
||||
* Flush (discard) data received but not read, and written but not transmitted.
|
||||
* Resolves once the flush operation finishes.
|
||||
*/
|
||||
abstract flush(): Promise<void>
|
||||
|
||||
/**
|
||||
* Drain waits until all output data is transmitted to the serial port. An in progress write should be completed before this returns.
|
||||
* Resolves once the drain operation finishes.
|
||||
*/
|
||||
abstract drain(): Promise<void>
|
||||
}
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
const serialNumParser = require('./win32-sn-parser')
|
||||
import { assert } from '../test/assert'
|
||||
import { serialNumParser } from './win32-sn-parser'
|
||||
|
||||
const devices = Object.freeze({
|
||||
const devices = {
|
||||
'FTDI Device': {
|
||||
pnpId: 'FTDIBUS\\VID_0403+PID_6015+DO004ZB7A\\0000',
|
||||
serialNumber: 'DO004ZB7',
|
||||
|
|
@ -25,14 +26,17 @@ const devices = Object.freeze({
|
|||
pnpId: 'WATEVER\\Whoever\\However!',
|
||||
serialNumber: null,
|
||||
},
|
||||
})
|
||||
'bad data': {
|
||||
pnpId: undefined,
|
||||
serialNumber: null,
|
||||
},
|
||||
}
|
||||
|
||||
describe('serialNumParser', () => {
|
||||
Object.entries(devices).forEach(([device, info]) => {
|
||||
for (const [device, info] of Object.entries(devices)) {
|
||||
it(`parses pnp id for ${device}`, () => {
|
||||
const pnpId = info.pnpId
|
||||
const serialNumber = info.serialNumber
|
||||
const { pnpId, serialNumber } = info
|
||||
assert.equal(serialNumParser(pnpId), serialNumber)
|
||||
})
|
||||
})
|
||||
}
|
||||
})
|
||||
|
|
@ -1,16 +1,10 @@
|
|||
/* eslint-disable mocha/no-pending-tests */
|
||||
let platform
|
||||
switch (process.platform) {
|
||||
case 'win32':
|
||||
case 'darwin':
|
||||
case 'linux':
|
||||
platform = process.platform
|
||||
break
|
||||
default:
|
||||
throw new Error(`Unknown platform "${process.platform}"`)
|
||||
}
|
||||
import { assert, shouldReject } from '../test/assert'
|
||||
import { makeTestFeature } from '../test/makeTestFeature'
|
||||
import { BindingInterface, OpenOptions, PortInfo, SetOptions } from './binding-interface'
|
||||
import Binding, { AllBindingClasses } from './index'
|
||||
import MockBinding from '@serialport/binding-mock'
|
||||
|
||||
const defaultOpenOptions = Object.freeze({
|
||||
const defaultOpenOptions: OpenOptions = Object.freeze({
|
||||
baudRate: 9600,
|
||||
dataBits: 8,
|
||||
hupcl: true,
|
||||
|
|
@ -23,7 +17,7 @@ const defaultOpenOptions = Object.freeze({
|
|||
xon: false,
|
||||
})
|
||||
|
||||
const defaultSetFlags = Object.freeze({
|
||||
const defaultSetFlags: SetOptions = Object.freeze({
|
||||
brk: false,
|
||||
cts: false,
|
||||
dtr: true,
|
||||
|
|
@ -32,9 +26,9 @@ const defaultSetFlags = Object.freeze({
|
|||
lowLatency: false,
|
||||
})
|
||||
|
||||
const listFields = ['path', 'manufacturer', 'serialNumber', 'pnpId', 'locationId', 'vendorId', 'productId']
|
||||
type MockBinding = any
|
||||
|
||||
const bindingsToTest = ['mock', platform]
|
||||
const listFields = ['path', 'manufacturer', 'serialNumber', 'pnpId', 'locationId', 'vendorId', 'productId']
|
||||
|
||||
// All bindings are required to work with an "echo" firmware
|
||||
// The echo firmware should respond with this data when it's
|
||||
|
|
@ -42,32 +36,23 @@ const bindingsToTest = ['mock', platform]
|
|||
// the default firmware is called arduinoEcho.ino
|
||||
const readyData = Buffer.from('READY')
|
||||
|
||||
// Test our mock binding and the binding for the platform we're running on
|
||||
bindingsToTest.forEach(bindingName => {
|
||||
const Binding = bindingName === 'mock' ? require('@serialport/binding-mock') : require(`./${bindingName}`)
|
||||
let testPort = process.env.TEST_PORT
|
||||
testBinding('mock', MockBinding, '/dev/exists')
|
||||
testBinding(process.platform, Binding, process.env.TEST_PORT)
|
||||
|
||||
if (bindingName === 'mock') {
|
||||
testPort = '/dev/exists'
|
||||
}
|
||||
|
||||
// eslint-disable-next-line no-use-before-define
|
||||
testBinding(bindingName, Binding, testPort)
|
||||
})
|
||||
|
||||
function testBinding(bindingName, Binding, testPort) {
|
||||
const testFeature = makeTestFeature(bindingName)
|
||||
function testBinding(bindingName: string, Binding: AllBindingClasses, testPort?: string) {
|
||||
const { testFeature, testHardware, describeHardware } = makeTestFeature(bindingName, testPort)
|
||||
|
||||
describe(`bindings/${bindingName}`, () => {
|
||||
before(() => {
|
||||
if (bindingName === 'mock') {
|
||||
Binding.createPort(testPort, { echo: true, readyData })
|
||||
(Binding as MockBinding).createPort(testPort, { echo: true, readyData })
|
||||
}
|
||||
})
|
||||
|
||||
describe('static method', () => {
|
||||
describe('.list', () => {
|
||||
it('returns an array', async () => {
|
||||
console.log({ Binding })
|
||||
const ports = await Binding.list()
|
||||
assert.isArray(ports)
|
||||
})
|
||||
|
|
@ -81,11 +66,10 @@ function testBinding(bindingName, Binding, testPort) {
|
|||
}
|
||||
ports.forEach(port => {
|
||||
assert.containSubset(Object.keys(port), listFields)
|
||||
Object.keys(port).forEach(key => {
|
||||
Object.keys(port).forEach((key: keyof PortInfo) => {
|
||||
assert.notEqual(port[key], '', 'empty values should be undefined')
|
||||
assert.isNotNull(port[key], 'empty values should be undefined')
|
||||
})
|
||||
assert.equal(port.comName, port.path)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
|
@ -96,16 +80,6 @@ function testBinding(bindingName, Binding, testPort) {
|
|||
const binding = new Binding()
|
||||
assert.instanceOf(binding, Binding)
|
||||
})
|
||||
|
||||
it('throws when given something weird', () => {
|
||||
try {
|
||||
new Binding(4)
|
||||
} catch (e) {
|
||||
assert.instanceOf(e, TypeError)
|
||||
return
|
||||
}
|
||||
throw new Error('Should have errored')
|
||||
})
|
||||
})
|
||||
|
||||
describe('instance property', () => {
|
||||
|
|
@ -115,26 +89,24 @@ function testBinding(bindingName, Binding, testPort) {
|
|||
return
|
||||
}
|
||||
|
||||
let binding
|
||||
let binding: BindingInterface
|
||||
beforeEach(() => {
|
||||
binding = new Binding()
|
||||
})
|
||||
|
||||
it('is true after open and false after close', () => {
|
||||
it('is true after open and false after close', async () => {
|
||||
assert.equal(binding.isOpen, false)
|
||||
await binding.open(testPort, defaultOpenOptions)
|
||||
assert.equal(binding.isOpen, true)
|
||||
await binding.close()
|
||||
assert.equal(binding.isOpen, false)
|
||||
return binding.open(testPort, defaultOpenOptions).then(() => {
|
||||
assert.equal(binding.isOpen, true)
|
||||
return binding.close().then(() => {
|
||||
assert.equal(binding.isOpen, false)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('instance method', () => {
|
||||
describe('#open', () => {
|
||||
let binding
|
||||
let binding: BindingInterface
|
||||
beforeEach(() => {
|
||||
binding = new Binding()
|
||||
})
|
||||
|
|
@ -158,21 +130,23 @@ function testBinding(bindingName, Binding, testPort) {
|
|||
return
|
||||
}
|
||||
|
||||
it('cannot open if already open', async () => {
|
||||
const options = { ...defaultOpenOptions, lock: false }
|
||||
await binding.open(testPort, options)
|
||||
await shouldReject(binding.open(testPort, options))
|
||||
await binding.close()
|
||||
describeHardware('with hardware', () => {
|
||||
it('cannot open if already open', async () => {
|
||||
const options = { ...defaultOpenOptions, lock: false }
|
||||
await binding.open(testPort, options)
|
||||
await shouldReject(binding.open(testPort, options))
|
||||
await binding.close()
|
||||
})
|
||||
|
||||
it('keeps open state', async () => {
|
||||
await binding.open(testPort, defaultOpenOptions)
|
||||
assert.equal(binding.isOpen, true)
|
||||
await binding.close()
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps open state', async () => {
|
||||
await binding.open(testPort, defaultOpenOptions)
|
||||
assert.equal(binding.isOpen, true)
|
||||
await binding.close()
|
||||
})
|
||||
|
||||
describe('arbitrary baud rates', () => {
|
||||
;[25000, 1000000, 250000].forEach(testBaud => {
|
||||
describeHardware('arbitrary baud rates', () => {
|
||||
[25000, 1000000, 250000].forEach(testBaud => {
|
||||
describe(`${testBaud} baud`, () => {
|
||||
const customRates = { ...defaultOpenOptions, baudRate: testBaud }
|
||||
testFeature(`baudrate.${testBaud}`, `opens at ${testBaud} baud`, async () => {
|
||||
|
|
@ -191,7 +165,7 @@ function testBinding(bindingName, Binding, testPort) {
|
|||
})
|
||||
})
|
||||
|
||||
describe('optional locking', () => {
|
||||
describeHardware('optional locking', () => {
|
||||
it('locks the port by default', async () => {
|
||||
const binding2 = new Binding()
|
||||
await binding.open(testPort, defaultOpenOptions)
|
||||
|
|
@ -217,7 +191,7 @@ function testBinding(bindingName, Binding, testPort) {
|
|||
})
|
||||
|
||||
describe('#close', () => {
|
||||
let binding
|
||||
let binding: BindingInterface
|
||||
beforeEach(() => {
|
||||
binding = new Binding()
|
||||
})
|
||||
|
|
@ -226,13 +200,8 @@ function testBinding(bindingName, Binding, testPort) {
|
|||
await shouldReject(binding.close())
|
||||
})
|
||||
|
||||
if (!testPort) {
|
||||
it('Cannot be tested further. Set the TEST_PORT env var with an available serialport for more testing.')
|
||||
return
|
||||
}
|
||||
|
||||
it('closes an open file descriptor', () => {
|
||||
return binding.open(testPort, defaultOpenOptions).then(() => {
|
||||
testHardware('closes an open file descriptor', () => {
|
||||
return binding.open(testPort!, defaultOpenOptions).then(() => {
|
||||
assert.equal(binding.isOpen, true)
|
||||
return binding.close()
|
||||
})
|
||||
|
|
@ -242,7 +211,7 @@ function testBinding(bindingName, Binding, testPort) {
|
|||
describe('#update', () => {
|
||||
it('throws when not given an object', async () => {
|
||||
const binding = new Binding()
|
||||
await shouldReject(binding.update(), TypeError)
|
||||
await shouldReject((binding as any).update(), TypeError)
|
||||
})
|
||||
|
||||
it('errors asynchronously when not open', done => {
|
||||
|
|
@ -256,32 +225,29 @@ function testBinding(bindingName, Binding, testPort) {
|
|||
noZalgo = true
|
||||
})
|
||||
|
||||
if (!testPort) {
|
||||
it('Cannot be tested further. Set the TEST_PORT env var with an available serialport for more testing.')
|
||||
return
|
||||
}
|
||||
describeHardware('update with hardware', () => {
|
||||
let binding: BindingInterface
|
||||
beforeEach(() => {
|
||||
binding = new Binding()
|
||||
return binding.open(testPort!, defaultOpenOptions)
|
||||
})
|
||||
|
||||
let binding
|
||||
beforeEach(() => {
|
||||
binding = new Binding()
|
||||
return binding.open(testPort, defaultOpenOptions)
|
||||
})
|
||||
afterEach(() => binding.close())
|
||||
|
||||
afterEach(() => binding.close())
|
||||
it('throws errors when updating nothing', async () => {
|
||||
await shouldReject((binding as any).update({}), Error)
|
||||
})
|
||||
|
||||
it('throws errors when updating nothing', async () => {
|
||||
await shouldReject(binding.update({}), Error)
|
||||
})
|
||||
it('errors when not called with options', async () => {
|
||||
await shouldReject(
|
||||
(binding as any).set(() => { }),
|
||||
Error,
|
||||
)
|
||||
})
|
||||
|
||||
it('errors when not called with options', async () => {
|
||||
await shouldReject(
|
||||
binding.set(() => {}),
|
||||
Error
|
||||
)
|
||||
})
|
||||
|
||||
it('updates baudRate', () => {
|
||||
return binding.update({ baudRate: 57600 })
|
||||
it('updates baudRate', () => {
|
||||
return binding.update({ baudRate: 57600 })
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
|
|
@ -300,7 +266,7 @@ function testBinding(bindingName, Binding, testPort) {
|
|||
assert.instanceOf(err, Error)
|
||||
assert(noZalgo)
|
||||
done()
|
||||
}
|
||||
},
|
||||
)
|
||||
.catch(done)
|
||||
noZalgo = true
|
||||
|
|
@ -308,36 +274,33 @@ function testBinding(bindingName, Binding, testPort) {
|
|||
|
||||
it('rejects when not given a buffer', async () => {
|
||||
const binding = new Binding()
|
||||
await shouldReject(binding.write(null), TypeError)
|
||||
await shouldReject((binding as any).write(null), TypeError)
|
||||
})
|
||||
|
||||
if (!testPort) {
|
||||
it(`Cannot be tested as we have no test ports on ${platform}`)
|
||||
return
|
||||
}
|
||||
describeHardware('with hardware', () => {
|
||||
let binding: BindingInterface
|
||||
beforeEach(() => {
|
||||
binding = new Binding()
|
||||
return binding.open(testPort!, defaultOpenOptions)
|
||||
})
|
||||
|
||||
let binding
|
||||
beforeEach(() => {
|
||||
binding = new Binding()
|
||||
return binding.open(testPort, defaultOpenOptions)
|
||||
})
|
||||
afterEach(() => binding.close())
|
||||
|
||||
afterEach(() => binding.close())
|
||||
it('resolves after a small write', () => {
|
||||
const data = Buffer.from('simple write of 24 bytes')
|
||||
return binding.write(data)
|
||||
})
|
||||
|
||||
it('resolves after a small write', () => {
|
||||
const data = Buffer.from('simple write of 24 bytes')
|
||||
return binding.write(data)
|
||||
})
|
||||
it('resolves after a large write (2k)', function () {
|
||||
this.timeout(20000)
|
||||
const data = Buffer.alloc(1024 * 2)
|
||||
return binding.write(data)
|
||||
})
|
||||
|
||||
it('resolves after a large write (2k)', function () {
|
||||
this.timeout(20000)
|
||||
const data = Buffer.alloc(1024 * 2)
|
||||
return binding.write(data)
|
||||
})
|
||||
|
||||
it('resolves after an empty write', () => {
|
||||
const data = Buffer.from([])
|
||||
return binding.write(data)
|
||||
it('resolves after an empty write', () => {
|
||||
const data = Buffer.from([])
|
||||
return binding.write(data)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
|
|
@ -358,7 +321,7 @@ function testBinding(bindingName, Binding, testPort) {
|
|||
return
|
||||
}
|
||||
|
||||
let binding
|
||||
let binding: BindingInterface
|
||||
beforeEach(() => {
|
||||
binding = new Binding()
|
||||
return binding.open(testPort, defaultOpenOptions)
|
||||
|
|
@ -370,20 +333,14 @@ function testBinding(bindingName, Binding, testPort) {
|
|||
return binding.drain()
|
||||
})
|
||||
|
||||
it('waits for in progress writes to finish', function (done) {
|
||||
this.timeout(10000)
|
||||
it('waits for in progress writes to finish', async () => {
|
||||
let finishedWrite = false
|
||||
binding
|
||||
.write(Buffer.alloc(1024 * 2))
|
||||
.then(() => {
|
||||
finishedWrite = true
|
||||
})
|
||||
.catch(done)
|
||||
binding
|
||||
.drain(() => {
|
||||
assert.isTrue(finishedWrite)
|
||||
})
|
||||
.then(done, done)
|
||||
const write = binding.write(Buffer.alloc(1024 * 2)).then(() => {
|
||||
finishedWrite = true
|
||||
})
|
||||
await binding.drain()
|
||||
assert.isTrue(finishedWrite)
|
||||
await write
|
||||
})
|
||||
})
|
||||
|
||||
|
|
@ -404,7 +361,7 @@ function testBinding(bindingName, Binding, testPort) {
|
|||
return
|
||||
}
|
||||
|
||||
let binding
|
||||
let binding: BindingInterface
|
||||
beforeEach(() => {
|
||||
binding = new Binding()
|
||||
return binding.open(testPort, defaultOpenOptions)
|
||||
|
|
@ -432,8 +389,8 @@ function testBinding(bindingName, Binding, testPort) {
|
|||
it('throws when not called with options', async () => {
|
||||
const binding = new Binding()
|
||||
await shouldReject(
|
||||
binding.set(() => {}),
|
||||
TypeError
|
||||
(binding as any).set(() => { }),
|
||||
TypeError,
|
||||
)
|
||||
})
|
||||
|
||||
|
|
@ -442,7 +399,7 @@ function testBinding(bindingName, Binding, testPort) {
|
|||
return
|
||||
}
|
||||
|
||||
let binding
|
||||
let binding: BindingInterface
|
||||
beforeEach(() => {
|
||||
binding = new Binding()
|
||||
return binding.open(testPort, defaultOpenOptions)
|
||||
|
|
@ -475,7 +432,8 @@ function testBinding(bindingName, Binding, testPort) {
|
|||
return
|
||||
}
|
||||
|
||||
let binding, buffer
|
||||
let binding: BindingInterface
|
||||
let buffer: Buffer
|
||||
beforeEach(async () => {
|
||||
buffer = Buffer.alloc(readyData.length)
|
||||
binding = new Binding()
|
||||
|
|
@ -484,7 +442,7 @@ function testBinding(bindingName, Binding, testPort) {
|
|||
|
||||
afterEach(() => binding.isOpen && binding.close())
|
||||
|
||||
it("doesn't throw if the port is open", async () => {
|
||||
it('doesn\'t throw if the port is open', async () => {
|
||||
await binding.read(buffer, 0, buffer.length)
|
||||
})
|
||||
|
||||
|
|
@ -524,7 +482,7 @@ function testBinding(bindingName, Binding, testPort) {
|
|||
return
|
||||
}
|
||||
|
||||
let binding
|
||||
let binding: BindingInterface
|
||||
beforeEach(() => {
|
||||
binding = new Binding()
|
||||
return binding.open(testPort, defaultOpenOptions)
|
||||
111
lib/darwin.js
111
lib/darwin.js
|
|
@ -1,111 +0,0 @@
|
|||
const { promisify } = require('util')
|
||||
const { join } = require('path')
|
||||
const binding = require('node-gyp-build')(join(__dirname, '../'))
|
||||
const AbstractBinding = require('@serialport/binding-abstract')
|
||||
const Poller = require('./poller')
|
||||
const unixRead = require('./unix-read')
|
||||
const unixWrite = require('./unix-write')
|
||||
const { wrapWithHiddenComName } = require('./legacy')
|
||||
|
||||
const defaultBindingOptions = Object.freeze({
|
||||
vmin: 1,
|
||||
vtime: 0,
|
||||
})
|
||||
|
||||
const asyncList = promisify(binding.list)
|
||||
const asyncOpen = promisify(binding.open)
|
||||
const asyncClose = promisify(binding.close)
|
||||
const asyncUpdate = promisify(binding.update)
|
||||
const asyncSet = promisify(binding.set)
|
||||
const asyncGet = promisify(binding.get)
|
||||
const asyncGetBaudRate = promisify(binding.getBaudRate)
|
||||
const asyncDrain = promisify(binding.drain)
|
||||
const asyncFlush = promisify(binding.flush)
|
||||
|
||||
/**
|
||||
* The Darwin binding layer for OSX
|
||||
*/
|
||||
class DarwinBinding extends AbstractBinding {
|
||||
static list() {
|
||||
return wrapWithHiddenComName(asyncList())
|
||||
}
|
||||
|
||||
constructor(opt = {}) {
|
||||
super(opt)
|
||||
this.bindingOptions = { ...defaultBindingOptions, ...opt.bindingOptions }
|
||||
this.fd = null
|
||||
this.writeOperation = null
|
||||
}
|
||||
|
||||
get isOpen() {
|
||||
return this.fd !== null
|
||||
}
|
||||
|
||||
async open(path, options) {
|
||||
await super.open(path, options)
|
||||
this.openOptions = { ...this.bindingOptions, ...options }
|
||||
const fd = await asyncOpen(path, this.openOptions)
|
||||
this.fd = fd
|
||||
this.poller = new Poller(fd)
|
||||
}
|
||||
|
||||
async close() {
|
||||
await super.close()
|
||||
const fd = this.fd
|
||||
this.poller.stop()
|
||||
this.poller.destroy()
|
||||
this.poller = null
|
||||
this.openOptions = null
|
||||
this.fd = null
|
||||
return asyncClose(fd)
|
||||
}
|
||||
|
||||
async read(buffer, offset, length) {
|
||||
await super.read(buffer, offset, length)
|
||||
return unixRead({ binding: this, buffer, offset, length })
|
||||
}
|
||||
|
||||
async write(buffer) {
|
||||
this.writeOperation = super.write(buffer).then(async () => {
|
||||
if (buffer.length === 0) {
|
||||
return
|
||||
}
|
||||
await unixWrite({ binding: this, buffer })
|
||||
this.writeOperation = null
|
||||
})
|
||||
return this.writeOperation
|
||||
}
|
||||
|
||||
async update(options) {
|
||||
await super.update(options)
|
||||
return asyncUpdate(this.fd, options)
|
||||
}
|
||||
|
||||
async set(options) {
|
||||
await super.set(options)
|
||||
return asyncSet(this.fd, options)
|
||||
}
|
||||
|
||||
async get() {
|
||||
await super.get()
|
||||
return asyncGet(this.fd)
|
||||
}
|
||||
|
||||
async getBaudRate() {
|
||||
await super.get()
|
||||
return asyncGetBaudRate(this.fd)
|
||||
}
|
||||
|
||||
async drain() {
|
||||
await super.drain()
|
||||
await this.writeOperation
|
||||
return asyncDrain(this.fd)
|
||||
}
|
||||
|
||||
async flush() {
|
||||
await super.flush()
|
||||
return asyncFlush(this.fd)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = DarwinBinding
|
||||
195
lib/darwin.ts
Normal file
195
lib/darwin.ts
Normal file
|
|
@ -0,0 +1,195 @@
|
|||
import debugFactory from 'debug'
|
||||
import { BindingInterface, OpenOptions, PortInfo, PortStatus, SetOptions, UpdateOptions } from './binding-interface'
|
||||
import { asyncClose, asyncDrain, asyncFlush, asyncGet, asyncGetBaudRate, asyncList, asyncOpen, asyncSet, asyncUpdate } from './load-bindings'
|
||||
import { Poller } from './poller'
|
||||
import { unixRead } from './unix-read'
|
||||
import { unixWrite } from './unix-write'
|
||||
|
||||
const debug = debugFactory('serialport/bindings-cpp')
|
||||
|
||||
export interface DarwinBindingOptions {
|
||||
/** see [`man termios`](http://linux.die.net/man/3/termios) defaults to 1 */
|
||||
vmin?: number
|
||||
/** see [`man termios`](http://linux.die.net/man/3/termios) defaults to 0 */
|
||||
vtime?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* The Darwin binding layer for OSX
|
||||
*/
|
||||
export class DarwinBinding extends BindingInterface {
|
||||
bindingOptions: DarwinBindingOptions
|
||||
fd: null | number
|
||||
writeOperation: Promise<void> | null
|
||||
openOptions: (DarwinBindingOptions & OpenOptions) | null
|
||||
poller: Poller | null
|
||||
|
||||
static async list(): Promise<PortInfo[]> {
|
||||
debug('list')
|
||||
return asyncList()
|
||||
}
|
||||
|
||||
constructor(opt?: DarwinBindingOptions) {
|
||||
super()
|
||||
this.bindingOptions = {
|
||||
vmin: 1,
|
||||
vtime: 0,
|
||||
...opt,
|
||||
}
|
||||
this.fd = null
|
||||
this.writeOperation = null
|
||||
}
|
||||
|
||||
get isOpen() {
|
||||
return this.fd !== null
|
||||
}
|
||||
|
||||
async open(path: string, options?: OpenOptions) {
|
||||
if (!path) {
|
||||
throw new TypeError('"path" is not a valid port')
|
||||
}
|
||||
|
||||
if (typeof options !== 'object') {
|
||||
throw new TypeError('"options" is not an object')
|
||||
}
|
||||
debug('open')
|
||||
|
||||
if (this.isOpen) {
|
||||
throw new Error('Already open')
|
||||
}
|
||||
|
||||
this.openOptions = { ...this.bindingOptions, ...options }
|
||||
const fd: number = await asyncOpen(path, this.openOptions)
|
||||
this.fd = fd
|
||||
this.poller = new Poller(fd)
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
debug('close')
|
||||
if (!this.isOpen) {
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
|
||||
const fd = this.fd
|
||||
this.poller?.stop()
|
||||
this.poller?.destroy()
|
||||
this.poller = null
|
||||
this.openOptions = null
|
||||
this.fd = null
|
||||
await asyncClose(fd)
|
||||
}
|
||||
|
||||
async read(
|
||||
buffer: Buffer,
|
||||
offset: number,
|
||||
length: number,
|
||||
): Promise<{
|
||||
buffer: Buffer
|
||||
bytesRead: number
|
||||
}> {
|
||||
if (!Buffer.isBuffer(buffer)) {
|
||||
throw new TypeError('"buffer" is not a Buffer')
|
||||
}
|
||||
|
||||
if (typeof offset !== 'number' || isNaN(offset)) {
|
||||
throw new TypeError(`"offset" is not an integer got "${isNaN(offset) ? 'NaN' : typeof offset}"`)
|
||||
}
|
||||
|
||||
if (typeof length !== 'number' || isNaN(length)) {
|
||||
throw new TypeError(`"length" is not an integer got "${isNaN(length) ? 'NaN' : typeof length}"`)
|
||||
}
|
||||
|
||||
debug('read')
|
||||
if (buffer.length < offset + length) {
|
||||
throw new Error('buffer is too small')
|
||||
}
|
||||
|
||||
if (!this.isOpen) {
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
|
||||
return unixRead({ binding: this, buffer, offset, length })
|
||||
}
|
||||
|
||||
async write(buffer: Buffer): Promise<void> {
|
||||
if (!Buffer.isBuffer(buffer)) {
|
||||
throw new TypeError('"buffer" is not a Buffer')
|
||||
}
|
||||
|
||||
debug('write', buffer.length, 'bytes')
|
||||
if (!this.isOpen) {
|
||||
debug('write', 'error port is not open')
|
||||
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
|
||||
this.writeOperation = (async () => {
|
||||
if (buffer.length === 0) {
|
||||
return
|
||||
}
|
||||
await unixWrite({ binding: this, buffer })
|
||||
this.writeOperation = null
|
||||
})()
|
||||
return this.writeOperation
|
||||
}
|
||||
|
||||
async update(options: UpdateOptions): Promise<void> {
|
||||
if (typeof options !== 'object') {
|
||||
throw TypeError('"options" is not an object')
|
||||
}
|
||||
|
||||
if (typeof options.baudRate !== 'number') {
|
||||
throw new TypeError('"options.baudRate" is not a number')
|
||||
}
|
||||
|
||||
debug('update')
|
||||
if (!this.isOpen) {
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
await asyncUpdate(this.fd, options)
|
||||
}
|
||||
|
||||
async set(options: SetOptions): Promise<void> {
|
||||
if (typeof options !== 'object') {
|
||||
throw new TypeError('"options" is not an object')
|
||||
}
|
||||
debug('set', options)
|
||||
if (!this.isOpen) {
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
await asyncSet(this.fd, options)
|
||||
}
|
||||
|
||||
async get(): Promise<PortStatus> {
|
||||
debug('get')
|
||||
if (!this.isOpen) {
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
return asyncGet(this.fd)
|
||||
}
|
||||
|
||||
async getBaudRate(): Promise<{ baudRate: number }> {
|
||||
debug('getBaudRate')
|
||||
if (!this.isOpen) {
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
return asyncGetBaudRate(this.fd)
|
||||
}
|
||||
|
||||
async flush(): Promise<void> {
|
||||
debug('flush')
|
||||
if (!this.isOpen) {
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
await asyncFlush(this.fd)
|
||||
}
|
||||
|
||||
async drain(): Promise<void> {
|
||||
debug('drain')
|
||||
if (!this.isOpen) {
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
await this.writeOperation
|
||||
await asyncDrain(this.fd)
|
||||
}
|
||||
}
|
||||
7
lib/errors.ts
Normal file
7
lib/errors.ts
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
export class CanceledError extends Error {
|
||||
canceled: true
|
||||
constructor(message: string) {
|
||||
super(message)
|
||||
this.canceled = true
|
||||
}
|
||||
}
|
||||
15
lib/index.js
15
lib/index.js
|
|
@ -1,15 +0,0 @@
|
|||
const debug = require('debug')('serialport/bindings')
|
||||
|
||||
switch (process.platform) {
|
||||
case 'win32':
|
||||
debug('loading WindowsBinding')
|
||||
module.exports = require('./win32')
|
||||
break
|
||||
case 'darwin':
|
||||
debug('loading DarwinBinding')
|
||||
module.exports = require('./darwin')
|
||||
break
|
||||
default:
|
||||
debug('loading LinuxBinding')
|
||||
module.exports = require('./linux')
|
||||
}
|
||||
30
lib/index.ts
Normal file
30
lib/index.ts
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
/* eslint-disable @typescript-eslint/no-var-requires */
|
||||
import debugFactory from 'debug'
|
||||
import { DarwinBinding } from './darwin'
|
||||
import { LinuxBinding } from './linux'
|
||||
import { WindowsBinding } from './win32'
|
||||
const debug = debugFactory('serialport/bindings-cpp')
|
||||
|
||||
export * from './darwin'
|
||||
export * from './linux'
|
||||
export * from './win32'
|
||||
export * from './binding-interface'
|
||||
|
||||
export type AllBindingClasses = typeof WindowsBinding | typeof DarwinBinding | typeof LinuxBinding
|
||||
export type AllBindings = WindowsBinding | DarwinBinding | LinuxBinding
|
||||
let binding: AllBindingClasses
|
||||
switch (process.platform) {
|
||||
case 'win32':
|
||||
debug('loading WindowsBinding')
|
||||
binding = WindowsBinding
|
||||
break
|
||||
case 'darwin':
|
||||
debug('loading DarwinBinding')
|
||||
binding = DarwinBinding
|
||||
break
|
||||
default:
|
||||
debug('loading LinuxBinding')
|
||||
binding = LinuxBinding
|
||||
}
|
||||
|
||||
export default binding
|
||||
|
|
@ -1,26 +0,0 @@
|
|||
let warningSent = false
|
||||
|
||||
const wrapWithHiddenComName = async portsPromise => {
|
||||
const ports = await portsPromise
|
||||
return ports.map(port => {
|
||||
const newPort = { ...port }
|
||||
return Object.defineProperties(newPort, {
|
||||
comName: {
|
||||
get() {
|
||||
if (!warningSent) {
|
||||
warningSent = true
|
||||
console.warn(
|
||||
`"PortInfo.comName" has been deprecated. You should now use "PortInfo.path". The property will be removed in the next major release.`
|
||||
)
|
||||
}
|
||||
return newPort.path
|
||||
},
|
||||
enumerable: false,
|
||||
},
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
wrapWithHiddenComName,
|
||||
}
|
||||
|
|
@ -1,100 +0,0 @@
|
|||
const childProcess = require('child_process')
|
||||
const Readline = require('@serialport/parser-readline')
|
||||
|
||||
// get only serial port names
|
||||
function checkPathOfDevice(path) {
|
||||
return /(tty(S|WCH|ACM|USB|AMA|MFD|O|XRUSB)|rfcomm)/.test(path) && path
|
||||
}
|
||||
|
||||
function propName(name) {
|
||||
return {
|
||||
DEVNAME: 'path',
|
||||
ID_VENDOR_ENC: 'manufacturer',
|
||||
ID_SERIAL_SHORT: 'serialNumber',
|
||||
ID_VENDOR_ID: 'vendorId',
|
||||
ID_MODEL_ID: 'productId',
|
||||
DEVLINKS: 'pnpId',
|
||||
}[name.toUpperCase()]
|
||||
}
|
||||
|
||||
function decodeHexEscape(str) {
|
||||
return str.replace(/\\x([a-fA-F0-9]{2})/g, (a, b) => {
|
||||
return String.fromCharCode(parseInt(b, 16))
|
||||
})
|
||||
}
|
||||
|
||||
function propVal(name, val) {
|
||||
if (name === 'pnpId') {
|
||||
const match = val.match(/\/by-id\/([^\s]+)/)
|
||||
return (match && match[1]) || undefined
|
||||
}
|
||||
if (name === 'manufacturer') {
|
||||
return decodeHexEscape(val)
|
||||
}
|
||||
if (/^0x/.test(val)) {
|
||||
return val.substr(2)
|
||||
}
|
||||
return val
|
||||
}
|
||||
|
||||
function listLinux() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const ports = []
|
||||
const ude = childProcess.spawn('udevadm', ['info', '-e'])
|
||||
const lines = ude.stdout.pipe(new Readline())
|
||||
ude.on('close', code => code && reject(new Error(`Error listing ports udevadm exited with error code: ${code}`)))
|
||||
ude.on('error', reject)
|
||||
lines.on('error', reject)
|
||||
|
||||
let port = {}
|
||||
let skipPort = false
|
||||
lines.on('data', line => {
|
||||
const lineType = line.slice(0, 1)
|
||||
const data = line.slice(3)
|
||||
// new port entry
|
||||
if (lineType === 'P') {
|
||||
port = {
|
||||
manufacturer: undefined,
|
||||
serialNumber: undefined,
|
||||
pnpId: undefined,
|
||||
locationId: undefined,
|
||||
vendorId: undefined,
|
||||
productId: undefined,
|
||||
}
|
||||
skipPort = false
|
||||
return
|
||||
}
|
||||
|
||||
if (skipPort) {
|
||||
return
|
||||
}
|
||||
|
||||
// Check dev name and save port if it matches flag to skip the rest of the data if not
|
||||
if (lineType === 'N') {
|
||||
if (checkPathOfDevice(data)) {
|
||||
ports.push(port)
|
||||
} else {
|
||||
skipPort = true
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// parse data about each port
|
||||
if (lineType === 'E') {
|
||||
const keyValue = data.match(/^(.+)=(.*)/)
|
||||
if (!keyValue) {
|
||||
return
|
||||
}
|
||||
const key = propName(keyValue[1])
|
||||
if (!key) {
|
||||
return
|
||||
}
|
||||
port[key] = propVal(key, keyValue[2])
|
||||
}
|
||||
})
|
||||
|
||||
lines.on('finish', () => resolve(ports))
|
||||
})
|
||||
}
|
||||
|
||||
module.exports = listLinux
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
const listLinux = require('./mocks/linux-list')
|
||||
import { assert, shouldReject } from '../test/assert'
|
||||
import { mockLinuxList as linuxList, mockLinuxListError } from './mocks/linux-list'
|
||||
|
||||
const ports = String.raw`
|
||||
const mockUdevOutput = String.raw`
|
||||
P: /devices/platform/serial8250/tty/ttyS0
|
||||
N: ttyS0
|
||||
E: DEVNAME=/dev/ttyS0
|
||||
|
|
@ -103,28 +104,13 @@ const portOutput = [
|
|||
]
|
||||
|
||||
describe('listLinux', () => {
|
||||
beforeEach(() => {
|
||||
listLinux.reset()
|
||||
it('lists available serialports', async () => {
|
||||
const ports = await linuxList(mockUdevOutput)
|
||||
assert.containSubset(ports, portOutput)
|
||||
})
|
||||
|
||||
it('lists available serialports', () => {
|
||||
listLinux.setPorts(ports)
|
||||
return listLinux().then(ports => {
|
||||
assert.containSubset(ports, portOutput)
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects on non-zero exit codes', () => {
|
||||
const list = listLinux()
|
||||
listLinux.emit('close', 1)
|
||||
|
||||
list.then(
|
||||
() => {
|
||||
assert.fail('should not resolve for non-zero exit codes')
|
||||
},
|
||||
error => {
|
||||
assert(error, new Error('Error listing ports udevadm exited with error code: 1'))
|
||||
}
|
||||
)
|
||||
it('rejects on non-zero exit codes', async () => {
|
||||
const list = mockLinuxListError('1')
|
||||
await shouldReject(list, Error, 'Error listing ports udevadm exited with error code: 1')
|
||||
})
|
||||
})
|
||||
115
lib/linux-list.ts
Normal file
115
lib/linux-list.ts
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
import { PortInfo } from './binding-interface'
|
||||
|
||||
import { spawn } from 'child_process'
|
||||
import Readline from '@serialport/parser-readline'
|
||||
|
||||
// get only serial port names
|
||||
function checkPathOfDevice(path: string) {
|
||||
return /(tty(S|WCH|ACM|USB|AMA|MFD|O|XRUSB)|rfcomm)/.test(path) && path
|
||||
}
|
||||
|
||||
function propName(name: string) {
|
||||
return {
|
||||
DEVNAME: 'path',
|
||||
ID_VENDOR_ENC: 'manufacturer',
|
||||
ID_SERIAL_SHORT: 'serialNumber',
|
||||
ID_VENDOR_ID: 'vendorId',
|
||||
ID_MODEL_ID: 'productId',
|
||||
DEVLINKS: 'pnpId',
|
||||
}[name.toUpperCase()]
|
||||
}
|
||||
|
||||
function decodeHexEscape(str: string) {
|
||||
return str.replace(/\\x([a-fA-F0-9]{2})/g, (a, b) => {
|
||||
return String.fromCharCode(parseInt(b, 16))
|
||||
})
|
||||
}
|
||||
|
||||
function propVal(name: string, val: string) {
|
||||
if (name === 'pnpId') {
|
||||
const match = val.match(/\/by-id\/([^\s]+)/)
|
||||
return (match && match[1]) || undefined
|
||||
}
|
||||
if (name === 'manufacturer') {
|
||||
return decodeHexEscape(val)
|
||||
}
|
||||
if (/^0x/.test(val)) {
|
||||
return val.substr(2)
|
||||
}
|
||||
return val
|
||||
}
|
||||
|
||||
export function linuxList(spawnCmd: typeof spawn = spawn) {
|
||||
const ports: PortInfo[] = []
|
||||
const udevadm = spawnCmd('udevadm', ['info', '-e'])
|
||||
const lines = udevadm.stdout.pipe(new Readline())
|
||||
|
||||
let skipPort = false
|
||||
let port: PortInfo = {
|
||||
path: '',
|
||||
manufacturer: undefined,
|
||||
serialNumber: undefined,
|
||||
pnpId: undefined,
|
||||
locationId: undefined,
|
||||
vendorId: undefined,
|
||||
productId: undefined,
|
||||
}
|
||||
|
||||
lines.on('data', (line: string) => {
|
||||
const lineType = line.slice(0, 1)
|
||||
const data = line.slice(3)
|
||||
// new port entry
|
||||
if (lineType === 'P') {
|
||||
port = {
|
||||
path: '',
|
||||
manufacturer: undefined,
|
||||
serialNumber: undefined,
|
||||
pnpId: undefined,
|
||||
locationId: undefined,
|
||||
vendorId: undefined,
|
||||
productId: undefined,
|
||||
}
|
||||
skipPort = false
|
||||
return
|
||||
}
|
||||
|
||||
if (skipPort) {
|
||||
return
|
||||
}
|
||||
|
||||
// Check dev name and save port if it matches flag to skip the rest of the data if not
|
||||
if (lineType === 'N') {
|
||||
if (checkPathOfDevice(data)) {
|
||||
ports.push(port)
|
||||
} else {
|
||||
skipPort = true
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// parse data about each port
|
||||
if (lineType === 'E') {
|
||||
const keyValue = data.match(/^(.+)=(.*)/)
|
||||
if (!keyValue) {
|
||||
return
|
||||
}
|
||||
const key = propName(keyValue[1]) as keyof PortInfo
|
||||
if (!key) {
|
||||
return
|
||||
}
|
||||
|
||||
port[key] = propVal(key, keyValue[2]) as string
|
||||
}
|
||||
})
|
||||
|
||||
return new Promise<PortInfo[]>((resolve, reject) => {
|
||||
udevadm.on('close', (code: string | null) => {
|
||||
if (code) {
|
||||
reject(new Error(`Error listing ports udevadm exited with error code: ${code}`))
|
||||
}
|
||||
})
|
||||
udevadm.on('error', reject)
|
||||
lines.on('error', reject)
|
||||
lines.on('finish', () => resolve(ports))
|
||||
})
|
||||
}
|
||||
111
lib/linux.js
111
lib/linux.js
|
|
@ -1,111 +0,0 @@
|
|||
const { promisify } = require('util')
|
||||
const { join } = require('path')
|
||||
const binding = require('node-gyp-build')(join(__dirname, '../'))
|
||||
const AbstractBinding = require('@serialport/binding-abstract')
|
||||
const linuxList = require('./linux-list')
|
||||
const Poller = require('./poller')
|
||||
const unixRead = require('./unix-read')
|
||||
const unixWrite = require('./unix-write')
|
||||
const { wrapWithHiddenComName } = require('./legacy')
|
||||
|
||||
const defaultBindingOptions = Object.freeze({
|
||||
vmin: 1,
|
||||
vtime: 0,
|
||||
})
|
||||
|
||||
const asyncOpen = promisify(binding.open)
|
||||
const asyncClose = promisify(binding.close)
|
||||
const asyncUpdate = promisify(binding.update)
|
||||
const asyncSet = promisify(binding.set)
|
||||
const asyncGet = promisify(binding.get)
|
||||
const asyncGetBaudRate = promisify(binding.getBaudRate)
|
||||
const asyncDrain = promisify(binding.drain)
|
||||
const asyncFlush = promisify(binding.flush)
|
||||
|
||||
/**
|
||||
* The linux binding layer
|
||||
*/
|
||||
class LinuxBinding extends AbstractBinding {
|
||||
static list() {
|
||||
return wrapWithHiddenComName(linuxList())
|
||||
}
|
||||
|
||||
constructor(opt = {}) {
|
||||
super(opt)
|
||||
this.bindingOptions = { ...defaultBindingOptions, ...opt.bindingOptions }
|
||||
this.fd = null
|
||||
this.writeOperation = null
|
||||
}
|
||||
|
||||
get isOpen() {
|
||||
return this.fd !== null
|
||||
}
|
||||
|
||||
async open(path, options) {
|
||||
await super.open(path, options)
|
||||
this.openOptions = { ...this.bindingOptions, ...options }
|
||||
const fd = await asyncOpen(path, this.openOptions)
|
||||
this.fd = fd
|
||||
this.poller = new Poller(fd)
|
||||
}
|
||||
|
||||
async close() {
|
||||
await super.close()
|
||||
const fd = this.fd
|
||||
this.poller.stop()
|
||||
this.poller.destroy()
|
||||
this.poller = null
|
||||
this.openOptions = null
|
||||
this.fd = null
|
||||
return asyncClose(fd)
|
||||
}
|
||||
|
||||
async read(buffer, offset, length) {
|
||||
await super.read(buffer, offset, length)
|
||||
return unixRead({ binding: this, buffer, offset, length })
|
||||
}
|
||||
|
||||
async write(buffer) {
|
||||
this.writeOperation = super.write(buffer).then(async () => {
|
||||
if (buffer.length === 0) {
|
||||
return
|
||||
}
|
||||
await unixWrite({ binding: this, buffer })
|
||||
this.writeOperation = null
|
||||
})
|
||||
return this.writeOperation
|
||||
}
|
||||
|
||||
async update(options) {
|
||||
await super.update(options)
|
||||
return asyncUpdate(this.fd, options)
|
||||
}
|
||||
|
||||
async set(options) {
|
||||
await super.set(options)
|
||||
return asyncSet(this.fd, options)
|
||||
}
|
||||
|
||||
async get() {
|
||||
await super.get()
|
||||
return asyncGet(this.fd)
|
||||
}
|
||||
|
||||
async getBaudRate() {
|
||||
await super.get()
|
||||
return asyncGetBaudRate(this.fd)
|
||||
}
|
||||
|
||||
async drain() {
|
||||
await super.drain()
|
||||
await this.writeOperation
|
||||
return asyncDrain(this.fd)
|
||||
}
|
||||
|
||||
async flush() {
|
||||
await super.flush()
|
||||
return asyncFlush(this.fd)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = LinuxBinding
|
||||
205
lib/linux.ts
Normal file
205
lib/linux.ts
Normal file
|
|
@ -0,0 +1,205 @@
|
|||
import debugFactory from 'debug'
|
||||
import { linuxList } from './linux-list'
|
||||
import { Poller } from './poller'
|
||||
import { unixRead } from './unix-read'
|
||||
import { unixWrite } from './unix-write'
|
||||
import { BindingInterface, OpenOptions, PortStatus, SetOptions, UpdateOptions } from './binding-interface'
|
||||
import { asyncOpen, asyncClose, asyncUpdate, asyncSet, asyncGet, asyncGetBaudRate, asyncFlush, asyncDrain } from './load-bindings'
|
||||
|
||||
const debug = debugFactory('serialport/bindings-cpp')
|
||||
|
||||
export interface LinuxBindingOptions {
|
||||
/** see [`man termios`](http://linux.die.net/man/3/termios) defaults to 1 */
|
||||
vmin?: number
|
||||
/** see [`man termios`](http://linux.die.net/man/3/termios) defaults to 0 */
|
||||
vtime?: number
|
||||
// * @param {Boolean} [options.lowLatency=false] flag for lowLatency mode on Linux
|
||||
}
|
||||
|
||||
export interface LinuxPortStatus extends PortStatus {
|
||||
lowLatency: boolean
|
||||
}
|
||||
|
||||
export interface LinuxSetOptions extends SetOptions {
|
||||
/** Low latency mode */
|
||||
lowLatency?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* The linux binding layer
|
||||
*/
|
||||
export class LinuxBinding extends BindingInterface {
|
||||
bindingOptions: LinuxBindingOptions
|
||||
fd: null | number
|
||||
writeOperation: Promise<void> | null
|
||||
openOptions: (LinuxBindingOptions & OpenOptions) | null
|
||||
poller: Poller | null
|
||||
|
||||
static list() {
|
||||
debug('list')
|
||||
return linuxList()
|
||||
}
|
||||
|
||||
constructor(opt?: LinuxBindingOptions) {
|
||||
super()
|
||||
this.bindingOptions = {
|
||||
vmin: 1,
|
||||
vtime: 0,
|
||||
...opt,
|
||||
}
|
||||
this.fd = null
|
||||
this.writeOperation = null
|
||||
}
|
||||
|
||||
get isOpen() {
|
||||
return this.fd !== null
|
||||
}
|
||||
|
||||
async open(path: string, options?: OpenOptions) {
|
||||
if (!path) {
|
||||
throw new TypeError('"path" is not a valid port')
|
||||
}
|
||||
|
||||
if (typeof options !== 'object') {
|
||||
throw new TypeError('"options" is not an object')
|
||||
}
|
||||
debug('open')
|
||||
|
||||
if (this.isOpen) {
|
||||
throw new Error('Already open')
|
||||
}
|
||||
this.openOptions = { ...this.bindingOptions, ...options }
|
||||
const fd: number = await asyncOpen(path, this.openOptions)
|
||||
this.fd = fd
|
||||
this.poller = new Poller(fd)
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
debug('close')
|
||||
if (!this.isOpen) {
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
|
||||
const fd = this.fd
|
||||
this.poller?.stop()
|
||||
this.poller?.destroy()
|
||||
this.poller = null
|
||||
this.openOptions = null
|
||||
this.fd = null
|
||||
await asyncClose(fd)
|
||||
}
|
||||
|
||||
async read(
|
||||
buffer: Buffer,
|
||||
offset: number,
|
||||
length: number,
|
||||
): Promise<{
|
||||
buffer: Buffer
|
||||
bytesRead: number
|
||||
}> {
|
||||
if (!Buffer.isBuffer(buffer)) {
|
||||
throw new TypeError('"buffer" is not a Buffer')
|
||||
}
|
||||
|
||||
if (typeof offset !== 'number' || isNaN(offset)) {
|
||||
throw new TypeError(`"offset" is not an integer got "${isNaN(offset) ? 'NaN' : typeof offset}"`)
|
||||
}
|
||||
|
||||
if (typeof length !== 'number' || isNaN(length)) {
|
||||
throw new TypeError(`"length" is not an integer got "${isNaN(length) ? 'NaN' : typeof length}"`)
|
||||
}
|
||||
|
||||
debug('read')
|
||||
if (buffer.length < offset + length) {
|
||||
throw new Error('buffer is too small')
|
||||
}
|
||||
|
||||
if (!this.isOpen) {
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
|
||||
return unixRead({ binding: this, buffer, offset, length })
|
||||
}
|
||||
|
||||
async write(buffer: Buffer): Promise<void> {
|
||||
if (!Buffer.isBuffer(buffer)) {
|
||||
throw new TypeError('"buffer" is not a Buffer')
|
||||
}
|
||||
|
||||
debug('write', buffer.length, 'bytes')
|
||||
if (!this.isOpen) {
|
||||
debug('write', 'error port is not open')
|
||||
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
|
||||
this.writeOperation = (async () => {
|
||||
if (buffer.length === 0) {
|
||||
return
|
||||
}
|
||||
await unixWrite({ binding: this, buffer })
|
||||
this.writeOperation = null
|
||||
})()
|
||||
return this.writeOperation
|
||||
}
|
||||
|
||||
async update(options: UpdateOptions): Promise<void> {
|
||||
if (typeof options !== 'object') {
|
||||
throw TypeError('"options" is not an object')
|
||||
}
|
||||
|
||||
if (typeof options.baudRate !== 'number') {
|
||||
throw new TypeError('"options.baudRate" is not a number')
|
||||
}
|
||||
|
||||
debug('update')
|
||||
if (!this.isOpen) {
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
await asyncUpdate(this.fd, options)
|
||||
}
|
||||
|
||||
async set(options: LinuxSetOptions): Promise<void> {
|
||||
if (typeof options !== 'object') {
|
||||
throw new TypeError('"options" is not an object')
|
||||
}
|
||||
debug('set')
|
||||
if (!this.isOpen) {
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
await asyncSet(this.fd, options)
|
||||
}
|
||||
|
||||
async get(): Promise<LinuxPortStatus> {
|
||||
debug('get')
|
||||
if (!this.isOpen) {
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
return asyncGet(this.fd)
|
||||
}
|
||||
|
||||
async getBaudRate(): Promise<{ baudRate: number }> {
|
||||
debug('getBaudRate')
|
||||
if (!this.isOpen) {
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
return asyncGetBaudRate(this.fd)
|
||||
}
|
||||
|
||||
async flush(): Promise<void> {
|
||||
debug('flush')
|
||||
if (!this.isOpen) {
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
await asyncFlush(this.fd)
|
||||
}
|
||||
|
||||
async drain(): Promise<void> {
|
||||
debug('drain')
|
||||
if (!this.isOpen) {
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
await this.writeOperation
|
||||
await asyncDrain(this.fd)
|
||||
}
|
||||
}
|
||||
17
lib/load-bindings.ts
Normal file
17
lib/load-bindings.ts
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import nodeGypBuild from 'node-gyp-build'
|
||||
import { promisify } from 'util'
|
||||
import { join } from 'path'
|
||||
|
||||
const binding = nodeGypBuild(join(__dirname, '../')) as any
|
||||
|
||||
export const asyncClose = binding.close ? promisify(binding.close) : async () => { throw new Error('"binding.close" Method not implemented')}
|
||||
export const asyncDrain = binding.drain ? promisify(binding.drain) : async () => { throw new Error('"binding.drain" Method not implemented')}
|
||||
export const asyncFlush = binding.flush ? promisify(binding.flush) : async () => { throw new Error('"binding.flush" Method not implemented')}
|
||||
export const asyncGet = binding.get ? promisify(binding.get) : async () => { throw new Error('"binding.get" Method not implemented')}
|
||||
export const asyncGetBaudRate = binding.getBaudRate ? promisify(binding.getBaudRate) : async () => { throw new Error('"binding.getBaudRate" Method not implemented')}
|
||||
export const asyncList = binding.list ? promisify(binding.list) : async () => { throw new Error('"binding.list" Method not implemented')}
|
||||
export const asyncOpen = binding.open ? promisify(binding.open) : async () => { throw new Error('"binding.open" Method not implemented')}
|
||||
export const asyncSet = binding.set ? promisify(binding.set) : async () => { throw new Error('"binding.set" Method not implemented')}
|
||||
export const asyncUpdate = binding.update ? promisify(binding.update) : async () => { throw new Error('"binding.update" Method not implemented')}
|
||||
export const asyncRead = binding.read ? promisify(binding.read) : async () => { throw new Error('"binding.read" Method not implemented')}
|
||||
export const asyncWrite = binding.read ? promisify(binding.write) : async () => { throw new Error('"binding.write" Method not implemented')}
|
||||
2
lib/missing-types.ts
Normal file
2
lib/missing-types.ts
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
declare module '@serialport/binding-mock'
|
||||
declare module '@serialport/parser-readline'
|
||||
|
|
@ -1,36 +0,0 @@
|
|||
// Mocks fs.read for listLinux
|
||||
|
||||
const EventEmitter = require('events')
|
||||
const proxyquire = require('proxyquire')
|
||||
const Readable = require('stream').Readable
|
||||
let mockPorts
|
||||
let event
|
||||
|
||||
proxyquire.noPreserveCache()
|
||||
const listLinux = proxyquire('../linux-list', {
|
||||
child_process: {
|
||||
spawn() {
|
||||
const stream = new Readable()
|
||||
event = new EventEmitter()
|
||||
event.stdout = stream
|
||||
stream.push(mockPorts)
|
||||
stream.push(null)
|
||||
return event
|
||||
},
|
||||
},
|
||||
})
|
||||
proxyquire.preserveCache()
|
||||
|
||||
listLinux.setPorts = ports => {
|
||||
mockPorts = ports
|
||||
}
|
||||
|
||||
listLinux.emit = () => {
|
||||
event.emit.apply(event, arguments)
|
||||
}
|
||||
|
||||
listLinux.reset = () => {
|
||||
mockPorts = undefined
|
||||
}
|
||||
|
||||
module.exports = listLinux
|
||||
27
lib/mocks/linux-list.ts
Normal file
27
lib/mocks/linux-list.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
// Mocks fs.read for listLinux
|
||||
|
||||
import { EventEmitter } from 'events'
|
||||
import { Readable } from 'stream'
|
||||
import { linuxList } from '../linux-list'
|
||||
|
||||
export const mockLinuxList = (mockUDevOutput: string) => {
|
||||
return linuxList(() => {
|
||||
const mockUDevAdm = new EventEmitter() as any
|
||||
const stream = new Readable({ read() {} })
|
||||
mockUDevAdm.stdout = stream
|
||||
stream.push(mockUDevOutput)
|
||||
stream.push(null)
|
||||
return mockUDevAdm
|
||||
})
|
||||
}
|
||||
|
||||
export const mockLinuxListError = (code: string) => {
|
||||
return linuxList(() => {
|
||||
const mockUDevAdm = new EventEmitter() as any
|
||||
mockUDevAdm.stdout = new Readable({ read() {} })
|
||||
setImmediate(() => {
|
||||
mockUDevAdm.emit('close', code)
|
||||
})
|
||||
return mockUDevAdm
|
||||
})
|
||||
}
|
||||
3
lib/node-gype-build.d.ts
vendored
Normal file
3
lib/node-gype-build.d.ts
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
declare module 'node-gyp-build' {
|
||||
export default function load(path: string): unknown
|
||||
}
|
||||
|
|
@ -1,22 +1,29 @@
|
|||
const Poller = require('./poller')
|
||||
import { Poller } from './poller'
|
||||
import { assert } from '../test/assert'
|
||||
|
||||
class MockPollerBidnings {
|
||||
constructor(fd, callback) {
|
||||
class MockPollerBindings {
|
||||
fd: number
|
||||
callback: any
|
||||
lastPollFlag: string
|
||||
constructor(fd: number, callback: any) {
|
||||
this.fd = fd
|
||||
this.callback = callback
|
||||
}
|
||||
poll(flag) {
|
||||
poll(flag: string) {
|
||||
this.lastPollFlag = flag
|
||||
setImmediate(() => this.callback(null, flag))
|
||||
}
|
||||
}
|
||||
|
||||
class ErrorPollerBindings {
|
||||
constructor(fd, callback) {
|
||||
fd: number
|
||||
callback: any
|
||||
lastPollFlag: string
|
||||
constructor(fd: number, callback: any) {
|
||||
this.fd = fd
|
||||
this.callback = callback
|
||||
}
|
||||
poll(flag) {
|
||||
poll(flag: string) {
|
||||
this.lastPollFlag = flag
|
||||
setImmediate(() => this.callback(new Error('oh no!'), flag))
|
||||
}
|
||||
|
|
@ -24,10 +31,10 @@ class ErrorPollerBindings {
|
|||
|
||||
describe('Poller', () => {
|
||||
it('constructs', () => {
|
||||
new Poller(1, MockPollerBidnings)
|
||||
new Poller(1, MockPollerBindings)
|
||||
})
|
||||
it('can listen to the readable event', done => {
|
||||
const poller = new Poller(1, MockPollerBidnings)
|
||||
const poller = new Poller(1, MockPollerBindings)
|
||||
poller.once('readable', err => {
|
||||
assert.equal(err, null)
|
||||
assert.equal(poller.poller.lastPollFlag, 1)
|
||||
|
|
@ -35,7 +42,7 @@ describe('Poller', () => {
|
|||
})
|
||||
})
|
||||
it('can listen to the writable event', done => {
|
||||
const poller = new Poller(1, MockPollerBidnings)
|
||||
const poller = new Poller(1, MockPollerBindings)
|
||||
poller.once('writable', err => {
|
||||
assert.equal(err, null)
|
||||
assert.equal(poller.poller.lastPollFlag, 2)
|
||||
|
|
@ -43,7 +50,7 @@ describe('Poller', () => {
|
|||
})
|
||||
})
|
||||
it('can listen to the disconnect event', done => {
|
||||
const poller = new Poller(1, MockPollerBidnings)
|
||||
const poller = new Poller(1, MockPollerBindings)
|
||||
poller.once('disconnect', err => {
|
||||
assert.equal(err, null)
|
||||
assert.equal(poller.poller.lastPollFlag, 4)
|
||||
|
|
@ -1,16 +1,19 @@
|
|||
const debug = require('debug')
|
||||
const logger = debug('serialport/bindings/poller')
|
||||
const EventEmitter = require('events')
|
||||
const { join } = require('path')
|
||||
const PollerBindings = require('node-gyp-build')(join(__dirname, '../')).Poller
|
||||
import debug from 'debug'
|
||||
import { EventEmitter } from 'events'
|
||||
import { join } from 'path'
|
||||
import nodeGypBuild from 'node-gyp-build'
|
||||
import { CanceledError } from './errors'
|
||||
|
||||
const EVENTS = {
|
||||
const { Poller: PollerBindings } = nodeGypBuild(join(__dirname, '../')) as any
|
||||
const logger = debug('serialport/bindings/poller')
|
||||
|
||||
export const EVENTS = {
|
||||
UV_READABLE: 0b0001,
|
||||
UV_WRITABLE: 0b0010,
|
||||
UV_DISCONNECT: 0b0100,
|
||||
}
|
||||
|
||||
function handleEvent(error, eventFlag) {
|
||||
function handleEvent(error: Error, eventFlag: number) {
|
||||
if (error) {
|
||||
logger('error', error)
|
||||
this.emit('readable', error)
|
||||
|
|
@ -35,8 +38,9 @@ function handleEvent(error, eventFlag) {
|
|||
/**
|
||||
* Polls unix systems for readable or writable states of a file or serialport
|
||||
*/
|
||||
class Poller extends EventEmitter {
|
||||
constructor(fd, FDPoller = PollerBindings) {
|
||||
export class Poller extends EventEmitter {
|
||||
poller: any
|
||||
constructor(fd: number, FDPoller = PollerBindings) {
|
||||
logger('Creating poller')
|
||||
super()
|
||||
this.poller = new FDPoller(fd, handleEvent.bind(this))
|
||||
|
|
@ -46,17 +50,17 @@ class Poller extends EventEmitter {
|
|||
* @param {string} event ('readable'|'writable'|'disconnect')
|
||||
* @returns {Poller} returns itself
|
||||
*/
|
||||
once(event, callback) {
|
||||
once(event: 'readable' | 'writable' | 'disconnect', callback: (err: null | Error) => void): this {
|
||||
switch (event) {
|
||||
case 'readable':
|
||||
this.poll(EVENTS.UV_READABLE)
|
||||
break
|
||||
case 'writable':
|
||||
this.poll(EVENTS.UV_WRITABLE)
|
||||
break
|
||||
case 'disconnect':
|
||||
this.poll(EVENTS.UV_DISCONNECT)
|
||||
break
|
||||
case 'readable':
|
||||
this.poll(EVENTS.UV_READABLE)
|
||||
break
|
||||
case 'writable':
|
||||
this.poll(EVENTS.UV_WRITABLE)
|
||||
break
|
||||
case 'disconnect':
|
||||
this.poll(EVENTS.UV_DISCONNECT)
|
||||
break
|
||||
}
|
||||
return super.once(event, callback)
|
||||
}
|
||||
|
|
@ -64,11 +68,8 @@ class Poller extends EventEmitter {
|
|||
/**
|
||||
* Ask the bindings to listen for an event, it is recommend to use `.once()` for easy use
|
||||
* @param {EVENTS} eventFlag polls for an event or group of events based upon a flag.
|
||||
* @returns {undefined}
|
||||
*/
|
||||
poll(eventFlag) {
|
||||
eventFlag = eventFlag || 0
|
||||
|
||||
poll(eventFlag = 0) {
|
||||
if (eventFlag & EVENTS.UV_READABLE) {
|
||||
logger('Polling for "readable"')
|
||||
}
|
||||
|
|
@ -84,29 +85,23 @@ class Poller extends EventEmitter {
|
|||
|
||||
/**
|
||||
* Stop listening for events and cancel all outstanding listening with an error
|
||||
* @returns {undefined}
|
||||
*/
|
||||
stop() {
|
||||
stop(): void {
|
||||
logger('Stopping poller')
|
||||
this.poller.stop()
|
||||
this.emitCanceled()
|
||||
}
|
||||
|
||||
destroy() {
|
||||
destroy(): void {
|
||||
logger('Destroying poller')
|
||||
this.poller.destroy()
|
||||
this.emitCanceled()
|
||||
}
|
||||
|
||||
emitCanceled() {
|
||||
const err = new Error('Canceled')
|
||||
err.canceled = true
|
||||
emitCanceled(): void {
|
||||
const err = new CanceledError('Canceled')
|
||||
this.emit('readable', err)
|
||||
this.emit('writable', err)
|
||||
this.emit('disconnect', err)
|
||||
}
|
||||
}
|
||||
|
||||
Poller.EVENTS = EVENTS
|
||||
|
||||
module.exports = Poller
|
||||
|
|
@ -1,24 +1,29 @@
|
|||
const unixRead = require('./unix-read')
|
||||
import { assert, shouldReject } from '../test/assert'
|
||||
import { LinuxBinding } from './linux'
|
||||
import { unixRead } from './unix-read'
|
||||
|
||||
const makeFsRead = (bytesRead, fill) => (fd, buffer, offset, length) => {
|
||||
buffer.fill(fill, offset, Math.min(length, bytesRead))
|
||||
return {
|
||||
buffer,
|
||||
bytesRead,
|
||||
}
|
||||
}
|
||||
const makeFsRead =
|
||||
(bytesRead: number, fill: number): any =>
|
||||
(fd: number, buffer: Buffer, offset: number, length: number) => {
|
||||
buffer.fill(fill, offset, Math.min(length, bytesRead))
|
||||
return {
|
||||
buffer,
|
||||
bytesRead,
|
||||
}
|
||||
}
|
||||
|
||||
const makeFsReadError = code => {
|
||||
const makeFsReadError = (code: string) => {
|
||||
const err = new Error(`Error: ${code}`)
|
||||
err.code = code
|
||||
;(err as any).code = code
|
||||
return () => {
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
const sequenceCalls = (...functions) => {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
const sequenceCalls = (...functions: Function[]) => {
|
||||
const funcs = [...functions]
|
||||
return (...args) => {
|
||||
return (...args: any[]) => {
|
||||
const func = funcs.shift()
|
||||
if (func) {
|
||||
return func(...args)
|
||||
|
|
@ -28,25 +33,25 @@ const sequenceCalls = (...functions) => {
|
|||
}
|
||||
}
|
||||
|
||||
const makeMockBinding = () => {
|
||||
const makeMockBinding = (): LinuxBinding => {
|
||||
return {
|
||||
isOpen: true,
|
||||
fd: 1,
|
||||
poller: {
|
||||
once(event, func) {
|
||||
once(event: any, func: () => void) {
|
||||
setImmediate(func)
|
||||
},
|
||||
},
|
||||
}
|
||||
} as any
|
||||
}
|
||||
|
||||
describe('unixRead', () => {
|
||||
let mock
|
||||
let mock: LinuxBinding
|
||||
beforeEach(() => {
|
||||
mock = makeMockBinding()
|
||||
})
|
||||
it('rejects when not open', async () => {
|
||||
mock.isOpen = false
|
||||
(mock as any).isOpen = false
|
||||
const readBuffer = Buffer.alloc(8, 0)
|
||||
await shouldReject(unixRead({ binding: mock, buffer: readBuffer, offset: 0, length: 8, fsReadAsync: makeFsRead(8, 255) }))
|
||||
})
|
||||
|
|
@ -88,8 +93,8 @@ describe('unixRead', () => {
|
|||
})
|
||||
it('rejects a canceled error if port closes after read a retryable error', async () => {
|
||||
const readBuffer = Buffer.alloc(8, 0)
|
||||
const fsReadAsync = () => {
|
||||
mock.isOpen = false
|
||||
const fsReadAsync: any = () => {
|
||||
(mock as any).isOpen = false
|
||||
makeFsReadError('EAGAIN')()
|
||||
}
|
||||
const err = await shouldReject(unixRead({ binding: mock, buffer: readBuffer, offset: 0, length: 8, fsReadAsync }))
|
||||
|
|
@ -1,22 +1,40 @@
|
|||
const fs = require('fs')
|
||||
const debug = require('debug')
|
||||
const logger = debug('serialport/bindings/unixRead')
|
||||
const { promisify } = require('util')
|
||||
import { promisify } from 'util'
|
||||
import { read as fsRead } from 'fs'
|
||||
import { CanceledError } from './errors'
|
||||
import debugFactory from 'debug'
|
||||
import { LinuxBinding } from './linux'
|
||||
import { DarwinBinding } from './darwin'
|
||||
|
||||
const readAsync = promisify(fs.read)
|
||||
const logger = debugFactory('serialport/bindings-cpp/unixRead')
|
||||
const readAsync = promisify(fsRead)
|
||||
|
||||
const readable = binding => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const readable = (binding: LinuxBinding | DarwinBinding) => {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
if (!binding.poller) {
|
||||
throw new Error('No poller on bindings')
|
||||
}
|
||||
binding.poller.once('readable', err => (err ? reject(err) : resolve()))
|
||||
})
|
||||
}
|
||||
|
||||
const unixRead = async ({ binding, buffer, offset, length, fsReadAsync = readAsync }) => {
|
||||
interface UnixReadOptions {
|
||||
binding: LinuxBinding | DarwinBinding
|
||||
buffer: Buffer
|
||||
offset: number
|
||||
length: number
|
||||
fsReadAsync?: typeof readAsync
|
||||
}
|
||||
|
||||
export const unixRead = async ({
|
||||
binding,
|
||||
buffer,
|
||||
offset,
|
||||
length,
|
||||
fsReadAsync = readAsync,
|
||||
}: UnixReadOptions): Promise<{ buffer: Buffer; bytesRead: number }> => {
|
||||
logger('Starting read')
|
||||
if (!binding.isOpen) {
|
||||
const err = new Error('Port is not open')
|
||||
err.canceled = true
|
||||
throw err
|
||||
if (!binding.isOpen || !binding.fd) {
|
||||
throw new CanceledError('Port is not open')
|
||||
}
|
||||
|
||||
try {
|
||||
|
|
@ -30,9 +48,7 @@ const unixRead = async ({ binding, buffer, offset, length, fsReadAsync = readAsy
|
|||
logger('read error', err)
|
||||
if (err.code === 'EAGAIN' || err.code === 'EWOULDBLOCK' || err.code === 'EINTR') {
|
||||
if (!binding.isOpen) {
|
||||
const err = new Error('Port is not open')
|
||||
err.canceled = true
|
||||
throw err
|
||||
throw new CanceledError('Port is not open')
|
||||
}
|
||||
logger('waiting for readable because of code:', err.code)
|
||||
await readable(binding)
|
||||
|
|
@ -53,5 +69,3 @@ const unixRead = async ({ binding, buffer, offset, length, fsReadAsync = readAsy
|
|||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = unixRead
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
const unixWrite = require('./unix-write')
|
||||
const { randomBytes } = require('crypto')
|
||||
const { promisify } = require('util')
|
||||
import { assert, shouldReject } from '../test/assert'
|
||||
import { unixWrite } from './unix-write'
|
||||
import { randomBytes } from 'crypto'
|
||||
import { promisify } from 'util'
|
||||
const randomBytesAsync = promisify(randomBytes)
|
||||
|
||||
const makeMockBinding = () => {
|
||||
|
|
@ -9,11 +10,11 @@ const makeMockBinding = () => {
|
|||
fd: 1,
|
||||
poller: {
|
||||
error: null,
|
||||
once(event, func) {
|
||||
once(event: any, func: (err: null | Error) => void) {
|
||||
setImmediate(() => func(this.error))
|
||||
},
|
||||
},
|
||||
}
|
||||
} as any
|
||||
}
|
||||
|
||||
const makeFsWrite = (maxBytesToWrite = Infinity) => {
|
||||
|
|
@ -22,7 +23,7 @@ const makeFsWrite = (maxBytesToWrite = Infinity) => {
|
|||
writeBuffer: Buffer.alloc(0),
|
||||
writes: 0,
|
||||
}
|
||||
const fsWriteAsync = (fd, buffer, offset, bytesToWrite) => {
|
||||
const fsWriteAsync: any = (fd: number, buffer: Buffer, offset: number, bytesToWrite: number) => {
|
||||
const bytesWritten = Math.min(maxBytesToWrite, bytesToWrite)
|
||||
info.bytesWritten += bytesWritten
|
||||
info.writeBuffer = Buffer.concat([info.writeBuffer, buffer.slice(offset, offset + bytesWritten)])
|
||||
|
|
@ -39,9 +40,10 @@ const makeFsWrite = (maxBytesToWrite = Infinity) => {
|
|||
}
|
||||
}
|
||||
|
||||
const sequenceCalls = (...functions) => {
|
||||
// eslint-disable-next-line @typescript-eslint/ban-types
|
||||
const sequenceCalls = (...functions: Function[]) => {
|
||||
const funcs = [...functions]
|
||||
return (...args) => {
|
||||
return (...args: any[]) => {
|
||||
const func = funcs.shift()
|
||||
if (func) {
|
||||
return func(...args)
|
||||
|
|
@ -51,16 +53,16 @@ const sequenceCalls = (...functions) => {
|
|||
}
|
||||
}
|
||||
|
||||
const makeFsWriteError = code => {
|
||||
const makeFsWriteError = (code: string) => {
|
||||
const err = new Error(`Error: ${code}`)
|
||||
err.code = code
|
||||
;(err as any).code = code
|
||||
return () => {
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
describe('unixWrite', () => {
|
||||
let mock
|
||||
let mock: ReturnType<typeof makeMockBinding>
|
||||
beforeEach(() => {
|
||||
mock = makeMockBinding()
|
||||
})
|
||||
|
|
@ -88,7 +90,7 @@ describe('unixWrite', () => {
|
|||
it('errors if the port closes after a partial write', async () => {
|
||||
const writeBuffer = await randomBytesAsync(16)
|
||||
const { fsWriteAsync: realFsWrite, info } = makeFsWrite(8)
|
||||
const fsWriteAsync = (...args) => {
|
||||
const fsWriteAsync = (...args: any[]) => {
|
||||
mock.isOpen = false
|
||||
return realFsWrite(...args)
|
||||
}
|
||||
|
|
@ -98,7 +100,7 @@ describe('unixWrite', () => {
|
|||
})
|
||||
it('errors if the poller errors after a partial write', async () => {
|
||||
const writeBuffer = await randomBytesAsync(16)
|
||||
const fsWriteAsync = () => {
|
||||
const fsWriteAsync: any = () => {
|
||||
mock.poller.error = new Error('PollerError')
|
||||
makeFsWriteError('EAGAIN')()
|
||||
}
|
||||
|
|
@ -114,7 +116,7 @@ describe('unixWrite', () => {
|
|||
makeFsWriteError('EAGAIN'),
|
||||
makeFsWriteError('EWOULDBLOCK'),
|
||||
makeFsWriteError('EINTR'),
|
||||
fsWriteAsyncReal
|
||||
fsWriteAsyncReal,
|
||||
)
|
||||
|
||||
await unixWrite({ binding: mock, buffer: writeBuffer, fsWriteAsync })
|
||||
|
|
@ -128,7 +130,7 @@ describe('unixWrite', () => {
|
|||
})
|
||||
it('rejects an error if port closes after read a retryable error', async () => {
|
||||
const writeBuffer = Buffer.alloc(8, 0)
|
||||
const fsWriteAsync = () => {
|
||||
const fsWriteAsync: any = () => {
|
||||
mock.isOpen = false
|
||||
makeFsWriteError('EAGAIN')()
|
||||
}
|
||||
|
|
@ -1,20 +1,29 @@
|
|||
const fs = require('fs')
|
||||
const debug = require('debug')
|
||||
const logger = debug('serialport/bindings/unixWrite')
|
||||
const { promisify } = require('util')
|
||||
import { write } from 'fs'
|
||||
import debugFactory from 'debug'
|
||||
import { promisify } from 'util'
|
||||
import { LinuxBinding } from './linux'
|
||||
import { DarwinBinding } from './darwin'
|
||||
const logger = debugFactory('serialport/bindings-cpp/unixWrite')
|
||||
|
||||
const writeAsync = promisify(fs.write)
|
||||
const writeAsync = promisify(write)
|
||||
|
||||
const writable = binding => {
|
||||
return new Promise((resolve, reject) => {
|
||||
binding.poller.once('writable', err => (err ? reject(err) : resolve()))
|
||||
const writable = (binding: LinuxBinding | DarwinBinding) => {
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
binding.poller?.once('writable', err => (err ? reject(err) : resolve()))
|
||||
})
|
||||
}
|
||||
|
||||
const unixWrite = async ({ binding, buffer, offset = 0, fsWriteAsync = writeAsync }) => {
|
||||
interface UnixWriteOptions {
|
||||
binding: LinuxBinding | DarwinBinding
|
||||
buffer: Buffer
|
||||
offset?: number
|
||||
fsWriteAsync?: typeof writeAsync
|
||||
}
|
||||
|
||||
export const unixWrite = async ({ binding, buffer, offset = 0, fsWriteAsync = writeAsync }: UnixWriteOptions): Promise<void> => {
|
||||
const bytesToWrite = buffer.length - offset
|
||||
logger('Starting write', buffer.length, 'bytes offset', offset, 'bytesToWrite', bytesToWrite)
|
||||
if (!binding.isOpen) {
|
||||
if (!binding.isOpen || !binding.fd) {
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
try {
|
||||
|
|
@ -54,4 +63,3 @@ const unixWrite = async ({ binding, buffer, offset = 0, fsWriteAsync = writeAsyn
|
|||
throw err
|
||||
}
|
||||
}
|
||||
module.exports = unixWrite
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
const PARSERS = [/USB\\(?:.+)\\(.+)/, /FTDIBUS\\(?:.+)\+(.+?)A?\\.+/]
|
||||
|
||||
module.exports = pnpId => {
|
||||
export const serialNumParser = (pnpId?: string) => {
|
||||
if (!pnpId) {
|
||||
return null
|
||||
}
|
||||
124
lib/win32.js
124
lib/win32.js
|
|
@ -1,124 +0,0 @@
|
|||
const { join } = require('path')
|
||||
const binding = require('node-gyp-build')(join(__dirname, '../'))
|
||||
const AbstractBinding = require('@serialport/binding-abstract')
|
||||
const { promisify } = require('util')
|
||||
const serialNumParser = require('./win32-sn-parser')
|
||||
|
||||
const asyncList = promisify(binding.list)
|
||||
const asyncOpen = promisify(binding.open)
|
||||
const asyncClose = promisify(binding.close)
|
||||
const asyncRead = promisify(binding.read)
|
||||
const asyncWrite = promisify(binding.write)
|
||||
const asyncUpdate = promisify(binding.update)
|
||||
const asyncSet = promisify(binding.set)
|
||||
const asyncGet = promisify(binding.get)
|
||||
const asyncGetBaudRate = promisify(binding.getBaudRate)
|
||||
const asyncDrain = promisify(binding.drain)
|
||||
const asyncFlush = promisify(binding.flush)
|
||||
const { wrapWithHiddenComName } = require('./legacy')
|
||||
|
||||
/**
|
||||
* The Windows binding layer
|
||||
*/
|
||||
class WindowsBinding extends AbstractBinding {
|
||||
static async list() {
|
||||
const ports = await asyncList()
|
||||
// Grab the serial number from the pnp id
|
||||
return wrapWithHiddenComName(
|
||||
ports.map(port => {
|
||||
if (port.pnpId && !port.serialNumber) {
|
||||
const serialNumber = serialNumParser(port.pnpId)
|
||||
if (serialNumber) {
|
||||
return {
|
||||
...port,
|
||||
serialNumber,
|
||||
}
|
||||
}
|
||||
}
|
||||
return port
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
constructor(opt = {}) {
|
||||
super(opt)
|
||||
this.bindingOptions = { ...opt.bindingOptions }
|
||||
this.fd = null
|
||||
this.writeOperation = null
|
||||
}
|
||||
|
||||
get isOpen() {
|
||||
return this.fd !== null
|
||||
}
|
||||
|
||||
async open(path, options) {
|
||||
await super.open(path, options)
|
||||
this.openOptions = { ...this.bindingOptions, ...options }
|
||||
const fd = await asyncOpen(path, this.openOptions)
|
||||
this.fd = fd
|
||||
}
|
||||
|
||||
async close() {
|
||||
await super.close()
|
||||
const fd = this.fd
|
||||
this.fd = null
|
||||
return asyncClose(fd)
|
||||
}
|
||||
|
||||
async read(buffer, offset, length) {
|
||||
await super.read(buffer, offset, length)
|
||||
try {
|
||||
const bytesRead = await asyncRead(this.fd, buffer, offset, length)
|
||||
return { bytesRead, buffer }
|
||||
} catch (err) {
|
||||
if (!this.isOpen) {
|
||||
err.canceled = true
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
async write(buffer) {
|
||||
this.writeOperation = super.write(buffer).then(async () => {
|
||||
if (buffer.length === 0) {
|
||||
return
|
||||
}
|
||||
await asyncWrite(this.fd, buffer)
|
||||
this.writeOperation = null
|
||||
})
|
||||
return this.writeOperation
|
||||
}
|
||||
|
||||
async update(options) {
|
||||
await super.update(options)
|
||||
return asyncUpdate(this.fd, options)
|
||||
}
|
||||
|
||||
async set(options) {
|
||||
await super.set(options)
|
||||
return asyncSet(this.fd, options)
|
||||
}
|
||||
|
||||
async get() {
|
||||
await super.get()
|
||||
return asyncGet(this.fd)
|
||||
}
|
||||
|
||||
async getBaudRate() {
|
||||
await super.get()
|
||||
return asyncGetBaudRate(this.fd)
|
||||
}
|
||||
|
||||
async drain() {
|
||||
await super.drain()
|
||||
await this.writeOperation
|
||||
return asyncDrain(this.fd)
|
||||
}
|
||||
|
||||
async flush() {
|
||||
await super.flush()
|
||||
return asyncFlush(this.fd)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WindowsBinding
|
||||
188
lib/win32.ts
Normal file
188
lib/win32.ts
Normal file
|
|
@ -0,0 +1,188 @@
|
|||
import debugFactory from 'debug'
|
||||
import { BindingInterface, OpenOptions, PortInfo, PortStatus, SetOptions, UpdateOptions } from './binding-interface'
|
||||
import { asyncClose, asyncDrain, asyncFlush, asyncGet, asyncGetBaudRate, asyncList, asyncOpen, asyncRead, asyncSet, asyncUpdate, asyncWrite } from './load-bindings'
|
||||
import { serialNumParser } from './win32-sn-parser'
|
||||
|
||||
const debug = debugFactory('serialport/bindings-cpp')
|
||||
|
||||
/**
|
||||
* The Windows binding layer
|
||||
*/
|
||||
export class WindowsBinding extends BindingInterface {
|
||||
fd: null | number
|
||||
writeOperation: Promise<void> | null
|
||||
openOptions: OpenOptions | null
|
||||
|
||||
static async list() {
|
||||
const ports: PortInfo[] = await asyncList()
|
||||
// Grab the serial number from the pnp id
|
||||
return ports.map(port => {
|
||||
if (port.pnpId && !port.serialNumber) {
|
||||
const serialNumber = serialNumParser(port.pnpId)
|
||||
if (serialNumber) {
|
||||
return {
|
||||
...port,
|
||||
serialNumber,
|
||||
}
|
||||
}
|
||||
}
|
||||
return port
|
||||
})
|
||||
}
|
||||
|
||||
constructor() {
|
||||
super()
|
||||
this.fd = null
|
||||
this.writeOperation = null
|
||||
}
|
||||
|
||||
get isOpen() {
|
||||
return this.fd !== null
|
||||
}
|
||||
|
||||
async open(path: string, options?: OpenOptions) {
|
||||
if (!path) {
|
||||
throw new TypeError('"path" is not a valid port')
|
||||
}
|
||||
|
||||
if (typeof options !== 'object') {
|
||||
throw new TypeError('"options" is not an object')
|
||||
}
|
||||
debug('open')
|
||||
|
||||
if (this.isOpen) {
|
||||
throw new Error('Already open')
|
||||
}
|
||||
this.openOptions = { ...options }
|
||||
const fd = await asyncOpen(path, this.openOptions)
|
||||
this.fd = fd
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
debug('close')
|
||||
if (!this.isOpen) {
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
|
||||
const fd = this.fd
|
||||
this.fd = null
|
||||
await asyncClose(fd)
|
||||
}
|
||||
|
||||
async read(buffer: Buffer, offset: number, length: number): Promise<{
|
||||
buffer: Buffer
|
||||
bytesRead: number
|
||||
}> {
|
||||
if (!Buffer.isBuffer(buffer)) {
|
||||
throw new TypeError('"buffer" is not a Buffer')
|
||||
}
|
||||
|
||||
if (typeof offset !== 'number' || isNaN(offset)) {
|
||||
throw new TypeError(`"offset" is not an integer got "${isNaN(offset) ? 'NaN' : typeof offset}"`)
|
||||
}
|
||||
|
||||
if (typeof length !== 'number' || isNaN(length)) {
|
||||
throw new TypeError(`"length" is not an integer got "${isNaN(length) ? 'NaN' : typeof length}"`)
|
||||
}
|
||||
|
||||
debug('read')
|
||||
if (buffer.length < offset + length) {
|
||||
throw new Error('buffer is too small')
|
||||
}
|
||||
|
||||
if (!this.isOpen) {
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
try {
|
||||
const bytesRead = await asyncRead(this.fd, buffer, offset, length)
|
||||
return { bytesRead, buffer }
|
||||
} catch (err) {
|
||||
if (!this.isOpen) {
|
||||
err.canceled = true
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
async write(buffer: Buffer): Promise<void> {
|
||||
if (!Buffer.isBuffer(buffer)) {
|
||||
throw new TypeError('"buffer" is not a Buffer')
|
||||
}
|
||||
|
||||
debug('write', buffer.length, 'bytes')
|
||||
if (!this.isOpen) {
|
||||
debug('write', 'error port is not open')
|
||||
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
|
||||
this.writeOperation = (async () => {
|
||||
if (buffer.length === 0) {
|
||||
return
|
||||
}
|
||||
await asyncWrite(this.fd, buffer)
|
||||
this.writeOperation = null
|
||||
})()
|
||||
return this.writeOperation
|
||||
}
|
||||
|
||||
async update(options: UpdateOptions): Promise<void> {
|
||||
if (typeof options !== 'object') {
|
||||
throw TypeError('"options" is not an object')
|
||||
}
|
||||
|
||||
if (typeof options.baudRate !== 'number') {
|
||||
throw new TypeError('"options.baudRate" is not a number')
|
||||
}
|
||||
|
||||
debug('update')
|
||||
if (!this.isOpen) {
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
await asyncUpdate(this.fd, options)
|
||||
}
|
||||
|
||||
async set(options: SetOptions): Promise<void> {
|
||||
if (typeof options !== 'object') {
|
||||
throw new TypeError('"options" is not an object')
|
||||
}
|
||||
debug('set', options)
|
||||
if (!this.isOpen) {
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
await asyncSet(this.fd, options)
|
||||
}
|
||||
|
||||
async get(): Promise<PortStatus> {
|
||||
debug('get')
|
||||
if (!this.isOpen) {
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
return asyncGet(this.fd)
|
||||
}
|
||||
|
||||
async getBaudRate(): Promise<{ baudRate: number }> {
|
||||
debug('getBaudRate')
|
||||
if (!this.isOpen) {
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
return asyncGetBaudRate(this.fd)
|
||||
}
|
||||
|
||||
async flush(): Promise<void> {
|
||||
debug('flush')
|
||||
if (!this.isOpen) {
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
await asyncFlush(this.fd)
|
||||
}
|
||||
|
||||
async drain(): Promise<void> {
|
||||
debug('drain')
|
||||
if (!this.isOpen) {
|
||||
throw new Error('Port is not open')
|
||||
}
|
||||
await this.writeOperation
|
||||
await asyncDrain(this.fd)
|
||||
}
|
||||
}
|
||||
2356
package-lock.json
generated
2356
package-lock.json
generated
File diff suppressed because it is too large
Load diff
30
package.json
30
package.json
|
|
@ -26,17 +26,19 @@
|
|||
"devDependencies": {
|
||||
"@semantic-release/exec": "^6.0.3",
|
||||
"@serialport/binding-mock": "10.0.1",
|
||||
"@types/chai": "^4.3.0",
|
||||
"@types/chai-subset": "^1.3.3",
|
||||
"@types/debug": "^4.1.7",
|
||||
"@types/mocha": "^9.0.0",
|
||||
"@typescript-eslint/eslint-plugin": "^5.10.0",
|
||||
"@typescript-eslint/parser": "^5.10.0",
|
||||
"cc": "^3.0.1",
|
||||
"chai": "^4.3.4",
|
||||
"chai-subset": "^1.6.0",
|
||||
"codecov": "^3.8.3",
|
||||
"esbuild": "^0.14.12",
|
||||
"esbuild-register": "^3.3.2",
|
||||
"eslint": "^8.2.0",
|
||||
"eslint-config-prettier": "^8.3.0",
|
||||
"eslint-plugin-import": "^2.25.3",
|
||||
"eslint-plugin-mocha": "^9.0.0",
|
||||
"eslint-plugin-node": "^11.1.0",
|
||||
"eslint-plugin-prettier": "^4.0.0",
|
||||
"eslint-plugin-promise": "^5.1.1",
|
||||
"mocha": "^9.1.3",
|
||||
"node-abi": "3.5.0",
|
||||
"node-gyp": "^7.1.2",
|
||||
|
|
@ -44,15 +46,15 @@
|
|||
"plop": "^2.7.6",
|
||||
"prebuildify": "^5.0.0",
|
||||
"prebuildify-cross": "^4.0.2",
|
||||
"prettier": "^2.4.1",
|
||||
"proxyquire": "^2.1.3",
|
||||
"semantic-release": "^18.0.1",
|
||||
"sinon": "^12.0.1"
|
||||
"sinon": "^12.0.1",
|
||||
"typescript": "^4.5.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=12.17.0 <13.0 || >=14.0.0"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "rm -rf dist && tsc -p tsconfig-build.json",
|
||||
"install": "node-gyp-build",
|
||||
"prebuild": "prebuildify --napi --target 14.0.0 --force --strip --verbose",
|
||||
"prebuild-cross": "prebuildify-cross --napi --target 14.0.0 --force --strip --verbose",
|
||||
|
|
@ -63,7 +65,8 @@
|
|||
"test": "nyc --reporter=html --reporter=text --reporter lcovonly mocha",
|
||||
"test:arduino": "TEST_PORT=$(./bin/find-arduino.js) npm test",
|
||||
"test:watch": "mocha -w",
|
||||
"semantic-release": "semantic-release"
|
||||
"semantic-release": "semantic-release",
|
||||
"typecheck": "tsc"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
|
|
@ -99,5 +102,12 @@
|
|||
"docs": "Documentation",
|
||||
"internal": "Chores"
|
||||
}
|
||||
},
|
||||
"mocha": {
|
||||
"bail": true,
|
||||
"require": [
|
||||
"esbuild-register"
|
||||
],
|
||||
"spec": "lib/**/*.test.*"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -50,7 +50,7 @@ SerialPortParity ToParityEnum(const Napi::String& str);
|
|||
SerialPortStopBits ToStopBitEnum(double stopBits);
|
||||
|
||||
struct OpenBaton : public Napi::AsyncWorker {
|
||||
OpenBaton(Napi::Function& callback) : Napi::AsyncWorker(callback, "node-serialport:OpenBaton"),
|
||||
OpenBaton(Napi::Function& callback) : Napi::AsyncWorker(callback, "node-serialport:OpenBaton"),
|
||||
errorString(), path() {}
|
||||
char errorString[ERROR_STRING_SIZE];
|
||||
char path[1024];
|
||||
|
|
@ -62,7 +62,6 @@ struct OpenBaton : public Napi::AsyncWorker {
|
|||
bool xon = false;
|
||||
bool xoff = false;
|
||||
bool xany = false;
|
||||
bool dsrdtr = false;
|
||||
bool hupcl = false;
|
||||
bool lock = false;
|
||||
SerialPortParity parity;
|
||||
|
|
@ -88,7 +87,7 @@ struct ConnectionOptions {
|
|||
};
|
||||
struct ConnectionOptionsBaton : ConnectionOptions , Napi::AsyncWorker {
|
||||
ConnectionOptionsBaton(Napi::Function& callback) : ConnectionOptions() , Napi::AsyncWorker(callback, "node-serialport:ConnectionOptionsBaton") {}
|
||||
|
||||
|
||||
void Execute() override;
|
||||
|
||||
void OnOK() override {
|
||||
|
|
@ -99,7 +98,7 @@ struct ConnectionOptionsBaton : ConnectionOptions , Napi::AsyncWorker {
|
|||
};
|
||||
|
||||
struct SetBaton : public Napi::AsyncWorker {
|
||||
SetBaton(Napi::Function& callback) : Napi::AsyncWorker(callback, "node-serialport:SetBaton"),
|
||||
SetBaton(Napi::Function& callback) : Napi::AsyncWorker(callback, "node-serialport:SetBaton"),
|
||||
errorString() {}
|
||||
int fd = 0;
|
||||
int result = 0;
|
||||
|
|
@ -121,7 +120,7 @@ struct SetBaton : public Napi::AsyncWorker {
|
|||
};
|
||||
|
||||
struct GetBaton : public Napi::AsyncWorker {
|
||||
GetBaton(Napi::Function& callback) : Napi::AsyncWorker(callback, "node-serialport:GetBaton"),
|
||||
GetBaton(Napi::Function& callback) : Napi::AsyncWorker(callback, "node-serialport:GetBaton"),
|
||||
errorString() {}
|
||||
int fd = 0;
|
||||
char errorString[ERROR_STRING_SIZE];
|
||||
|
|
@ -145,12 +144,12 @@ struct GetBaton : public Napi::AsyncWorker {
|
|||
};
|
||||
|
||||
struct GetBaudRateBaton : public Napi::AsyncWorker {
|
||||
GetBaudRateBaton(Napi::Function& callback) : Napi::AsyncWorker(callback, "node-serialport:GetBaudRateBaton"),
|
||||
GetBaudRateBaton(Napi::Function& callback) : Napi::AsyncWorker(callback, "node-serialport:GetBaudRateBaton"),
|
||||
errorString() {}
|
||||
int fd = 0;
|
||||
char errorString[ERROR_STRING_SIZE];
|
||||
int baudRate = 0;
|
||||
|
||||
|
||||
void Execute() override;
|
||||
|
||||
void OnOK() override {
|
||||
|
|
@ -163,7 +162,7 @@ struct GetBaudRateBaton : public Napi::AsyncWorker {
|
|||
};
|
||||
|
||||
struct VoidBaton : public Napi::AsyncWorker {
|
||||
VoidBaton(Napi::Function& callback, const char *resource_name) : Napi::AsyncWorker(callback, resource_name),
|
||||
VoidBaton(Napi::Function& callback, const char *resource_name) : Napi::AsyncWorker(callback, resource_name),
|
||||
errorString() {}
|
||||
int fd = 0;
|
||||
char errorString[ERROR_STRING_SIZE];
|
||||
|
|
|
|||
15
test/assert.ts
Normal file
15
test/assert.ts
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import { assert, use } from 'chai'
|
||||
import chaiSubset from 'chai-subset'
|
||||
use(chaiSubset)
|
||||
|
||||
export const shouldReject = async (promise: Promise<any>, errType = Error, message = 'Should have rejected') => {
|
||||
try {
|
||||
await promise
|
||||
} catch (err) {
|
||||
assert.instanceOf(err, errType)
|
||||
return err
|
||||
}
|
||||
throw new Error(message)
|
||||
}
|
||||
|
||||
export { assert }
|
||||
|
|
@ -1,9 +0,0 @@
|
|||
global.shouldReject = async (promise, errType = Error, message = 'Should have rejected') => {
|
||||
try {
|
||||
await promise
|
||||
} catch (err) {
|
||||
assert.instanceOf(err, errType)
|
||||
return err
|
||||
}
|
||||
throw new Error(message)
|
||||
}
|
||||
|
|
@ -1,4 +0,0 @@
|
|||
const chai = require('chai')
|
||||
const chaiSubset = require('chai-subset')
|
||||
global.assert = chai.assert
|
||||
chai.use(chaiSubset)
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
const fs = require('fs')
|
||||
const files = fs.readdirSync(__dirname).filter(file => file !== 'index.js' && file.match(/\.js$/))
|
||||
files.forEach(file => {
|
||||
console.log(`Loading ${file}`)
|
||||
require(`./${file}`)
|
||||
})
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
const testConfig = require('../test-config.json')
|
||||
|
||||
global.makeTestFeature = function makeTestFeature(envName) {
|
||||
const config = { ...testConfig.all, ...testConfig[envName] }
|
||||
return function testFeature(feature, description, callback) {
|
||||
if (config[feature] === false) {
|
||||
return it(`Feature "${feature}" is disabled in "${envName}. "${description}"`)
|
||||
}
|
||||
it(description, callback)
|
||||
}
|
||||
}
|
||||
43
test/makeTestFeature.ts
Normal file
43
test/makeTestFeature.ts
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
import testConfig from './config.json'
|
||||
|
||||
export const makeTestFeature = (envName: string, testPort?: string) => {
|
||||
const config = { ...testConfig.all, ...(testConfig as any)[envName] }
|
||||
|
||||
const testFeature = (feature: string, description: string, callback: () => any) => {
|
||||
if (config[feature] === false) {
|
||||
return it(`Feature "${feature}" is disabled in "${envName}. "${description}"`)
|
||||
}
|
||||
it(description, callback)
|
||||
}
|
||||
|
||||
const testHardware = (description: string, callback: () => any) => {
|
||||
if (!testPort) {
|
||||
return it(`${description} - Cannot be tested. Set the TEST_PORT env var with an available serialport for more testing.`)
|
||||
}
|
||||
it(description, callback)
|
||||
}
|
||||
|
||||
const testHardwareFeature = (feature: string, description: string, callback: () => any) => {
|
||||
if (!testPort) {
|
||||
return it(`${description} - Cannot be tested. Set the TEST_PORT env var with an available serialport for more testing.`)
|
||||
}
|
||||
if (config[feature] === false) {
|
||||
return it(`Feature "${feature}" is disabled in "${envName}. "${description}"`)
|
||||
}
|
||||
it(description, callback)
|
||||
}
|
||||
|
||||
const describeHardware = (description: string, callback: () => any) => {
|
||||
if (!testPort) {
|
||||
return it(`${description} - Cannot be tested. Set the TEST_PORT env var with an available serialport for more testing.`)
|
||||
}
|
||||
describe(description, callback)
|
||||
}
|
||||
|
||||
return {
|
||||
testFeature,
|
||||
testHardwareFeature,
|
||||
testHardware,
|
||||
describeHardware,
|
||||
}
|
||||
}
|
||||
13
tsconfig-build.json
Normal file
13
tsconfig-build.json
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "dist",
|
||||
"noEmit": false,
|
||||
"module": "commonjs"
|
||||
},
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"**/*.test.ts",
|
||||
"lib/mocks/*"
|
||||
]
|
||||
}
|
||||
23
tsconfig.json
Normal file
23
tsconfig.json
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"noEmit": true,
|
||||
"allowJs": false,
|
||||
"target": "es2017",
|
||||
"moduleResolution": "node",
|
||||
"module": "commonjs",
|
||||
"noImplicitAny": true,
|
||||
"strictNullChecks": true,
|
||||
"declaration": true,
|
||||
"importHelpers": false,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"useUnknownInCatchVariables": false,
|
||||
"esModuleInterop": true,
|
||||
"resolveJsonModule": true
|
||||
},
|
||||
"include": [
|
||||
"lib/**/*.ts",
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue