feat: new binding interface (#19)

- We now only return a port object if it's open and list and open methods are now exported on an interface
- hardware tests now work and only require a loopback (no ready event)
- Test pass on darwin (not on mock - it's not up to date yet and coverage is going to drop)
- cleanup up tests with modern javascript
- Breaking - change the names of the exported types
- No more constructors, now all binding specicific open options are specificd on open
- Arduino test file for loopback
This commit is contained in:
Francis Gulotta 2022-01-29 22:51:40 -05:00 • committed by GitHub
parent d7a855da8b
commit cf03d6ddd1
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
16 changed files with 481 additions and 596 deletions

View file

@ -31,6 +31,7 @@ The Bindings provide a low level interface to work with your serialport. It is p
1. Clone this repo `git clone git@github.com:serialport/bindings-cpp.git`
1. Run `npm install` to setup local package dependencies (run this any time you depend on a package local to this repo)
1. Run `npm test` to ensure everything is working properly
1. If you have a serial loopback device (TX to RX) you can run run `TEST_PORT=/path/to/port npm test` for a more comprehensive test suite. (Defaults to 115200 baud customize with the TEST_BAUD env.) You can use an arduino with the `test/arduino-echo` sketch.
### Developing Docs

View file

@ -1,42 +0,0 @@
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')
})
})

View file

@ -14,24 +14,28 @@ export interface PortInfo {
}
export interface OpenOptions {
/** The path of the port */
path: string
/** 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
/** Must be one of these: 8, 7, 6, or 5 defaults to 8 */
dataBits?: 8 | 7 | 6 | 5
/** Prevent other processes from opening the port. Windows does not currently support `false`. Defaults to true */
lock?: boolean
/** defaults to 1 - TODO should be a string */
stopBits?: 1 | 2 | 3
/** Device parity defaults to none */
parity?: 'none' | 'event' | 'mark' | 'odd' | 'space'
/** Flow control Setting. Defaults to false */
rtscts?: boolean
/** Flow control Setting. Defaults to false */
xon?: boolean
/** Flow control Setting. Defaults to false */
xoff?: boolean
/** Flow control Setting defaults to false*/
xany?: boolean
/** drop DTR on close. Defaults to true */
hupcl?: boolean
}
export interface UpdateOptions {
@ -56,31 +60,20 @@ export interface PortStatus {
/**
* 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.')
}
export interface BindingPortInterface {
readonly openOptions: Required<OpenOptions>
/**
* 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>
isOpen: boolean
/**
* Closes an open connection
*/
abstract close(): Promise<void>
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.
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) as it will attempt to read up to `length` number of bytes. This function has a guarantee that it will always return at least one byte. This leverages os specific polling or async reads so you don't have to.
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.
@ -88,7 +81,7 @@ export abstract class BindingInterface {
* @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 }>
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.
@ -97,39 +90,51 @@ export abstract class BindingInterface {
Resolves after the data is passed to the operating system for writing.
*/
abstract write(buffer: Buffer): Promise<void>
write(buffer: Buffer): Promise<void>
/**
Changes connection settings on an open port.
*/
abstract update(options: UpdateOptions): Promise<void>
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>
set(options: SetOptions): Promise<void>
/**
* Get the control flags (CTS, DSR, DCD) on the open port.
*/
abstract get(): Promise<PortStatus>
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 }>
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>
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>
drain(): Promise<void>
}
export interface BindingInterface<Port extends BindingPortInterface = BindingPortInterface, Open extends OpenOptions = OpenOptions> {
/**
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.
*/
list(): Promise<PortInfo[]>
/**
* Opens a connection to the serial port referenced by the path.
*/
open(options: Open): Promise<Port>
}

View file

@ -1,13 +1,18 @@
import { assert, shouldReject } from '../test/assert'
import { makeTestFeature } from '../test/makeTestFeature'
import { BindingInterface, OpenOptions, PortInfo, SetOptions } from './binding-interface'
import { autoDetect, AllBindingClasses } from './index'
import { autoDetect } from './index'
import MockBinding from '@serialport/binding-mock'
const defaultOpenOptions: OpenOptions = Object.freeze({
baudRate: 9600,
// All bindings are required to work with an "echo" firmware
const TEST_PORT = process.env.TEST_PORT
const TEST_BAUD = Number(process.env.TEST_BAUDRATE) || 115200
const defaultOpenOptions: OpenOptions = {
path: 'bad path',
baudRate: TEST_BAUD,
dataBits: 8,
hupcl: true,
hupcl: false,
lock: true,
parity: 'none',
rtscts: false,
@ -15,37 +20,31 @@ const defaultOpenOptions: OpenOptions = Object.freeze({
xany: false,
xoff: false,
xon: false,
})
}
const defaultSetFlags: SetOptions = Object.freeze({
const defaultSetFlags: SetOptions = {
brk: false,
cts: false,
dtr: true,
dts: false,
rts: true,
lowLatency: false,
})
}
type MockBinding = any
interface MockBinding extends BindingInterface {
createPort(path: string, options: any): void
}
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
// ready to echo. This allows for remote device boot up.
// the default firmware is called arduinoEcho.ino
const readyData = Buffer.from('READY')
// testBinding('mock', MockBinding, '/dev/exists')
testBinding(process.platform, autoDetect(), TEST_PORT)
testBinding('mock', MockBinding, '/dev/exists')
testBinding(process.platform, autoDetect(), process.env.TEST_PORT)
function testBinding(bindingName: string, Binding: AllBindingClasses, testPort?: string) {
const { testFeature, testHardware, describeHardware } = makeTestFeature(bindingName, testPort)
function testBinding(bindingName: string, Binding: BindingInterface, testPort?: string) {
const { testFeature, describeHardware } = makeTestFeature(bindingName, testPort)
describe(`bindings/${bindingName}`, () => {
before(() => {
if (bindingName === 'mock') {
(Binding as MockBinding).createPort(testPort, { echo: true, readyData })
(Binding as MockBinding).createPort(testPort!, { echo: true })
}
})
@ -72,430 +71,301 @@ function testBinding(bindingName: string, Binding: AllBindingClasses, testPort?:
})
})
})
})
describe('constructor', () => {
it('creates a binding object', () => {
const binding = new Binding()
assert.instanceOf(binding, Binding)
})
})
describe('instance property', () => {
describe('#isOpen', () => {
if (!testPort) {
it('Cannot be tested. Set the TEST_PORT env var with an available serialport for more testing.')
return
}
let binding: BindingInterface
beforeEach(() => {
binding = new Binding()
})
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)
})
})
})
describe('instance method', () => {
describe('#open', () => {
let binding: BindingInterface
beforeEach(() => {
binding = new Binding()
})
describeHardware('.open', () => {
it('errors when providing a bad port', async () => {
const err = await shouldReject(binding.open('COMBAD', defaultOpenOptions))
const err = await shouldReject(Binding.open({
path: 'COMBAD',
baudRate: 115200,
}))
assert.include(err.message, 'COMBAD')
assert.equal(binding.isOpen, false)
})
it('throws when not given a path', async () => {
await shouldReject(binding.open(''), TypeError)
await shouldReject(Binding.open({
path: '',
baudRate: 115200,
}), TypeError)
})
it('throws when not given a baudRate', async () => {
const err = await shouldReject(Binding.open({
path: 'COMBAD',
baudRate: undefined,
} as any))
assert.include(err.message, 'baudRate')
})
it('throws when not given options', async () => {
await shouldReject(binding.open('COMBAD'), TypeError)
const err = await shouldReject(Binding.open(undefined as any))
assert.include(err.message, 'options')
})
if (!testPort) {
it('Cannot be tested further. Set the TEST_PORT env var with an available serialport for more testing.')
return
}
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()
const port = await Binding.open({ ...defaultOpenOptions, path: testPort! })
assert.equal(port.isOpen, true)
await port.close()
assert.equal(port.isOpen, false)
})
})
describeHardware('arbitrary baud rates', () => {
[25000, 1000000, 250000].forEach(testBaud => {
describe(`${testBaud} baud`, () => {
const customRates = { ...defaultOpenOptions, baudRate: testBaud }
const customRates = { ...defaultOpenOptions, baudRate: testBaud, path: testPort! }
testFeature(`baudrate.${testBaud}`, `opens at ${testBaud} baud`, async () => {
await binding.open(testPort, customRates)
assert.equal(binding.isOpen, true)
await binding.close()
const port = await Binding.open(customRates)
assert.equal(port.isOpen, true)
await port.close()
})
testFeature(`baudrate.${testBaud}_check`, `sets ${testBaud} baud successfully`, async () => {
await binding.open(testPort, customRates)
const { baudRate } = await binding.getBaudRate()
const port = await Binding.open(customRates)
const { baudRate } = await port.getBaudRate()
assert.equal(baudRate, customRates.baudRate)
return binding.close()
await port.close()
})
})
})
})
describeHardware('optional locking', () => {
const options = { ...defaultOpenOptions, path: testPort!, lock: true }
it('locks the port by default', async () => {
const binding2 = new Binding()
await binding.open(testPort, defaultOpenOptions)
assert.equal(binding.isOpen, true)
await shouldReject(binding2.open(testPort, defaultOpenOptions))
assert.equal(binding2.isOpen, false)
await binding.close()
const port = await Binding.open(options)
assert.equal(port.isOpen, true)
await shouldReject(Binding.open(options))
await port.close()
})
testFeature('open.unlock', 'can unlock the port', async () => {
const noLock = { ...defaultOpenOptions, lock: false }
const binding2 = new Binding()
const noLock = { ...options, lock: false }
await binding.open(testPort, noLock)
assert.equal(binding.isOpen, true)
const port = await Binding.open(noLock)
assert.equal(port.isOpen, true)
await binding2.open(testPort, noLock)
assert.equal(binding2.isOpen, true)
const port2 = await Binding.open(noLock)
assert.equal(port2.isOpen, true)
await Promise.all([binding.close(), binding2.close()])
await Promise.all([port.close(), port2.close()])
})
})
})
})
describeHardware('PortInstance', () => {
const options = { ...defaultOpenOptions, path: testPort! }
describe('#isOpen', () => {
it('is true after open and false after close', async () => {
const port = await Binding.open(options)
assert.equal(port.isOpen, true)
await port.close()
assert.equal(port.isOpen, false)
})
})
describe('#close', () => {
let binding: BindingInterface
beforeEach(() => {
binding = new Binding()
})
it('errors when already closed', async () => {
await shouldReject(binding.close())
const port = await Binding.open(options)
assert.equal(port.isOpen, true)
await port.close()
assert.equal(port.isOpen, false)
await shouldReject(port.close())
})
testHardware('closes an open file descriptor', () => {
return binding.open(testPort!, defaultOpenOptions).then(() => {
assert.equal(binding.isOpen, true)
return binding.close()
})
it('closes an open port', async () => {
const port = await Binding.open(options)
await port.close()
assert.equal(port.isOpen, false)
})
})
describe('#update', () => {
it('throws when not given an object', async () => {
const binding = new Binding()
await shouldReject((binding as any).update(), TypeError)
it('errors when not given an object', async () => {
const port = await Binding.open(options)
await shouldReject(port.update(undefined as any), TypeError)
await port.close()
})
it('errors asynchronously when not open', done => {
const binding = new Binding()
let noZalgo = false
binding.update({ baudRate: 9600 }).catch(err => {
assert.instanceOf(err, Error)
assert(noZalgo)
done()
})
noZalgo = true
it('errors when updating nothing', async () => {
const port = await Binding.open(options)
await shouldReject(port.update({} as any), Error)
await port.close()
})
describeHardware('update with hardware', () => {
let binding: BindingInterface
beforeEach(() => {
binding = new Binding()
return binding.open(testPort!, defaultOpenOptions)
})
it('errors when closed', async () => {
const port = await Binding.open(options)
await port.close()
await shouldReject(port.update({ baudRate: 57600 }), Error)
})
afterEach(() => binding.close())
it('throws errors when updating nothing', async () => {
await shouldReject((binding as any).update({}), Error)
})
it('errors when not called with options', async () => {
await shouldReject(
(binding as any).set(() => { }),
Error,
)
})
it('updates baudRate', () => {
return binding.update({ baudRate: 57600 })
})
testFeature('getBaudRate', 'updates baudRate', async () => {
const port = await Binding.open(options)
await port.update({ baudRate: 57600 })
const { baudRate } = await port.getBaudRate()
assert.equal(baudRate, 57600)
await port.close()
})
})
describe('#write', () => {
it('errors asynchronously when not open', done => {
const binding = new Binding()
let noZalgo = false
binding
.write(Buffer.from([]))
.then(
data => {
console.log({ data })
throw new Error('Should have errored')
},
err => {
assert.instanceOf(err, Error)
assert(noZalgo)
done()
},
)
.catch(done)
noZalgo = true
})
it('rejects when not given a buffer', async () => {
const binding = new Binding()
await shouldReject((binding as any).write(null), TypeError)
})
describeHardware('with hardware', () => {
let binding: BindingInterface
beforeEach(() => {
binding = new Binding()
return binding.open(testPort!, defaultOpenOptions)
})
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 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)
})
})
})
describe('#drain', () => {
it('errors asynchronously when not open', done => {
const binding = new Binding()
let noZalgo = false
binding.drain().catch(err => {
assert.instanceOf(err, Error)
assert(noZalgo)
done()
})
noZalgo = true
})
if (!testPort) {
it('Cannot be tested further. Set the TEST_PORT env var with an available serialport for more testing.')
return
}
let binding: BindingInterface
beforeEach(() => {
binding = new Binding()
return binding.open(testPort, defaultOpenOptions)
})
afterEach(() => binding.close())
it('drains the port', () => {
return binding.drain()
})
it('waits for in progress writes to finish', async () => {
let finishedWrite = false
const write = binding.write(Buffer.alloc(1024 * 2)).then(() => {
finishedWrite = true
})
await binding.drain()
assert.isTrue(finishedWrite)
await write
})
})
describe('#flush', () => {
it('errors asynchronously when not open', done => {
const binding = new Binding()
let noZalgo = false
binding.flush().catch(err => {
assert.instanceOf(err, Error)
assert(noZalgo)
done()
})
noZalgo = true
})
if (!testPort) {
it('Cannot be tested further. Set the TEST_PORT env var with an available serialport for more testing.')
return
}
let binding: BindingInterface
beforeEach(() => {
binding = new Binding()
return binding.open(testPort, defaultOpenOptions)
})
afterEach(() => binding.close())
it('flushes the port', () => {
return binding.flush()
})
})
describe('#set', () => {
it('errors asynchronously when not open', done => {
const binding = new Binding()
let noZalgo = false
binding.set(defaultSetFlags).catch(err => {
assert.instanceOf(err, Error)
assert(noZalgo)
done()
})
noZalgo = true
})
it('throws when not called with options', async () => {
const binding = new Binding()
await shouldReject(
(binding as any).set(() => { }),
TypeError,
)
})
if (!testPort) {
it('Cannot be tested further. Set the TEST_PORT env var with an available serialport for more testing.')
return
}
let binding: BindingInterface
beforeEach(() => {
binding = new Binding()
return binding.open(testPort, defaultOpenOptions)
})
afterEach(() => binding.close())
testFeature('set.set', 'sets flags on the port', () => {
return binding.set(defaultSetFlags)
})
})
// because of the nature of opening and closing the ports a fair amount of data
// is left over on the pipe and isn't cleared when flushed on unix
describe('#read', () => {
it('errors asynchronously when not open', done => {
const binding = new Binding()
const smallSampleData = Buffer.from('12345')
it('errors when closed', async () => {
const buffer = Buffer.alloc(5)
let noZalgo = false
binding.read(buffer, 0, buffer.length).catch(err => {
assert.instanceOf(err, Error)
assert(noZalgo)
done()
})
noZalgo = true
const port = await Binding.open(options)
await port.close()
await shouldReject(port.read(buffer, 0, buffer.length), Error)
})
if (!testPort) {
it('Cannot be tested further. Set the TEST_PORT env var with an available serialport for more testing.')
return
}
let binding: BindingInterface
let buffer: Buffer
beforeEach(async () => {
buffer = Buffer.alloc(readyData.length)
binding = new Binding()
await binding.open(testPort, defaultOpenOptions)
})
afterEach(() => binding.isOpen && binding.close())
it('doesn\'t throw if the port is open', async () => {
await binding.read(buffer, 0, buffer.length)
it('reads requested number of bytes', async () => {
const buffer = Buffer.alloc(smallSampleData.length)
const port = await Binding.open(options)
await port.write(smallSampleData)
await port.read(buffer, 0, buffer.length)
assert.deepEqual(smallSampleData, buffer, 'Data matches')
await port.close()
})
it('returns at maximum the requested number of bytes and the buffer', async () => {
const { bytesRead, buffer: returnedBuffer } = await binding.read(buffer, 0, 1)
const buffer = Buffer.alloc(smallSampleData.length)
const port = await Binding.open(options)
await port.write(smallSampleData)
const { bytesRead, buffer: returnedBuffer } = await port.read(buffer, 0, 1)
assert.equal(bytesRead, 1)
assert.equal(buffer, returnedBuffer)
assert.strictEqual(buffer, returnedBuffer)
assert.deepEqual(buffer, Buffer.from([smallSampleData[0], 0, 0, 0, 0]))
await port.close()
})
it('cancels the read when the port is closed', async () => {
let bytesToRead = 0
while (bytesToRead < readyData.length) {
const { bytesRead } = await binding.read(buffer, 0, readyData.length)
bytesToRead += bytesRead
}
const readError = shouldReject(binding.read(Buffer.allocUnsafe(100), 0, 100))
await binding.close()
const port = await Binding.open(options)
const readError = shouldReject(port.read(Buffer.alloc(100), 0, 100))
await port.close()
const err = await readError
assert.isTrue(err.canceled)
})
})
describe('#write', () => {
it('errors when not given a buffer', async () => {
const port = await Binding.open(options)
await shouldReject(port.write(null as any), TypeError)
await port.close()
})
it('errors when closed', async () => {
const data = Buffer.from('data!')
const port = await Binding.open(options)
await port.close()
await shouldReject(port.write(data), Error)
})
it('resolves after a small write', async () => {
const data = Buffer.from('simple write of 24 bytes')
const port = await Binding.open(options)
await port.write(data)
await port.close()
})
it('resolves after a large write (2k)', async function () {
this.timeout(20000)
const data = Buffer.alloc(1024 * 2)
const port = await Binding.open(options)
await port.write(data)
await port.close()
})
it('resolves after an empty write', async () => {
const data = Buffer.from([])
const port = await Binding.open(options)
await port.write(data)
await port.close()
})
})
describe('#drain', () => {
it('errors when closed', async () => {
const port = await Binding.open(options)
await port.close()
await shouldReject(port.drain(), Error)
})
it('drains the port', async () => {
const port = await Binding.open(options)
await port.drain()
await port.close()
})
it('waits for in progress writes to finish', async () => {
const port = await Binding.open(options)
let finishedWrite = false
const write = port.write(Buffer.alloc(1024 * 2)).then(() => {
finishedWrite = true
})
await port.drain()
assert.isTrue(finishedWrite)
await write
await port.close()
})
})
describe('#flush', () => {
it('errors when closed', async () => {
const port = await Binding.open(options)
await port.close()
await shouldReject(port.flush(), Error)
})
it('flushes the port', async () => {
const port = await Binding.open(options)
await port.flush()
await port.close()
})
})
describe('#set', () => {
it('errors when closed', async () => {
const port = await Binding.open(options)
await port.close()
await shouldReject(port.set(defaultSetFlags), Error)
})
it('throws when not called with options', async () => {
const port = await Binding.open(options)
await shouldReject(port.set(undefined as any), TypeError)
await port.close()
})
it('sets flags on the port', async () => {
const port = await Binding.open(options)
await port.set(defaultSetFlags)
await port.close()
})
})
describe('#get', () => {
it('errors asynchronously when not open', done => {
const binding = new Binding()
let noZalgo = false
binding.get().catch(err => {
assert.instanceOf(err, Error)
assert(noZalgo)
done()
})
noZalgo = true
it('errors when closed', async () => {
const port = await Binding.open(options)
await port.close()
await shouldReject(port.get(), Error)
})
if (!testPort) {
it('Cannot be tested further. Set the TEST_PORT env var with an available serialport for more testing.')
return
}
let binding: BindingInterface
beforeEach(() => {
binding = new Binding()
return binding.open(testPort, defaultOpenOptions)
})
afterEach(() => binding.close())
testFeature('get.get', 'gets modem line status from the port', () => {
return binding.get().then(status => {
assert.isObject(status)
assert.isBoolean(status.cts)
assert.isBoolean(status.dsr)
assert.isBoolean(status.dcd)
})
it('gets modem line status from the port', async () => {
const port = await Binding.open(options)
const status = await port.get()
assert.isObject(status)
assert.isBoolean(status.cts)
assert.isBoolean(status.dsr)
assert.isBoolean(status.dcd)
await port.close()
})
})
})

View file

@ -1,42 +1,72 @@
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 { BindingPortInterface } from '.'
import { BindingInterface, OpenOptions, PortStatus, SetOptions, UpdateOptions } from './binding-interface'
import { asyncClose, asyncDrain, asyncFlush, asyncGet, 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 {
export interface DarwinOpenOptions extends OpenOptions {
/** 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
}
export const DarwinBinding: BindingInterface<DarwinPortBinding, DarwinOpenOptions> = {
list() {
debug('list')
return asyncList()
},
async open(options) {
if (!options || typeof options !== 'object' || Array.isArray(options)) {
throw new TypeError('"options" is not an object')
}
if (!options.path) {
throw new TypeError('"path" is not a valid port')
}
if (!options.baudRate) {
throw new TypeError('"baudRate" is not a valid baudRate')
}
debug('open')
const openOptions: Required<DarwinOpenOptions> = {
vmin: 1,
vtime: 0,
dataBits: 8,
lock: true,
stopBits: 1,
parity: 'none',
rtscts: false,
xon: false,
xoff: false,
xany: false,
hupcl: true,
...options,
}
const fd: number = await asyncOpen(openOptions.path, openOptions)
return new DarwinPortBinding(fd, openOptions)
},
}
/**
* The Darwin binding layer for OSX
*/
export class DarwinBinding extends BindingInterface {
bindingOptions: DarwinBindingOptions
export class DarwinPortBinding implements BindingPortInterface {
readonly openOptions: Required<DarwinOpenOptions>
readonly poller: Poller
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
constructor(fd:number, options: Required<DarwinOpenOptions>) {
this.fd = fd
this.openOptions = options
this.poller = new Poller(fd)
this.writeOperation = null
}
@ -44,26 +74,6 @@ export class DarwinBinding extends BindingInterface {
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) {
@ -71,10 +81,8 @@ export class DarwinBinding extends BindingInterface {
}
const fd = this.fd
this.poller?.stop()
this.poller?.destroy()
this.poller = null
this.openOptions = null
this.poller.stop()
this.poller.destroy()
this.fd = null
await asyncClose(fd)
}
@ -117,9 +125,9 @@ export class DarwinBinding extends BindingInterface {
}
debug('write', buffer.length, 'bytes')
if (!this.isOpen) {
debug('write', 'error port is not open')
throw new Error('Port is not open')
}
@ -134,7 +142,8 @@ export class DarwinBinding extends BindingInterface {
}
async update(options: UpdateOptions): Promise<void> {
if (typeof options !== 'object') {
if (!options || typeof options !== 'object' || Array.isArray(options)) {
throw TypeError('"options" is not an object')
}
@ -150,7 +159,8 @@ export class DarwinBinding extends BindingInterface {
}
async set(options: SetOptions): Promise<void> {
if (typeof options !== 'object') {
if (!options || typeof options !== 'object' || Array.isArray(options)) {
throw new TypeError('"options" is not an object')
}
debug('set', options)
@ -173,7 +183,7 @@ export class DarwinBinding extends BindingInterface {
if (!this.isOpen) {
throw new Error('Port is not open')
}
return asyncGetBaudRate(this.fd)
throw new Error('getBaudRate is not implemented on darwin')
}
async flush(): Promise<void> {

View file

@ -1,22 +1,24 @@
/* eslint-disable @typescript-eslint/no-var-requires */
import debugFactory from 'debug'
import { DarwinBinding } from './darwin'
import { LinuxBinding } from './linux'
import { WindowsBinding } from './win32'
import { BindingInterface } from './binding-interface'
import { DarwinBinding, DarwinPortBinding, DarwinOpenOptions } from './darwin'
import { LinuxBinding, LinuxPortBinding, LinuxOpenOptions } from './linux'
import { WindowsBinding, WindowsPortBinding } from './win32'
const debug = debugFactory('serialport/bindings-cpp')
export * from './darwin'
export * from './linux'
export * from './win32'
export * from './binding-interface'
export * from './errors'
export type AllBindingClasses = typeof WindowsBinding | typeof DarwinBinding | typeof LinuxBinding
export type AllBindings = WindowsBinding | DarwinBinding | LinuxBinding
export type AutoDetectTypes = BindingInterface<DarwinPortBinding, DarwinOpenOptions> | BindingInterface<WindowsPortBinding> | BindingInterface<LinuxPortBinding, LinuxOpenOptions>
/**
* This is an auto detected binding for your current platform
*/
export const autoDetect = (): AllBindingClasses => {
export function autoDetect(): AutoDetectTypes
{
switch (process.platform) {
case 'win32':
debug('loading WindowsBinding')

View file

@ -28,7 +28,7 @@ function decodeHexEscape(str: string) {
function propVal(name: string, val: string) {
if (name === 'pnpId') {
const match = val.match(/\/by-id\/([^\s]+)/)
return (match && match[1]) || undefined
return (match?.[1]) || undefined
}
if (name === 'manufacturer') {
return decodeHexEscape(val)

View file

@ -5,10 +5,11 @@ 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'
import { BindingPortInterface } from '.'
const debug = debugFactory('serialport/bindings-cpp')
export interface LinuxBindingOptions {
export interface LinuxOpenOptions extends OpenOptions {
/** 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 */
@ -25,29 +26,58 @@ export interface LinuxSetOptions extends SetOptions {
lowLatency?: boolean
}
export const LinuxBinding: BindingInterface<LinuxPortBinding, LinuxOpenOptions> = {
list() {
debug('list')
return linuxList()
},
async open(options) {
if (!options || typeof options !== 'object' || Array.isArray(options)) {
throw new TypeError('"options" is not an object')
}
if (!options.path) {
throw new TypeError('"path" is not a valid port')
}
if (!options.baudRate) {
throw new TypeError('"baudRate" is not a valid baudRate')
}
debug('open')
const openOptions: Required<LinuxOpenOptions> = {
vmin: 1,
vtime: 0,
dataBits: 8,
lock: true,
stopBits: 1,
parity: 'none',
rtscts: false,
xon: false,
xoff: false,
xany: false,
hupcl: true,
...options,
}
const fd: number = await asyncOpen(openOptions.path, openOptions)
this.fd = fd
return new LinuxPortBinding(fd, openOptions)
},
}
/**
* 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
export class LinuxPortBinding implements BindingPortInterface {
readonly openOptions: Required<LinuxOpenOptions>
readonly poller: Poller
private writeOperation: Promise<void> | null
public fd: number | null
static list() {
debug('list')
return linuxList()
}
constructor(opt?: LinuxBindingOptions) {
super()
this.bindingOptions = {
vmin: 1,
vtime: 0,
...opt,
}
this.fd = null
constructor(fd: number, openOptions: Required<LinuxOpenOptions>) {
this.fd = fd
this.openOptions = openOptions
this.poller = new Poller(fd)
this.writeOperation = null
}
@ -55,25 +85,6 @@ export class LinuxBinding extends BindingInterface {
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) {
@ -81,10 +92,8 @@ export class LinuxBinding extends BindingInterface {
}
const fd = this.fd
this.poller?.stop()
this.poller?.destroy()
this.poller = null
this.openOptions = null
this.poller.stop()
this.poller.destroy()
this.fd = null
await asyncClose(fd)
}
@ -129,7 +138,6 @@ export class LinuxBinding extends BindingInterface {
debug('write', buffer.length, 'bytes')
if (!this.isOpen) {
debug('write', 'error port is not open')
throw new Error('Port is not open')
}
@ -144,7 +152,8 @@ export class LinuxBinding extends BindingInterface {
}
async update(options: UpdateOptions): Promise<void> {
if (typeof options !== 'object') {
if (!options || typeof options !== 'object' || Array.isArray(options)) {
throw TypeError('"options" is not an object')
}
@ -160,7 +169,8 @@ export class LinuxBinding extends BindingInterface {
}
async set(options: LinuxSetOptions): Promise<void> {
if (typeof options !== 'object') {
if (!options || typeof options !== 'object' || Array.isArray(options)) {
throw new TypeError('"options" is not an object')
}
debug('set')

View file

@ -1,5 +1,5 @@
import { assert, shouldReject } from '../test/assert'
import { LinuxBinding } from './linux'
import { LinuxPortBinding } from './linux'
import { unixRead } from './unix-read'
const makeFsRead =
@ -33,7 +33,7 @@ const sequenceCalls = (...functions: Function[]) => {
}
}
const makeMockBinding = (): LinuxBinding => {
const makeMockBinding = (): LinuxPortBinding => {
return {
isOpen: true,
fd: 1,
@ -46,7 +46,7 @@ const makeMockBinding = (): LinuxBinding => {
}
describe('unixRead', () => {
let mock: LinuxBinding
let mock: LinuxPortBinding
beforeEach(() => {
mock = makeMockBinding()
})

View file

@ -2,13 +2,13 @@ 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'
import { LinuxPortBinding } from './linux'
import { DarwinPortBinding } from './darwin'
const logger = debugFactory('serialport/bindings-cpp/unixRead')
const readAsync = promisify(fsRead)
const readable = (binding: LinuxBinding | DarwinBinding) => {
const readable = (binding: LinuxPortBinding | DarwinPortBinding) => {
return new Promise<void>((resolve, reject) => {
if (!binding.poller) {
throw new Error('No poller on bindings')
@ -18,7 +18,7 @@ const readable = (binding: LinuxBinding | DarwinBinding) => {
}
interface UnixReadOptions {
binding: LinuxBinding | DarwinBinding
binding: LinuxPortBinding | DarwinPortBinding
buffer: Buffer
offset: number
length: number

View file

@ -1,20 +1,20 @@
import { write } from 'fs'
import debugFactory from 'debug'
import { promisify } from 'util'
import { LinuxBinding } from './linux'
import { DarwinBinding } from './darwin'
import { LinuxPortBinding } from './linux'
import { DarwinPortBinding } from './darwin'
const logger = debugFactory('serialport/bindings-cpp/unixWrite')
const writeAsync = promisify(write)
const writable = (binding: LinuxBinding | DarwinBinding) => {
const writable = (binding: LinuxPortBinding | DarwinPortBinding) => {
return new Promise<void>((resolve, reject) => {
binding.poller?.once('writable', err => (err ? reject(err) : resolve()))
binding.poller.once('writable', err => (err ? reject(err) : resolve()))
})
}
interface UnixWriteOptions {
binding: LinuxBinding | DarwinBinding
binding: LinuxPortBinding | DarwinPortBinding
buffer: Buffer
offset?: number
fsWriteAsync?: typeof writeAsync

View file

@ -1,19 +1,13 @@
import debugFactory from 'debug'
import { BindingPortInterface } from '.'
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() {
export const WindowsBinding: BindingInterface<WindowsPortBinding> = {
async list() {
const ports: PortInfo[] = await asyncList()
// Grab the serial number from the pnp id
return ports.map(port => {
@ -28,11 +22,51 @@ export class WindowsBinding extends BindingInterface {
}
return port
})
}
},
async open(options) {
if (!options || typeof options !== 'object' || Array.isArray(options)) {
constructor() {
super()
this.fd = null
throw new TypeError('"options" is not an object')
}
if (!options.path) {
throw new TypeError('"path" is not a valid port')
}
if (!options.baudRate) {
throw new TypeError('"baudRate" is not a valid baudRate')
}
debug('open')
const openOptions: Required<OpenOptions> = {
dataBits: 8,
lock: true,
stopBits: 1,
parity: 'none',
rtscts: false,
xon: false,
xoff: false,
xany: false,
hupcl: true,
...options,
}
const fd = await asyncOpen(openOptions.path, openOptions)
return new WindowsPortBinding(fd, openOptions)
},
}
/**
* The Windows binding layer
*/
export class WindowsPortBinding implements BindingPortInterface {
fd: null | number
writeOperation: Promise<void> | null
openOptions: Required<OpenOptions>
constructor(fd: number, options: Required<OpenOptions>) {
this.fd = fd
this.openOptions = options
this.writeOperation = null
}
@ -40,24 +74,6 @@ export class WindowsBinding extends BindingInterface {
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) {
@ -127,7 +143,8 @@ export class WindowsBinding extends BindingInterface {
}
async update(options: UpdateOptions): Promise<void> {
if (typeof options !== 'object') {
if (!options || typeof options !== 'object' || Array.isArray(options)) {
throw TypeError('"options" is not an object')
}
@ -143,7 +160,8 @@ export class WindowsBinding extends BindingInterface {
}
async set(options: SetOptions): Promise<void> {
if (typeof options !== 'object') {
if (!options || typeof options !== 'object' || Array.isArray(options)) {
throw new TypeError('"options" is not an object')
}
debug('set', options)

View file

@ -90,7 +90,7 @@ void OpenBaton::Execute() {
return;
}
if (-1 == setup(fd, this)) {
if (-1 == setup(fd, this)) {
this->SetError(errorString);
close(fd);
return;

View file

@ -0,0 +1,13 @@
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(115200);
Serial.write("READY");
}
void loop() {
while (Serial.available()) {
uint8_t oneByteData = Serial.read();
Serial.write(oneByteData);
}
}

View file

@ -7,6 +7,7 @@
"port.update-baudrate": false
},
"darwin": {
"getBaudRate": false,
"baudrate.25000_check": false,
"baudrate.1000000_check": false,
"baudrate.250000_check": false

View file

@ -16,8 +16,5 @@
},
"include": [
"lib/**/*.ts",
],
"exclude": [
"node_modules"
]
}