mirror of
https://github.com/siemens-mobile-hacks/node-serialport-bindings-cpp.git
synced 2026-11-25 18:37:19 +00:00
Streams rewrite
This is a major change. To reading, the poller and the bindings layer, there isn’t a great way to do this piecemeal. The goal here is to make bindings a plugin layer, our c++ bindings isolated and tested, and make Serialport a streams object.
- Move all bindings into platform specific modules DarwinBinding LinuxBinding, and WindowsBinding
- Separate out the bindings from the SerialPort class so it can be required by itself.
- Provide mock bindings as a tested first class bindings layer
- Mixin stream methods with `pushBindingWrap`, inspired from fs.readStream
- All integration tests now require an Arduino
- Ditch sandboxed modules as we don't need to be that heavy handed to test anymore
TODO
- windows binding
- performance test
- memory leak test
- 🎉
This commit is contained in:
parent
9f8a359a86
commit
39d0103937
28 changed files with 2594 additions and 1619 deletions
|
|
@ -313,9 +313,9 @@ port.write(new Buffer('Hi Mom!'));
|
|||
|
||||
Enjoy and do cool things with this code.
|
||||
|
||||
{{#modules~}}
|
||||
{{#module name="serialport"}}
|
||||
{{>members~}}
|
||||
{{/modules}}
|
||||
{{/module}}
|
||||
|
||||
## Command Line Tools
|
||||
If you install `serialport` globally. (eg, `npm install -g serialport`) you'll receive two command line tools.
|
||||
|
|
|
|||
355
README.md
355
README.md
|
|
@ -65,23 +65,37 @@ For getting started with node-serialport, we recommend you begin with the follow
|
|||
* _instance_
|
||||
* [`.open([callback])`](#module_serialport--SerialPort+open)
|
||||
* [`.update([options], [callback])`](#module_serialport--SerialPort+update)
|
||||
* [`.write(data, [callback])`](#module_serialport--SerialPort+write)
|
||||
* [`.pause()`](#module_serialport--SerialPort+pause)
|
||||
* [`.resume()`](#module_serialport--SerialPort+resume)
|
||||
* [`.write(data, [encoding], [callback])`](#module_serialport--SerialPort+write) ⇒ <code>boolean</code>
|
||||
* [`.read([size])`](#module_serialport--SerialPort+read) ⇒ <code>string</code> | <code>Buffer</code> | <code>null</code>
|
||||
* [`.close(callback)`](#module_serialport--SerialPort+close)
|
||||
* [`.set([options], [callback])`](#module_serialport--SerialPort+set)
|
||||
* [`.get([callback])`](#module_serialport--SerialPort+get)
|
||||
* [`.flush([callback])`](#module_serialport--SerialPort+flush)
|
||||
* [`.drain([callback])`](#module_serialport--SerialPort+drain)
|
||||
* [`Event: "data"`](#module_serialport--SerialPort+event_data)
|
||||
* [`.pause()`](#module_serialport--SerialPort+pause) ⇒
|
||||
* [`.resume()`](#module_serialport--SerialPort+resume) ⇒
|
||||
* [`Event: "error"`](#module_serialport--SerialPort+event_error)
|
||||
* [`Event: "open"`](#module_serialport--SerialPort+event_open)
|
||||
* [`Event: "data"`](#module_serialport--SerialPort+event_data)
|
||||
* [`Event: "disconnect"`](#module_serialport--SerialPort+event_disconnect)
|
||||
* [`Event: "close"`](#module_serialport--SerialPort+event_close)
|
||||
* _static_
|
||||
* [`.Binding`](#module_serialport--SerialPort.Binding) : <code>[Binding](#module_serialport--SerialPort..Binding)</code>
|
||||
* [`.parsers`](#module_serialport--SerialPort.parsers) : <code>object</code>
|
||||
* [`.list`](#module_serialport--SerialPort.list) : <code>function</code>
|
||||
* [`.list(callback)`](#module_serialport--SerialPort.list) : <code>function</code>
|
||||
* _inner_
|
||||
* [~Binding](#module_serialport--SerialPort..Binding) : <code>Class</code>
|
||||
* [`new Binding(options)`](#new_module_serialport--SerialPort..Binding_new)
|
||||
* [`.list(callback)`](#module_serialport--SerialPort..Binding+list)
|
||||
* [`.open(path, openOptions, openCallback)`](#module_serialport--SerialPort..Binding+open)
|
||||
* [`.close(callback)`](#module_serialport--SerialPort..Binding+close)
|
||||
* [`.read(data, length, readCallback)`](#module_serialport--SerialPort..Binding+read)
|
||||
* [`.write(data, writeCallback)`](#module_serialport--SerialPort..Binding+write)
|
||||
* [`.set([options], callback)`](#module_serialport--SerialPort..Binding+set)
|
||||
* [`.get([callback])`](#module_serialport--SerialPort..Binding+get)
|
||||
* [`.flush(callback)`](#module_serialport--SerialPort..Binding+flush)
|
||||
* [`.drain(callback)`](#module_serialport--SerialPort..Binding+drain)
|
||||
* [`~readCallback`](#module_serialport--SerialPort..readCallback) : <code>function</code>
|
||||
* [`~errorCallback`](#module_serialport--SerialPort..errorCallback) : <code>function</code>
|
||||
* [`~modemBitsCallback`](#module_serialport--SerialPort..modemBitsCallback) : <code>function</code>
|
||||
* [`~openOptions`](#module_serialport--SerialPort..openOptions) : <code>Object</code>
|
||||
|
|
@ -354,8 +368,10 @@ Enjoy and do cool things with this code.
|
|||
|
||||
| Name | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| baudRate | <code>number</code> | The port's baudRate, use `.update` to change it. Read Only. |
|
||||
| binding | <code>object</code> | The binding object backing the port Read Only. |
|
||||
| isOpen | <code>boolean</code> | `true` if the port is open, `false` otherwise. Read Only. |
|
||||
| path | <code>string</code> | The system path or name of the serial port. Read Only. |
|
||||
| isOpen | <code>boolean</code> | true if the port is open, false otherwise. Read Only. |
|
||||
|
||||
|
||||
-
|
||||
|
|
@ -412,34 +428,39 @@ Changes the baud rate for an open port. Throws if you provide a bad argument. Em
|
|||
|
||||
<a name="module_serialport--SerialPort+write"></a>
|
||||
|
||||
#### `serialPort.write(data, [callback])`
|
||||
#### `serialPort.write(data, [encoding], [callback])` ⇒ <code>boolean</code>
|
||||
Writes data to the given serial port. Buffers written data if the port is not open.
|
||||
|
||||
The write operation is non-blocking. When it returns, data may still have not actually been written to the serial port. See `drain()`.
|
||||
|
||||
Some devices like the Arduino reset when you open a connection to them. In these cases if you immediately write to the device they wont be ready to receive the data. This is often worked around by having the Arduino send a "ready" byte that your node program waits for before writing. You can also often get away with waiting around 400ms.
|
||||
|
||||
Even though serialport is a stream, when writing it can accept arrays of bytes in addition to strings and buffers. This extra functionality is pretty sweet.
|
||||
|
||||
**Kind**: instance method of <code>[SerialPort](#exp_module_serialport--SerialPort)</code>
|
||||
**Returns**: <code>boolean</code> - `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| data | <code>string</code> | <code>array</code> | <code>buffer</code> | Accepts a [`Buffer` ](http://nodejs.org/api/buffer.html) object, or a type that is accepted by the `Buffer` constructor (ex. an array of bytes or a string). |
|
||||
| [callback] | <code>[errorCallback](#module_serialport--SerialPort..errorCallback)</code> | Called once the write operation returns. |
|
||||
| [encoding] | <code>string</code> | The encoding, if chunk is a String. Defaults to `'utf8'`. Also accepts `'ascii'`, `'base64'`, `'binary'`, `'hex'` See [Buffers and Character Encodings](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings) for all available options. |
|
||||
| [callback] | <code>function</code> | Called once the write operation finishes. Data may not yet be flushed to the underlying port, no arguments. |
|
||||
|
||||
|
||||
-
|
||||
|
||||
<a name="module_serialport--SerialPort+pause"></a>
|
||||
<a name="module_serialport--SerialPort+read"></a>
|
||||
|
||||
#### `serialPort.pause()`
|
||||
Pauses an open connection (unix only)
|
||||
#### `serialPort.read([size])` ⇒ <code>string</code> | <code>Buffer</code> | <code>null</code>
|
||||
Request a number of bytes from the SerialPort. The `read()` method pulls some data out of the internal buffer and returns it. If no data available to be read, null is returned. By default, the data will be returned as a Buffer object unless an encoding has been specified using the `.setEncoding()` method.
|
||||
|
||||
**Kind**: instance method of <code>[SerialPort](#exp_module_serialport--SerialPort)</code>
|
||||
**Returns**: <code>string</code> | <code>Buffer</code> | <code>null</code> - The data from internal buffers
|
||||
|
||||
-
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| [size] | <code>number</code> | size specify how many bytes of data to return if available. |
|
||||
|
||||
<a name="module_serialport--SerialPort+resume"></a>
|
||||
|
||||
#### `serialPort.resume()`
|
||||
Resumes a paused connection (unix only)
|
||||
|
||||
**Kind**: instance method of <code>[SerialPort](#exp_module_serialport--SerialPort)</code>
|
||||
|
||||
-
|
||||
|
||||
|
|
@ -461,7 +482,7 @@ Closes an open connection
|
|||
<a name="module_serialport--SerialPort+set"></a>
|
||||
|
||||
#### `serialPort.set([options], [callback])`
|
||||
Sets flags on an open port. Uses [`SetCommMask`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa363257(v=vs.85).aspx) for windows and [`ioctl`](http://linux.die.net/man/4/tty_ioctl) for mac and linux.
|
||||
Set control flags on an open port. Uses [`SetCommMask`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa363257(v=vs.85).aspx) for windows and [`ioctl`](http://linux.die.net/man/4/tty_ioctl) for mac and linux.
|
||||
|
||||
**Kind**: instance method of <code>[SerialPort](#exp_module_serialport--SerialPort)</code>
|
||||
|
||||
|
|
@ -481,7 +502,7 @@ Sets flags on an open port. Uses [`SetCommMask`](https://msdn.microsoft.com/en-u
|
|||
<a name="module_serialport--SerialPort+get"></a>
|
||||
|
||||
#### `serialPort.get([callback])`
|
||||
Returns the modem status bits (CTS, DSR, DCD) on the open port.
|
||||
Returns the control flags (CTS, DSR, DCD) on the open port.
|
||||
Uses [`GetCommModemStatus`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa363258(v=vs.85).aspx) for windows and [`ioctl`](http://linux.die.net/man/4/tty_ioctl) for mac and linux.
|
||||
|
||||
**Kind**: instance method of <code>[SerialPort](#exp_module_serialport--SerialPort)</code>
|
||||
|
|
@ -521,7 +542,7 @@ Waits until all output data has been transmitted to the serial port. See [`tcdra
|
|||
**Example**
|
||||
Writes `data` and waits until it has finish transmitting to the target serial port before calling the callback.
|
||||
|
||||
```
|
||||
```js
|
||||
function writeAndDrain (data, callback) {
|
||||
sp.write(data, function () {
|
||||
sp.drain(callback);
|
||||
|
|
@ -531,12 +552,25 @@ function writeAndDrain (data, callback) {
|
|||
|
||||
-
|
||||
|
||||
<a name="module_serialport--SerialPort+event_data"></a>
|
||||
<a name="module_serialport--SerialPort+pause"></a>
|
||||
|
||||
#### `Event: "data"`
|
||||
The `data` event's callback is called received data as it's received. If you're using a parser you want to use your parser's `data` event or `read()` function. Data will be a `Buffer` object with a varying amount of data in it. The `readLine` parser will provide a string of a received ASCII or UTF8 line. See the [parsers](#module_serialport--SerialPort.parsers) section for more information.
|
||||
#### `serialPort.pause()` ⇒
|
||||
The `pause()` method will cause a stream in flowing mode to stop emitting 'data' events, switching out of flowing mode. Any data that becomes available will remain in the internal buffer.
|
||||
|
||||
**Kind**: event emitted by <code>[SerialPort](#exp_module_serialport--SerialPort)</code>
|
||||
**Kind**: instance method of <code>[SerialPort](#exp_module_serialport--SerialPort)</code>
|
||||
**Returns**: `this`
|
||||
**See**: module:serialport#resume
|
||||
|
||||
-
|
||||
|
||||
<a name="module_serialport--SerialPort+resume"></a>
|
||||
|
||||
#### `serialPort.resume()` ⇒
|
||||
The `resume()` method causes an explicitly paused Readable stream to resume emitting 'data' events, switching the stream into flowing mode.
|
||||
|
||||
**Kind**: instance method of <code>[SerialPort](#exp_module_serialport--SerialPort)</code>
|
||||
**Returns**: `this`
|
||||
**See**: module:serialport#pause
|
||||
|
||||
-
|
||||
|
||||
|
|
@ -558,6 +592,15 @@ The `open` event's callback is called with no arguments when the port is opened
|
|||
|
||||
-
|
||||
|
||||
<a name="module_serialport--SerialPort+event_data"></a>
|
||||
|
||||
#### `Event: "data"`
|
||||
The `data` event puts the port in flowing mode. data will be emitted as soon as it's received. Data will be a `Buffer` object with a varying amount of data in it. The `readLine` parser converts the data into string lines. See the [parsers](#module_serialport--SerialPort.parsers) section for more information on parsers and the [NodeJS stream documentation](https://nodejs.org/api/stream.html#stream_event_data) for more information on the data event.
|
||||
|
||||
**Kind**: event emitted by <code>[SerialPort](#exp_module_serialport--SerialPort)</code>
|
||||
|
||||
-
|
||||
|
||||
<a name="module_serialport--SerialPort+event_disconnect"></a>
|
||||
|
||||
#### `Event: "disconnect"`
|
||||
|
|
@ -576,6 +619,21 @@ The `close` event's callback is called with no arguments when the port is closed
|
|||
|
||||
-
|
||||
|
||||
<a name="module_serialport--SerialPort.Binding"></a>
|
||||
|
||||
#### `SerialPort.Binding` : <code>[Binding](#module_serialport--SerialPort..Binding)</code>
|
||||
The Binding is how node SerialPort talks to the underlying system. By default we auto detect windows, Linux and OSX and load the appropriate module for your system. You can assign `SerialPort.Binding` to any backend you like. You can find more by searching on [npm](https://npmjs.org/).
|
||||
|
||||
You can also avoid auto loading the default backends by requiring SerialPort with
|
||||
```js
|
||||
var SerialPort = require('serialport/lib/serialport');
|
||||
SerialPort.Binding = MyBindingClass;
|
||||
```
|
||||
|
||||
**Kind**: static property of <code>[SerialPort](#exp_module_serialport--SerialPort)</code>
|
||||
|
||||
-
|
||||
|
||||
<a name="module_serialport--SerialPort.parsers"></a>
|
||||
|
||||
#### `SerialPort.parsers` : <code>object</code>
|
||||
|
|
@ -637,10 +695,10 @@ parser.on('data', console.log);
|
|||
|
||||
<a name="module_serialport--SerialPort.list"></a>
|
||||
|
||||
#### `SerialPort.list` : <code>function</code>
|
||||
#### `SerialPort.list(callback)` : <code>function</code>
|
||||
Retrieves a list of available serial ports with metadata. Only the `comName` is guaranteed, all the other fields will be undefined if they are unavailable. The `comName` is either the path or an identifier (eg `COM1`) used to open the serialport.
|
||||
|
||||
**Kind**: static property of <code>[SerialPort](#exp_module_serialport--SerialPort)</code>
|
||||
**Kind**: static method of <code>[SerialPort](#exp_module_serialport--SerialPort)</code>
|
||||
|
||||
| Param | Type |
|
||||
| --- | --- |
|
||||
|
|
@ -672,6 +730,240 @@ SerialPort.list(function (err, ports) {
|
|||
});
|
||||
```
|
||||
|
||||
-
|
||||
|
||||
<a name="module_serialport--SerialPort..Binding"></a>
|
||||
|
||||
#### SerialPort~Binding : <code>Class</code>
|
||||
**Kind**: inner class of <code>[SerialPort](#exp_module_serialport--SerialPort)</code>
|
||||
**Properties**
|
||||
|
||||
| Name | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| isOpen | <code>boolean</code> | Required property. `true` if the port is open, `false` otherwise. Should be read only. |
|
||||
|
||||
|
||||
* [~Binding](#module_serialport--SerialPort..Binding) : <code>Class</code>
|
||||
* [`new Binding(options)`](#new_module_serialport--SerialPort..Binding_new)
|
||||
* [`.list(callback)`](#module_serialport--SerialPort..Binding+list)
|
||||
* [`.open(path, openOptions, openCallback)`](#module_serialport--SerialPort..Binding+open)
|
||||
* [`.close(callback)`](#module_serialport--SerialPort..Binding+close)
|
||||
* [`.read(data, length, readCallback)`](#module_serialport--SerialPort..Binding+read)
|
||||
* [`.write(data, writeCallback)`](#module_serialport--SerialPort..Binding+write)
|
||||
* [`.set([options], callback)`](#module_serialport--SerialPort..Binding+set)
|
||||
* [`.get([callback])`](#module_serialport--SerialPort..Binding+get)
|
||||
* [`.flush(callback)`](#module_serialport--SerialPort..Binding+flush)
|
||||
* [`.drain(callback)`](#module_serialport--SerialPort..Binding+drain)
|
||||
|
||||
|
||||
-
|
||||
|
||||
<a name="new_module_serialport--SerialPort..Binding_new"></a>
|
||||
|
||||
##### `new Binding(options)`
|
||||
You wont ever have to use Binding objects directly they'll be used by SerialPort to access the underlying hardware. This documentation is geared towards people making bindings for different platforms.
|
||||
|
||||
**Throws**:
|
||||
|
||||
- <code>TypeError</code> When given invalid arguments a TypeError will be thrown.
|
||||
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| options | <code>object</code> | |
|
||||
| options.disconnect | <code>function</code> | function to be called when the bindings have detected a disconnected port. This function should be called during any operation instead of that operations usual callback. The `SerialPort` class will attempt to call `close` after a disconnection and ignore any errors. |
|
||||
|
||||
|
||||
-
|
||||
|
||||
<a name="module_serialport--SerialPort..Binding+list"></a>
|
||||
|
||||
##### `binding.list(callback)`
|
||||
Retrieves a list of available serial ports with metadata. The `comName` must be guaranteed and all the other fields should be undefined if they are unavailable. The `comName` is either the path or an identifier (eg `COM1`) used to open the serialport.
|
||||
|
||||
**Kind**: instance method of <code>[Binding](#module_serialport--SerialPort..Binding)</code>
|
||||
|
||||
| Param | Type |
|
||||
| --- | --- |
|
||||
| callback | <code>[listCallback](#module_serialport--SerialPort..listCallback)</code> |
|
||||
|
||||
|
||||
-
|
||||
|
||||
<a name="module_serialport--SerialPort..Binding+open"></a>
|
||||
|
||||
##### `binding.open(path, openOptions, openCallback)`
|
||||
Opens a connection to the serial port referenced by the path.
|
||||
|
||||
**Kind**: instance method of <code>[Binding](#module_serialport--SerialPort..Binding)</code>
|
||||
**Throws**:
|
||||
|
||||
- <code>TypeError</code> When given invalid arguments a TypeError will be thrown.
|
||||
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| path | <code>string</code> | |
|
||||
| openOptions | <code>[openOptions](#module_serialport--SerialPort..openOptions)</code> | |
|
||||
| openCallback | <code>[errorCallback](#module_serialport--SerialPort..errorCallback)</code> | is called after the data has been passed to the operating system for writing. This will only be called when there isn't a pending write operation. |
|
||||
|
||||
|
||||
-
|
||||
|
||||
<a name="module_serialport--SerialPort..Binding+close"></a>
|
||||
|
||||
##### `binding.close(callback)`
|
||||
Closes an open connection
|
||||
|
||||
**Kind**: instance method of <code>[Binding](#module_serialport--SerialPort..Binding)</code>
|
||||
**Throws**:
|
||||
|
||||
- <code>TypeError</code> When given invalid arguments a TypeError will be thrown.
|
||||
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| callback | <code>[errorCallback](#module_serialport--SerialPort..errorCallback)</code> | Called once a connection is closed. |
|
||||
|
||||
|
||||
-
|
||||
|
||||
<a name="module_serialport--SerialPort..Binding+read"></a>
|
||||
|
||||
##### `binding.read(data, length, readCallback)`
|
||||
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).
|
||||
|
||||
**Kind**: instance method of <code>[Binding](#module_serialport--SerialPort..Binding)</code>
|
||||
**Throws**:
|
||||
|
||||
- <code>TypeError</code> When given invalid arguments a TypeError will be thrown.
|
||||
|
||||
**Params**: <code>integer</code> offset - is the offset in the buffer to start writing at.
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| data | <code>buffer</code> | Accepts a [`Buffer`](http://nodejs.org/api/buffer.html) object. |
|
||||
| length | <code>integer</code> | specifying the maximum number of bytes to read. |
|
||||
| readCallback | <code>[readCallback](#module_serialport--SerialPort..readCallback)</code> | is called after a read operation |
|
||||
|
||||
|
||||
-
|
||||
|
||||
<a name="module_serialport--SerialPort..Binding+write"></a>
|
||||
|
||||
##### `binding.write(data, writeCallback)`
|
||||
Write a number of bytes to the SerialPort
|
||||
|
||||
**Kind**: instance method of <code>[Binding](#module_serialport--SerialPort..Binding)</code>
|
||||
**Throws**:
|
||||
|
||||
- <code>TypeError</code> When given invalid arguments a TypeError will be thrown.
|
||||
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| data | <code>buffer</code> | Accepts a [`Buffer`](http://nodejs.org/api/buffer.html) object. |
|
||||
| writeCallback | <code>[errorCallback](#module_serialport--SerialPort..errorCallback)</code> | is called after the data has been passed to the operating system for writing. This will only be called when there isn't a pending write operation. |
|
||||
|
||||
|
||||
-
|
||||
|
||||
<a name="module_serialport--SerialPort..Binding+set"></a>
|
||||
|
||||
##### `binding.set([options], callback)`
|
||||
Set control flags on an open port.
|
||||
|
||||
**Kind**: instance method of <code>[Binding](#module_serialport--SerialPort..Binding)</code>
|
||||
**Throws**:
|
||||
|
||||
- <code>TypeError</code> When given invalid arguments a TypeError will be thrown.
|
||||
|
||||
|
||||
| Param | Type | Default | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| [options] | <code>object</code> | | All options are operating system default when the port is opened. Every flag is set on each call to the provided or default values. All options will always be provided. |
|
||||
| [options.brk] | <code>Boolean</code> | <code>false</code> | |
|
||||
| [options.cts] | <code>Boolean</code> | <code>false</code> | |
|
||||
| [options.dsr] | <code>Boolean</code> | <code>false</code> | |
|
||||
| [options.dtr] | <code>Boolean</code> | <code>true</code> | |
|
||||
| [options.rts] | <code>Boolean</code> | <code>true</code> | |
|
||||
| callback | <code>[errorCallback](#module_serialport--SerialPort..errorCallback)</code> | | Called once the port's flags have been set. |
|
||||
|
||||
|
||||
-
|
||||
|
||||
<a name="module_serialport--SerialPort..Binding+get"></a>
|
||||
|
||||
##### `binding.get([callback])`
|
||||
Get the control flags (CTS, DSR, DCD) on the open port.
|
||||
|
||||
**Kind**: instance method of <code>[Binding](#module_serialport--SerialPort..Binding)</code>
|
||||
**Throws**:
|
||||
|
||||
- <code>TypeError</code> When given invalid arguments a TypeError will be thrown.
|
||||
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| [callback] | <code>[modemBitsCallback](#module_serialport--SerialPort..modemBitsCallback)</code> | Called once the flags have been retrieved. |
|
||||
|
||||
|
||||
-
|
||||
|
||||
<a name="module_serialport--SerialPort..Binding+flush"></a>
|
||||
|
||||
##### `binding.flush(callback)`
|
||||
Flush (discard) data received but not read and written but not transmitted.
|
||||
|
||||
**Kind**: instance method of <code>[Binding](#module_serialport--SerialPort..Binding)</code>
|
||||
**Throws**:
|
||||
|
||||
- <code>TypeError</code> When given invalid arguments a TypeError will be thrown.
|
||||
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| callback | <code>[errorCallback](#module_serialport--SerialPort..errorCallback)</code> | Called once the flush operation finishes. |
|
||||
|
||||
|
||||
-
|
||||
|
||||
<a name="module_serialport--SerialPort..Binding+drain"></a>
|
||||
|
||||
##### `binding.drain(callback)`
|
||||
Drain waits until all output data has been transmitted to the serial port.
|
||||
|
||||
**Kind**: instance method of <code>[Binding](#module_serialport--SerialPort..Binding)</code>
|
||||
**Throws**:
|
||||
|
||||
- <code>TypeError</code> When given invalid arguments a TypeError will be thrown.
|
||||
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| callback | <code>[errorCallback](#module_serialport--SerialPort..errorCallback)</code> | Called once the drain operation finishes. |
|
||||
|
||||
|
||||
-
|
||||
|
||||
<a name="module_serialport--SerialPort..readCallback"></a>
|
||||
|
||||
#### `SerialPort~readCallback` : <code>function</code>
|
||||
A callback called with an error or null.
|
||||
|
||||
**Kind**: inner typedef of <code>[SerialPort](#exp_module_serialport--SerialPort)</code>
|
||||
**Throws**:
|
||||
|
||||
- <code>TypeError</code> When given invalid arguments a TypeError will be thrown.
|
||||
|
||||
|
||||
| Param | Type | Description |
|
||||
| --- | --- | --- |
|
||||
| error | <code>error</code> | |
|
||||
| bytesRead | <code>integer</code> | the number of bytes that have been written into the buffer |
|
||||
| buffer | <code>buffer</code> | the buffer that data was written into, same object that was passed into `read`. |
|
||||
|
||||
|
||||
-
|
||||
|
||||
<a name="module_serialport--SerialPort..errorCallback"></a>
|
||||
|
|
@ -714,20 +1006,21 @@ A callback called with an error or an object with the modem line values (cts, ds
|
|||
|
||||
| Name | Type | Default | Description |
|
||||
| --- | --- | --- | --- |
|
||||
| Binding | <code>[Binding](#new_module_serialport--SerialPort..Binding_new)</code> | | The hardware access binding, The Binding is how node SerialPort talks to the underlying system. By default we auto detect Windows (`WindowsBinding`), Linux (`LinuxBinding`) and OSX (`DarwinBinding`) and load the appropriate module for your system. |
|
||||
| autoOpen | <code>boolean</code> | <code>true</code> | Automatically opens the port on `nextTick` |
|
||||
| lock | <code>boolean</code> | <code>true</code> | Prevent other processes from opening the port. false is not currently supported on windows. |
|
||||
| baudRate | <code>number</code> | <code>9600</code> | The baud rate of the port to be opened. This should match one of commonly available baud rates, such as 110, 300, 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, 115200. There is no guarantee, that the device connected to the serial port will support the requested baud rate, even if the port itself supports that baud rate. |
|
||||
| dataBits | <code>number</code> | <code>8</code> | Must be one of: 8, 7, 6, or 5. |
|
||||
| stopBits | <code>number</code> | <code>1</code> | Must be one of: 1 or 2. |
|
||||
| highWaterMark | <code>number</code> | <code>16384</code> | The size of the read and write buffers defaults to 16k |
|
||||
| parity | <code>string</code> | <code>"none"</code> | Must be one of: 'none', 'even', 'mark', 'odd', 'space' |
|
||||
| rtscts | <code>boolean</code> | <code>false</code> | flow control setting |
|
||||
| xon | <code>boolean</code> | <code>false</code> | flow control setting |
|
||||
| xoff | <code>boolean</code> | <code>false</code> | flow control setting |
|
||||
| xany | <code>boolean</code> | <code>false</code> | flow control setting |
|
||||
| bufferSize | <code>number</code> | <code>65536</code> | Size of read buffer |
|
||||
| platformOptions | <code>object</code> | | sets platform specific options |
|
||||
| platformOptions.vmin | <code>number</code> | <code>1</code> | see [`man termios`](http://linux.die.net/man/3/termios) |
|
||||
| platformOptions.vtime | <code>number</code> | <code>0</code> | see [`man termios`](http://linux.die.net/man/3/termios) |
|
||||
| bindingOptions | <code>object</code> | | sets binding specific options |
|
||||
| bindingOptions.vmin | <code>number</code> | <code>1</code> | see [`man termios`](http://linux.die.net/man/3/termios) LinuxBinding and DarwinBinding |
|
||||
| bindingOptions.vtime | <code>number</code> | <code>0</code> | see [`man termios`](http://linux.die.net/man/3/termios) LinuxBinding and DarwinBinding |
|
||||
|
||||
|
||||
-
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@
|
|||
{
|
||||
'sources': [
|
||||
'src/serialport_unix.cpp',
|
||||
'src/serialport_poller.cpp',
|
||||
'src/read-poller.cpp',
|
||||
],
|
||||
'xcode_settings': {
|
||||
'OTHER_LDFLAGS': [
|
||||
|
|
@ -41,7 +41,7 @@
|
|||
{
|
||||
'sources': [
|
||||
'src/serialport_unix.cpp',
|
||||
'src/serialport_poller.cpp',
|
||||
'src/read-poller.cpp',
|
||||
],
|
||||
}
|
||||
],
|
||||
|
|
|
|||
129
lib/bindings-auto-detect.js
Normal file
129
lib/bindings-auto-detect.js
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
'use strict';
|
||||
|
||||
/**
|
||||
* @module serialport
|
||||
*/
|
||||
|
||||
/**
|
||||
* @name module:serialport.Binding
|
||||
* @type {module:serialport~Binding}
|
||||
* @description The Binding is how node SerialPort talks to the underlying system. By default we auto detect windows, Linux and OSX and load the appropriate module for your system. You can assign `SerialPort.Binding` to any backend you like. You can find more by searching on [npm](https://npmjs.org/).
|
||||
|
||||
You can also avoid auto loading the default backends by requiring SerialPort with
|
||||
```js
|
||||
var SerialPort = require('serialport/lib/serialport');
|
||||
SerialPort.Binding = MyBindingClass;
|
||||
```
|
||||
*/
|
||||
|
||||
switch (process.platform) {
|
||||
case 'win32':
|
||||
module.exports = require('./bindings-win32');
|
||||
break;
|
||||
case 'darwin':
|
||||
module.exports = require('./bindings-darwin');
|
||||
break;
|
||||
default:
|
||||
module.exports = require('./bindings-linux');
|
||||
}
|
||||
|
||||
/**
|
||||
* You wont ever have to use Binding objects directly they'll be used by SerialPort to access the underlying hardware. This documentation is geared towards people making bindings for different platforms.
|
||||
* @typedef {Class} Binding
|
||||
* @class
|
||||
* @param {object} options
|
||||
* @param {function} options.disconnect - function to be called when the bindings have detected a disconnected port. This function should be called during any operation instead of that operations usual callback. The `SerialPort` class will attempt to call `close` after a disconnection and ignore any errors.
|
||||
* @property {boolean} isOpen Required property. `true` if the port is open, `false` otherwise. Should be read only.
|
||||
* @throws {TypeError} When given invalid arguments a TypeError will be thrown.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Retrieves a list of available serial ports with metadata. The `comName` must be guaranteed and all the other fields should be undefined if they are unavailable. The `comName` is either the path or an identifier (eg `COM1`) used to open the serialport.
|
||||
* @method module:serialport~Binding#list
|
||||
* @param {module:serialport~listCallback} callback
|
||||
*/
|
||||
|
||||
/**
|
||||
* Opens a connection to the serial port referenced by the path.
|
||||
* @method module:serialport~Binding#open
|
||||
* @param {string} path
|
||||
* @param {module:serialport~openOptions} openOptions
|
||||
* @param {module:serialport~errorCallback} openCallback - is called after the data has been passed to the operating system for writing. This will only be called when there isn't a pending write operation.
|
||||
* @throws {TypeError} When given invalid arguments a TypeError will be thrown.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Closes an open connection
|
||||
* @method module:serialport~Binding#close
|
||||
* @param {module:serialport~errorCallback} callback Called once a connection is closed.
|
||||
* @throws {TypeError} When given invalid arguments a TypeError will be thrown.
|
||||
*/
|
||||
|
||||
/**
|
||||
* 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).
|
||||
* @method module:serialport~Binding#read
|
||||
* @param {buffer} data - Accepts a [`Buffer`](http://nodejs.org/api/buffer.html) object.
|
||||
* @params {integer} offset - is the offset in the buffer to start writing at.
|
||||
* @param {integer} length - specifying the maximum number of bytes to read.
|
||||
* @param {module:serialport~readCallback} readCallback - is called after a read operation
|
||||
* @throws {TypeError} When given invalid arguments a TypeError will be thrown.
|
||||
*/
|
||||
|
||||
/**
|
||||
* A callback called with an error or null.
|
||||
* @typedef {function} module:serialport~readCallback
|
||||
* @param {?error} error
|
||||
* @param {integer} bytesRead - the number of bytes that have been written into the buffer
|
||||
* @param {buffer} buffer - the buffer that data was written into, same object that was passed into `read`.
|
||||
* @throws {TypeError} When given invalid arguments a TypeError will be thrown.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Write a number of bytes to the SerialPort
|
||||
* @method module:serialport~Binding#write
|
||||
* @param {buffer} data - Accepts a [`Buffer`](http://nodejs.org/api/buffer.html) object.
|
||||
* @param {module:serialport~errorCallback} writeCallback - is called after the data has been passed to the operating system for writing. This will only be called when there isn't a pending write operation.
|
||||
* @throws {TypeError} When given invalid arguments a TypeError will be thrown.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Set control flags on an open port.
|
||||
* @method module:serialport~Binding#set
|
||||
* @param {object=} options All options are operating system default when the port is opened. Every flag is set on each call to the provided or default values. All options will always be provided.
|
||||
* @param {Boolean} [options.brk=false]
|
||||
* @param {Boolean} [options.cts=false]
|
||||
* @param {Boolean} [options.dsr=false]
|
||||
* @param {Boolean} [options.dtr=true]
|
||||
* @param {Boolean} [options.rts=true]
|
||||
* @param {module:serialport~errorCallback} callback Called once the port's flags have been set.
|
||||
* @throws {TypeError} When given invalid arguments a TypeError will be thrown.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Get the control flags (CTS, DSR, DCD) on the open port.
|
||||
* @method module:serialport~Binding#get
|
||||
* @param {module:serialport~modemBitsCallback=} callback Called once the flags have been retrieved.
|
||||
* @throws {TypeError} When given invalid arguments a TypeError will be thrown.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Flush (discard) data received but not read and written but not transmitted.
|
||||
* @method module:serialport~Binding#flush
|
||||
* @param {module:serialport~errorCallback} callback Called once the flush operation finishes.
|
||||
* @throws {TypeError} When given invalid arguments a TypeError will be thrown.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Drain waits until all output data has been transmitted to the serial port.
|
||||
* @method module:serialport~Binding#drain
|
||||
* @param {module:serialport~errorCallback} callback Called once the drain operation finishes.
|
||||
* @throws {TypeError} When given invalid arguments a TypeError will be thrown.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Changes options on an open port. Currently only the baudRate is required but any option could be passed to the bindings.
|
||||
* @param {object=} options Only `baudRate` is currently supported
|
||||
* @param {number=} [options.baudRate] If provided a baudRate that isn't supported by the bindings it should pass an error to the callback
|
||||
* @param {module:serialport~errorCallback} [callback] Called once the port's baud rate has been changed.
|
||||
* @throws {TypeError} When given invalid arguments a TypeError will be thrown.
|
||||
*/
|
||||
146
lib/bindings-darwin.js
Normal file
146
lib/bindings-darwin.js
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
'use strict';
|
||||
|
||||
var binding = require('bindings')('serialport.node');
|
||||
var assign = require('object.assign').getPolyfill();
|
||||
|
||||
var defaultBindingOptions = {
|
||||
vmin: 1,
|
||||
vtime: 0
|
||||
};
|
||||
|
||||
function asyncError(cb, err) {
|
||||
process.nextTick(function() {
|
||||
cb(err);
|
||||
});
|
||||
}
|
||||
|
||||
function DarwinBinding(opt) {
|
||||
if (typeof opt !== 'object') {
|
||||
throw new TypeError('options is not an object');
|
||||
}
|
||||
if (typeof opt.disconnect !== 'function') {
|
||||
throw new TypeError('options.disconnect is not a function');
|
||||
}
|
||||
this.disconnect = opt.disconnect;
|
||||
this.bindingOptions = opt.bindingOptions || {};
|
||||
this.fd = null;
|
||||
};
|
||||
|
||||
DarwinBinding.list = binding.list;
|
||||
|
||||
DarwinBinding.prototype.read = require('./read-unix');
|
||||
|
||||
DarwinBinding.prototype.open = function(path, options, cb) {
|
||||
if (typeof path !== 'string') {
|
||||
throw new TypeError('path is not a string');
|
||||
}
|
||||
|
||||
if (typeof options !== 'object') {
|
||||
throw new TypeError('options is not an object');
|
||||
}
|
||||
|
||||
if (typeof cb !== 'function') {
|
||||
throw new TypeError('cb is not a function');
|
||||
}
|
||||
|
||||
if (this.isOpen) {
|
||||
return asyncError(cb, new Error('Already open'));
|
||||
}
|
||||
|
||||
options = assign({}, options, defaultBindingOptions, this.bindingOptions);
|
||||
|
||||
binding.open(path, options, function(err, fd) {
|
||||
if (err) {
|
||||
return cb(err);
|
||||
}
|
||||
this.fd = fd;
|
||||
cb(null);
|
||||
}.bind(this));
|
||||
};
|
||||
|
||||
DarwinBinding.prototype.close = function(cb) {
|
||||
if (typeof cb !== 'function') {
|
||||
throw new TypeError('cb is not a function');
|
||||
}
|
||||
|
||||
if (!this.isOpen) {
|
||||
return asyncError(cb, new Error('Port is not open'));
|
||||
}
|
||||
|
||||
if (this.readPoller) {
|
||||
this.readPoller.stop();
|
||||
this.readPoller = null;
|
||||
}
|
||||
|
||||
binding.close(this.fd, function(err) {
|
||||
if (err) {
|
||||
return cb(err);
|
||||
}
|
||||
this.fd = null;
|
||||
cb(null);
|
||||
}.bind(this));
|
||||
};
|
||||
|
||||
DarwinBinding.prototype.set = function(options, cb) {
|
||||
if (typeof options !== 'object') {
|
||||
throw new TypeError('options is not an object');
|
||||
}
|
||||
|
||||
if (typeof cb !== 'function') {
|
||||
throw new TypeError('cb is not a function');
|
||||
}
|
||||
|
||||
if (!this.isOpen) {
|
||||
return asyncError(cb, new Error('Port is not open'));
|
||||
}
|
||||
binding.set(this.fd, options, cb);
|
||||
};
|
||||
|
||||
DarwinBinding.prototype.write = function(buffer, cb) {
|
||||
if (!Buffer.isBuffer(buffer)) {
|
||||
throw new TypeError('buffer is not a Buffer');
|
||||
}
|
||||
|
||||
if (typeof cb !== 'function') {
|
||||
throw new TypeError('cb is not a function');
|
||||
}
|
||||
|
||||
if (!this.isOpen) {
|
||||
return asyncError(cb, new Error('Port is not open'));
|
||||
}
|
||||
|
||||
binding.write(this.fd, buffer, cb);
|
||||
};
|
||||
|
||||
var commonMethods = [
|
||||
'drain',
|
||||
'flush',
|
||||
'update',
|
||||
'get'
|
||||
];
|
||||
|
||||
commonMethods.map(function(methodName) {
|
||||
DarwinBinding.prototype[methodName] = function() {
|
||||
var args = Array.prototype.slice.apply(arguments);
|
||||
var cb = args[args.length - 1];
|
||||
|
||||
if (typeof cb !== 'function') {
|
||||
throw new TypeError('cb is not a function');
|
||||
}
|
||||
|
||||
if (!this.isOpen) {
|
||||
return asyncError(cb, new Error('Port is not open'));
|
||||
}
|
||||
args.unshift(this.fd);
|
||||
binding[methodName].apply(binding, args);
|
||||
};
|
||||
});
|
||||
|
||||
Object.defineProperty(DarwinBinding.prototype, 'isOpen', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this.fd !== null;
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = DarwinBinding;
|
||||
145
lib/bindings-linux.js
Normal file
145
lib/bindings-linux.js
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
'use strict';
|
||||
|
||||
var binding = require('bindings')('serialport.node');
|
||||
var assign = require('object.assign').getPolyfill();
|
||||
|
||||
var defaultBindingOptions = {
|
||||
vmin: 1,
|
||||
vtime: 0
|
||||
};
|
||||
|
||||
function asyncError(cb, err) {
|
||||
process.nextTick(function() {
|
||||
cb(err);
|
||||
});
|
||||
}
|
||||
|
||||
function LinuxBinding(opt) {
|
||||
if (typeof opt !== 'object') {
|
||||
throw new TypeError('options is not an object');
|
||||
}
|
||||
if (typeof opt.disconnect !== 'function') {
|
||||
throw new TypeError('options.disconnect is not a function');
|
||||
}
|
||||
this.disconnect = opt.disconnect;
|
||||
this.bindingOptions = opt.bindingOptions || {};
|
||||
this.fd = null;
|
||||
};
|
||||
|
||||
LinuxBinding.list = require('./list-linux');
|
||||
|
||||
LinuxBinding.prototype.read = require('./read-unix');
|
||||
|
||||
LinuxBinding.prototype.open = function(path, options, cb) {
|
||||
if (typeof path !== 'string') {
|
||||
throw new TypeError('path is not a string');
|
||||
}
|
||||
|
||||
if (typeof options !== 'object') {
|
||||
throw new TypeError('options is not an object');
|
||||
}
|
||||
|
||||
if (typeof cb !== 'function') {
|
||||
throw new TypeError('cb is not a function');
|
||||
}
|
||||
|
||||
if (this.isOpen) {
|
||||
return asyncError(cb, new Error('Already open'));
|
||||
}
|
||||
|
||||
options = assign({}, options, defaultBindingOptions, this.bindingOptions);
|
||||
|
||||
binding.open(path, options, function(err, fd) {
|
||||
if (err) {
|
||||
return cb(err);
|
||||
}
|
||||
this.fd = fd;
|
||||
cb(null);
|
||||
}.bind(this));
|
||||
};
|
||||
|
||||
LinuxBinding.prototype.close = function(cb) {
|
||||
if (typeof cb !== 'function') {
|
||||
throw new TypeError('cb is not a function');
|
||||
}
|
||||
|
||||
if (!this.isOpen) {
|
||||
return asyncError(cb, new Error('Port is not open'));
|
||||
}
|
||||
|
||||
if (this.readPoller) {
|
||||
this.readPoller.stop();
|
||||
this.readPoller = null;
|
||||
}
|
||||
|
||||
binding.close(this.fd, function(err) {
|
||||
if (err) {
|
||||
return cb(err);
|
||||
}
|
||||
this.fd = null;
|
||||
cb(null);
|
||||
}.bind(this));
|
||||
};
|
||||
|
||||
LinuxBinding.prototype.set = function(options, cb) {
|
||||
if (typeof options !== 'object') {
|
||||
throw new TypeError('options is not an object');
|
||||
}
|
||||
|
||||
if (typeof cb !== 'function') {
|
||||
throw new TypeError('cb is not a function');
|
||||
}
|
||||
|
||||
if (!this.isOpen) {
|
||||
return asyncError(cb, new Error('Port is not open'));
|
||||
}
|
||||
binding.set(this.fd, options, cb);
|
||||
};
|
||||
|
||||
LinuxBinding.prototype.write = function(buffer, cb) {
|
||||
if (!Buffer.isBuffer(buffer)) {
|
||||
throw new TypeError('buffer is not a Buffer');
|
||||
}
|
||||
|
||||
if (typeof cb !== 'function') {
|
||||
throw new TypeError('cb is not a function');
|
||||
}
|
||||
|
||||
if (!this.isOpen) {
|
||||
return asyncError(cb, new Error('Port is not open'));
|
||||
}
|
||||
binding.write(this.fd, buffer, cb);
|
||||
};
|
||||
|
||||
var commonMethods = [
|
||||
'drain',
|
||||
'flush',
|
||||
'update',
|
||||
'get'
|
||||
];
|
||||
|
||||
commonMethods.map(function(methodName) {
|
||||
LinuxBinding.prototype[methodName] = function() {
|
||||
var args = Array.prototype.slice.apply(arguments);
|
||||
var cb = args[args.length - 1];
|
||||
|
||||
if (typeof cb !== 'function') {
|
||||
throw new TypeError('cb is not a function');
|
||||
}
|
||||
|
||||
if (!this.isOpen) {
|
||||
return asyncError(cb, new Error('Port is not open'));
|
||||
}
|
||||
args.unshift(this.fd);
|
||||
binding[methodName].apply(binding, args);
|
||||
};
|
||||
});
|
||||
|
||||
Object.defineProperty(LinuxBinding.prototype, 'isOpen', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this.fd !== null;
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = LinuxBinding;
|
||||
228
lib/bindings-mock.js
Normal file
228
lib/bindings-mock.js
Normal file
|
|
@ -0,0 +1,228 @@
|
|||
'use strict';
|
||||
|
||||
var inherits = require('util').inherits;
|
||||
var processNextTick = function() {
|
||||
var args = Array.prototype.slice.apply(arguments);
|
||||
var cb = args.shift();
|
||||
process.nextTick(function() { cb.apply(null, args) });
|
||||
};
|
||||
|
||||
function MissingPortError(name) {
|
||||
name = name || 'unknown method:';
|
||||
this.message = name + ' Port does not exist - please call hardware.createPort(path) first';
|
||||
this.name = 'MissingPortError';
|
||||
Error.captureStackTrace(this, MissingPortError);
|
||||
}
|
||||
inherits(MissingPortError, Error);
|
||||
|
||||
function ClosedPortError(name) {
|
||||
name = name || 'unknown method:';
|
||||
this.message = name + ' Port is closed';
|
||||
this.name = 'ClosedPortError';
|
||||
Error.captureStackTrace(this, MissingPortError);
|
||||
}
|
||||
inherits(ClosedPortError, Error);
|
||||
|
||||
var ports = {};
|
||||
|
||||
function MockBindings(opt) {
|
||||
if (typeof opt.disconnect !== 'function') {
|
||||
throw new TypeError('options.disconnect is not a function');
|
||||
}
|
||||
this.onDisconnect = opt.disconnect;
|
||||
this.pendingReadCB = null;
|
||||
this.isOpen = false;
|
||||
};
|
||||
|
||||
MockBindings.reset = function() {
|
||||
ports = {};
|
||||
};
|
||||
|
||||
// control function
|
||||
MockBindings.createPort = function(path, opt) {
|
||||
opt = opt || {};
|
||||
var echo = opt.echo;
|
||||
var readyData = opt.readyData || new Buffer('READY');
|
||||
ports[path] = {
|
||||
data: new Buffer(0),
|
||||
lastWrite: null,
|
||||
echo: echo,
|
||||
readyData: readyData,
|
||||
info: {
|
||||
comName: path,
|
||||
manufacturer: 'The J5 Robotics Company',
|
||||
serialNumber: undefined,
|
||||
pnpId: undefined,
|
||||
locationId: undefined,
|
||||
vendorId: undefined,
|
||||
productId: undefined
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
MockBindings.list = function(cb) {
|
||||
var info = Object.keys(ports).map(function(path) {
|
||||
return ports[path].info;
|
||||
});
|
||||
processNextTick(cb, null, info);
|
||||
};
|
||||
|
||||
// control function
|
||||
MockBindings.prototype.emitData = function(data) {
|
||||
if (!this.isOpen) {
|
||||
return;
|
||||
}
|
||||
this.port.data = Buffer.concat([this.port.data, data]);
|
||||
|
||||
if (this.port.pendingReadCB) {
|
||||
var buffer = this.port.pendingReadCB[0];
|
||||
var offset = this.port.pendingReadCB[1];
|
||||
var length = this.port.pendingReadCB[2];
|
||||
var cb = this.port.pendingReadCB[3];
|
||||
this.port.pendingReadCB = null;
|
||||
processNextTick(this.read.bind(this), buffer, offset, length, cb);
|
||||
}
|
||||
};
|
||||
|
||||
MockBindings.prototype.disconnect = function(err) {
|
||||
err = err || new Error('disconnected');
|
||||
this.onDisconnect(err);
|
||||
};
|
||||
|
||||
MockBindings.prototype.open = function(path, opt, cb) {
|
||||
var port = this.port = ports[path];
|
||||
if (!port) {
|
||||
return cb(new MissingPortError(path));
|
||||
}
|
||||
|
||||
if (port.openOpt && port.openOpt.lock) {
|
||||
return cb(new Error('port is locked cannot open'));
|
||||
}
|
||||
|
||||
if (this.isOpen) {
|
||||
return processNextTick(cb, new Error('open: binding is already open'));
|
||||
}
|
||||
|
||||
port.openOpt = opt;
|
||||
processNextTick(function() {
|
||||
this.isOpen = true;
|
||||
processNextTick(function() {
|
||||
if (port.echo) {
|
||||
this.emitData(port.readyData);
|
||||
}
|
||||
cb(null);
|
||||
}.bind(this));
|
||||
}.bind(this));
|
||||
};
|
||||
|
||||
MockBindings.prototype.close = function(cb) {
|
||||
var port = this.port;
|
||||
if (!port) {
|
||||
return processNextTick(cb, new Error('port is already closed'));
|
||||
}
|
||||
processNextTick(function() {
|
||||
delete port.openOpt;
|
||||
|
||||
// reset data on close
|
||||
port.data = new Buffer(0);
|
||||
|
||||
delete this.port;
|
||||
this.isOpen = false;
|
||||
processNextTick(cb, null);
|
||||
}.bind(this));
|
||||
};
|
||||
|
||||
MockBindings.prototype.update = function(opt, cb) {
|
||||
if (typeof opt !== 'object') {
|
||||
throw new TypeError('options is not an object');
|
||||
}
|
||||
|
||||
if (!opt.baudRate) {
|
||||
throw new Error('Missing baudRate');
|
||||
}
|
||||
|
||||
if (!this.isOpen) {
|
||||
return processNextTick(cb, new ClosedPortError('update'));
|
||||
}
|
||||
this.port.openOpt.baudRate = opt.baudRate;
|
||||
processNextTick(cb, null);
|
||||
};
|
||||
|
||||
MockBindings.prototype.set = function(opt, cb) {
|
||||
if (typeof opt !== 'object') {
|
||||
throw new TypeError('options is not an object');
|
||||
}
|
||||
|
||||
if (!this.isOpen) {
|
||||
return processNextTick(cb, new ClosedPortError('set'));
|
||||
}
|
||||
processNextTick(cb, null);
|
||||
};
|
||||
|
||||
MockBindings.prototype.write = function(buffer, cb) {
|
||||
if (!Buffer.isBuffer(buffer)) {
|
||||
throw new TypeError('buffer is not a Buffer');
|
||||
}
|
||||
|
||||
if (typeof cb !== 'function') {
|
||||
throw new TypeError('callback is not a function');
|
||||
}
|
||||
|
||||
if (!this.isOpen) {
|
||||
return processNextTick(cb, new ClosedPortError('write'));
|
||||
}
|
||||
|
||||
var data = this.port.lastWrite = new Buffer(buffer); // copy
|
||||
processNextTick(cb, null);
|
||||
|
||||
if (this.port.echo) {
|
||||
processNextTick(this.emitData.bind(this), data);
|
||||
}
|
||||
};
|
||||
|
||||
MockBindings.prototype.read = function(buffer, offset, length, cb) {
|
||||
if (typeof cb !== 'function') {
|
||||
throw new TypeError("cb in read isn't a function");
|
||||
}
|
||||
|
||||
if (!this.isOpen) {
|
||||
return processNextTick(cb, new ClosedPortError('read'));
|
||||
}
|
||||
|
||||
if (this.port.data.length <= 0) {
|
||||
this.port.pendingReadCB = [buffer, offset, length, cb];
|
||||
return;
|
||||
}
|
||||
var data = this.port.data.slice(0, length);
|
||||
var readLength = data.copy(buffer, offset);
|
||||
this.port.data = this.port.data.slice(length);
|
||||
|
||||
processNextTick(cb, null, readLength, buffer);
|
||||
};
|
||||
|
||||
MockBindings.prototype.get = function(cb) {
|
||||
if (!this.isOpen) {
|
||||
return processNextTick(cb, new ClosedPortError('flush'));
|
||||
}
|
||||
processNextTick(cb, null, {
|
||||
cts: true,
|
||||
dsr: false,
|
||||
dcd: false
|
||||
});
|
||||
};
|
||||
|
||||
MockBindings.prototype.flush = function(cb) {
|
||||
if (!this.isOpen) {
|
||||
return processNextTick(cb, new ClosedPortError('flush'));
|
||||
}
|
||||
processNextTick(cb, null);
|
||||
};
|
||||
|
||||
MockBindings.prototype.drain = function(cb) {
|
||||
if (!this.isOpen) {
|
||||
return processNextTick(cb, new ClosedPortError('drain'));
|
||||
}
|
||||
processNextTick(cb, null);
|
||||
};
|
||||
|
||||
module.exports = MockBindings;
|
||||
137
lib/bindings-win32.js
Normal file
137
lib/bindings-win32.js
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
'use strict';
|
||||
|
||||
var binding = require('bindings')('serialport.node');
|
||||
|
||||
function asyncError(cb, err) {
|
||||
process.nextTick(function() {
|
||||
cb(err);
|
||||
});
|
||||
}
|
||||
|
||||
function WindowsBinding(opt) {
|
||||
if (typeof opt !== 'object') {
|
||||
throw new TypeError('options is not an object');
|
||||
}
|
||||
if (typeof opt.disconnect !== 'function') {
|
||||
throw new TypeError('options.disconnect is not a function');
|
||||
}
|
||||
this.disconnect = opt.disconnect;
|
||||
this.fd = null;
|
||||
};
|
||||
|
||||
WindowsBinding.prototype.read = require('./read-unix');
|
||||
|
||||
WindowsBinding.prototype.open = function(path, options, cb) {
|
||||
if (typeof path !== 'string') {
|
||||
throw new TypeError('path is not a string');
|
||||
}
|
||||
|
||||
if (typeof options !== 'object') {
|
||||
throw new TypeError('options is not an object');
|
||||
}
|
||||
|
||||
if (typeof cb !== 'function') {
|
||||
throw new TypeError('cb is not a function');
|
||||
}
|
||||
|
||||
if (this.isOpen) {
|
||||
return asyncError(cb, new Error('Already open'));
|
||||
}
|
||||
|
||||
binding.open(path, options, function(err, fd) {
|
||||
if (err) {
|
||||
return cb(err);
|
||||
}
|
||||
this.fd = fd;
|
||||
cb(null);
|
||||
}.bind(this));
|
||||
};
|
||||
|
||||
WindowsBinding.prototype.close = function(cb) {
|
||||
if (typeof cb !== 'function') {
|
||||
throw new TypeError('cb is not a function');
|
||||
}
|
||||
|
||||
if (!this.isOpen) {
|
||||
return asyncError(cb, new Error('Port is not open'));
|
||||
}
|
||||
|
||||
if (this.readPoller) {
|
||||
this.readPoller.stop();
|
||||
this.readPoller = null;
|
||||
}
|
||||
|
||||
binding.close(this.fd, function(err) {
|
||||
if (err) {
|
||||
return cb(err);
|
||||
}
|
||||
this.fd = null;
|
||||
cb(null);
|
||||
}.bind(this));
|
||||
};
|
||||
|
||||
WindowsBinding.prototype.set = function(options, cb) {
|
||||
if (typeof options !== 'object') {
|
||||
throw new TypeError('options is not an object');
|
||||
}
|
||||
|
||||
if (typeof cb !== 'function') {
|
||||
throw new TypeError('cb is not a function');
|
||||
}
|
||||
|
||||
if (!this.isOpen) {
|
||||
return asyncError(cb, new Error('Port is not open'));
|
||||
}
|
||||
|
||||
binding.set(this.fd, options, cb);
|
||||
};
|
||||
|
||||
WindowsBinding.prototype.write = function(buffer, cb) {
|
||||
if (!Buffer.isBuffer(buffer)) {
|
||||
throw new TypeError('buffer is not a Buffer');
|
||||
}
|
||||
|
||||
if (typeof cb !== 'function') {
|
||||
throw new TypeError('cb is not a function');
|
||||
}
|
||||
|
||||
if (!this.isOpen) {
|
||||
return asyncError(cb, new Error('Port is not open'));
|
||||
}
|
||||
|
||||
binding.write(this.fd, buffer, cb);
|
||||
};
|
||||
|
||||
var commonMethods = [
|
||||
'drain',
|
||||
'flush',
|
||||
'update',
|
||||
'get'
|
||||
];
|
||||
|
||||
commonMethods.map(function(methodName) {
|
||||
WindowsBinding.prototype[methodName] = function() {
|
||||
var args = Array.prototype.slice.apply(arguments);
|
||||
var cb = args[args.length - 1];
|
||||
|
||||
if (typeof cb !== 'function') {
|
||||
throw new TypeError('cb is not a function');
|
||||
}
|
||||
|
||||
if (!this.isOpen) {
|
||||
return asyncError(cb, new Error('Port is not open'));
|
||||
}
|
||||
args.unshift(this.fd);
|
||||
binding[methodName].apply(binding, args);
|
||||
};
|
||||
});
|
||||
|
||||
Object.defineProperty(WindowsBinding.prototype, 'isOpen', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this.fd !== null;
|
||||
}
|
||||
});
|
||||
|
||||
WindowsBinding.list = binding.list;
|
||||
module.exports = WindowsBinding;
|
||||
|
|
@ -1,28 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
var bindings = require('bindings')('serialport.node');
|
||||
var listLinux = require('./list-linux');
|
||||
|
||||
var linux = process.platform !== 'win32' && process.platform !== 'darwin';
|
||||
|
||||
var platformOptions = {};
|
||||
if (process.platform !== 'win32') {
|
||||
platformOptions = {
|
||||
vmin: 1,
|
||||
vtime: 0
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
close: bindings.close,
|
||||
drain: bindings.drain,
|
||||
flush: bindings.flush,
|
||||
list: linux ? listLinux : bindings.list,
|
||||
open: bindings.open,
|
||||
SerialportPoller: bindings.SerialportPoller,
|
||||
set: bindings.set,
|
||||
get: bindings.get,
|
||||
update: bindings.update,
|
||||
write: bindings.write,
|
||||
platformOptions: platformOptions
|
||||
};
|
||||
15
lib/index.js
Normal file
15
lib/index.js
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
'use strict';
|
||||
|
||||
/**
|
||||
* @module serialport
|
||||
* @copyright Chris Williams <chris@iterativedesigns.com>
|
||||
*/
|
||||
|
||||
var SerialPort = require('./serialport');
|
||||
var Binding = require('./bindings-auto-detect');
|
||||
var parsers = require('./parsers');
|
||||
|
||||
SerialPort.Binding = Binding;
|
||||
SerialPort.parsers = parsers;
|
||||
|
||||
module.exports = SerialPort;
|
||||
62
lib/push-methods.js
Normal file
62
lib/push-methods.js
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
'use strict';
|
||||
|
||||
function allocNewPool(poolSize) {
|
||||
var pool;
|
||||
// performs better on node 6+
|
||||
if (Buffer.allocUnsafe) {
|
||||
pool = Buffer.allocUnsafe(poolSize);
|
||||
} else {
|
||||
pool = new Buffer(poolSize);
|
||||
}
|
||||
pool.used = 0;
|
||||
return pool;
|
||||
}
|
||||
|
||||
function _read(bytesToRead) {
|
||||
if (!this._pool || this._pool.length - this._pool.used < this._kMinPoolSpace) {
|
||||
// discard the old this._pool.
|
||||
this._pool = allocNewPool(this._readBufferSize);
|
||||
}
|
||||
|
||||
// Grab another reference to the pool in the case that while we're
|
||||
// in the thread pool another read() finishes up the pool, and
|
||||
// allocates a new one.
|
||||
var pool = this._pool;
|
||||
// Read the smaller of rest of the pool or however many bytes we want
|
||||
var toRead = Math.min(pool.length - pool.used, bytesToRead);
|
||||
var start = pool.used;
|
||||
|
||||
// the actual read.
|
||||
var self = this;
|
||||
this.read(pool, start, toRead, function onRead(err, bytesRead) {
|
||||
if (err) {
|
||||
return this.disconnect(err);
|
||||
}
|
||||
pool.used += bytesRead;
|
||||
self.push(pool.slice(start, start + bytesRead));
|
||||
});
|
||||
};
|
||||
|
||||
function pushBindingWrap(opt) {
|
||||
if (typeof opt.binding !== 'object') {
|
||||
throw new TypeError('binding is not an object');
|
||||
}
|
||||
if (typeof opt.push !== 'function') {
|
||||
throw new TypeError('push is not a function');
|
||||
}
|
||||
|
||||
var binding = opt.binding;
|
||||
if (typeof binding._read !== 'function') {
|
||||
binding._read = _read;
|
||||
binding._readBufferSize = opt.readBufferSize || 1024;
|
||||
binding._kMinPoolSpace = opt.kMinPoolSpace || 128;
|
||||
binding._pool = null;
|
||||
}
|
||||
if (typeof binding.push !== 'function') {
|
||||
binding.push = opt.push;
|
||||
}
|
||||
return binding;
|
||||
};
|
||||
|
||||
|
||||
module.exports = pushBindingWrap;
|
||||
43
lib/read-unix.js
Normal file
43
lib/read-unix.js
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
'use strict';
|
||||
var fs = require('fs');
|
||||
var ReadPoller = require('bindings')('serialport.node').ReadPoller;
|
||||
|
||||
module.exports = function readUnix(buffer, offset, length, cb) {
|
||||
if (typeof cb !== 'function') {
|
||||
throw new TypeError("cb in read isn't a function");
|
||||
}
|
||||
|
||||
if (!this.isOpen) {
|
||||
process.nextTick(function() {
|
||||
cb(new Error('Port is not open'));
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.readPoller) {
|
||||
this.readPoller.stop();
|
||||
this.readPoller = null;
|
||||
}
|
||||
|
||||
fs.read(this.fd, buffer, offset, length, null, function(err, bytesRead) {
|
||||
if (err && err.code === 'EAGAIN') {
|
||||
this.readPoller = new ReadPoller(this.fd, function() {
|
||||
this.readPoller = null;
|
||||
this.read(buffer, offset, length, cb);
|
||||
}.bind(this));
|
||||
return;
|
||||
}
|
||||
|
||||
var disconnectError = err && (
|
||||
err.code === 'EBADF' || // Bad file number means we got closed
|
||||
err.code === 'ENXIO' || // No such device or address probably usb disconnect
|
||||
err.code === 'UNKNOWN' || // ¯\_(ツ)_/¯ does this ever happen?
|
||||
err.errno === -1 // generic error
|
||||
);
|
||||
|
||||
if (disconnectError) {
|
||||
return this.disconnect(err);
|
||||
}
|
||||
cb(err, bytesRead, buffer);
|
||||
}.bind(this));
|
||||
};
|
||||
|
|
@ -6,19 +6,15 @@
|
|||
*/
|
||||
|
||||
// 3rd Party Dependencies
|
||||
var stream = require('readable-stream');
|
||||
var debug = require('debug')('serialport');
|
||||
|
||||
// Internal Dependencies
|
||||
var mixInPushMethods = require('./push-methods');
|
||||
|
||||
// shims
|
||||
var assign = require('object.assign').getPolyfill();
|
||||
|
||||
// Internal Dependencies
|
||||
var SerialPortBinding = require('./bindings');
|
||||
var parsers = require('./parsers');
|
||||
|
||||
// Built-ins Dependencies
|
||||
var fs = require('fs');
|
||||
var stream = require('stream');
|
||||
var util = require('util');
|
||||
var inherits = require('util').inherits;
|
||||
|
||||
// VALIDATION ARRAYS
|
||||
var DATABITS = [5, 6, 7, 8];
|
||||
|
|
@ -27,24 +23,19 @@ var PARITY = ['none', 'even', 'mark', 'odd', 'space'];
|
|||
var FLOWCONTROLS = ['xon', 'xoff', 'xany', 'rtscts'];
|
||||
var SET_OPTIONS = ['brk', 'cts', 'dtr', 'dts', 'rts'];
|
||||
|
||||
// Stuff from ReadStream, refactored for our usage:
|
||||
var kPoolSize = 40 * 1024;
|
||||
var kMinPoolSpace = 128;
|
||||
|
||||
var defaultSettings = {
|
||||
baudRate: 9600,
|
||||
autoOpen: true,
|
||||
parity: 'none',
|
||||
xon: false,
|
||||
xoff: false,
|
||||
xany: false,
|
||||
rtscts: false,
|
||||
hupcl: true,
|
||||
baudRate: 9600,
|
||||
dataBits: 8,
|
||||
stopBits: 1,
|
||||
bufferSize: 64 * 1024,
|
||||
hupcl: true,
|
||||
lock: true,
|
||||
platformOptions: SerialPortBinding.platformOptions
|
||||
parity: 'none',
|
||||
rtscts: false,
|
||||
stopBits: 1,
|
||||
xany: false,
|
||||
xoff: false,
|
||||
xon: false,
|
||||
highWaterMark: 16 * 1024,
|
||||
};
|
||||
|
||||
var defaultSetFlags = {
|
||||
|
|
@ -73,32 +64,34 @@ var defaultSetFlags = {
|
|||
|
||||
/**
|
||||
* @typedef {Object} openOptions
|
||||
* @property {boolean} [autoOpen=true] - Automatically opens the port on `nextTick`
|
||||
* @property {module:serialport~Binding=} Binding The hardware access binding, The Binding is how node SerialPort talks to the underlying system. By default we auto detect Windows (`WindowsBinding`), Linux (`LinuxBinding`) and OSX (`DarwinBinding`) and load the appropriate module for your system.
|
||||
* @property {boolean} [autoOpen=true] Automatically opens the port on `nextTick`
|
||||
* @property {boolean} [lock=true] Prevent other processes from opening the port. false is not currently supported on windows.
|
||||
* @property {number} [baudRate=9600] The baud rate of the port to be opened. This should match one of commonly available baud rates, such as 110, 300, 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, 115200. There is no guarantee, that the device connected to the serial port will support the requested baud rate, even if the port itself supports that baud rate.
|
||||
* @property {number} [dataBits=8] Must be one of: 8, 7, 6, or 5.
|
||||
* @property {number} [stopBits=1] Must be one of: 1 or 2.
|
||||
* @property {number} [highWaterMark=16384] The size of the read and write buffers defaults to 16k
|
||||
* @property {string} [parity=none] Must be one of: 'none', 'even', 'mark', 'odd', 'space'
|
||||
* @property {boolean} [rtscts=false] flow control setting
|
||||
* @property {boolean} [xon=false] flow control setting
|
||||
* @property {boolean} [xoff=false] flow control setting
|
||||
* @property {boolean} [xany=false] flow control setting
|
||||
* @property {number} [bufferSize=65536] Size of read buffer
|
||||
* @property {object=} platformOptions sets platform specific options
|
||||
* @property {number} [platformOptions.vmin=1] see [`man termios`](http://linux.die.net/man/3/termios)
|
||||
* @property {number} [platformOptions.vtime=0] see [`man termios`](http://linux.die.net/man/3/termios)
|
||||
* @property {object=} bindingOptions sets binding specific options
|
||||
* @property {number} [bindingOptions.vmin=1] see [`man termios`](http://linux.die.net/man/3/termios) LinuxBinding and DarwinBinding
|
||||
* @property {number} [bindingOptions.vtime=0] see [`man termios`](http://linux.die.net/man/3/termios) LinuxBinding and DarwinBinding
|
||||
*/
|
||||
|
||||
/**
|
||||
* Creates a SerialPort Object.
|
||||
* Create a new serial port object for the `path`. In the case of invalid arguments or invalid options when constructing a new SerialPort it will throw an error. The port will open automatically by default which is the equivalent of calling `port.open(openCallback)` in the next tick. This can be disabled by setting the option `autoOpen` to false.
|
||||
* @class
|
||||
* @description Create a new serial port object for the `path`. In the case of invalid arguments or invalid options when constructing a new SerialPort it will throw an error. The port will open automatically by default which is the equivalent of calling `port.open(openCallback)` in the next tick. This can be disabled by setting the option `autoOpen` to false.
|
||||
* @param {string} path - The system path of the serial port to open. For example, `/dev/tty.XXX` on Mac/Linux or `COM1` on Windows.
|
||||
* @param {module:serialport~openOptions=} options - Port configuration options
|
||||
* @param {module:serialport~errorCallback=} openCallback - Called when a connection has been opened. If this is not provided and an error occurs, it will be emitted on the ports `error` event. The callback will NOT be called if autoOpen is set to false in the openOptions as the open will not be performed.
|
||||
* @throws {TypeError} When given invalid arguments a TypeError will be thrown.
|
||||
* @property {number} baudRate The port's baudRate, use `.update` to change it. Read Only.
|
||||
* @property {object} binding The binding object backing the port Read Only.
|
||||
* @property {boolean} isOpen `true` if the port is open, `false` otherwise. Read Only.
|
||||
* @property {string} path The system path or name of the serial port. Read Only.
|
||||
* @property {boolean} isOpen true if the port is open, false otherwise. Read Only.
|
||||
* @throws {TypeError} When given invalid arguments a TypeError will be thrown.
|
||||
* @emits module:serialport#open
|
||||
* @emits module:serialport#data
|
||||
* @emits module:serialport#close
|
||||
|
|
@ -111,12 +104,6 @@ function SerialPort(path, options, callback) {
|
|||
return new SerialPort(path, options, callback);
|
||||
}
|
||||
|
||||
stream.Stream.call(this);
|
||||
|
||||
if (typeof callback === 'boolean' || typeof options === 'boolean') {
|
||||
throw new TypeError('`openImmediately` is now called `autoOpen` and is a property of options');
|
||||
}
|
||||
|
||||
if (typeof options === 'function') {
|
||||
callback = options;
|
||||
options = {};
|
||||
|
|
@ -124,20 +111,17 @@ function SerialPort(path, options, callback) {
|
|||
|
||||
var settings = assign({}, defaultSettings, options);
|
||||
|
||||
Object.defineProperty(this, 'path', {
|
||||
enumerable: true,
|
||||
writable: false,
|
||||
value: path
|
||||
stream.Duplex.call(this, {
|
||||
highWaterMark: settings.highWaterMark
|
||||
});
|
||||
|
||||
Object.defineProperty(this, 'isOpen', {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this.fd !== null && !this.closing;
|
||||
}
|
||||
});
|
||||
var Binding = settings.binding || SerialPort.Binding;
|
||||
|
||||
if (!this.path) {
|
||||
if (!Binding) {
|
||||
throw new TypeError('No binding set, pass it as `options.binding` or set it on `SerialPort.Binding`');
|
||||
}
|
||||
|
||||
if (!path) {
|
||||
throw new TypeError('No path specified');
|
||||
}
|
||||
|
||||
|
|
@ -163,35 +147,59 @@ function SerialPort(path, options, callback) {
|
|||
}
|
||||
});
|
||||
|
||||
settings.disconnectedCallback = this._disconnected.bind(this);
|
||||
var push = this.push.bind(this);
|
||||
var binding = new Binding({
|
||||
disconnect: this._disconnected.bind(this),
|
||||
push: push,
|
||||
readBufferSize: settings.highWaterMark,
|
||||
bindingOptions: settings.bindingOptions
|
||||
});
|
||||
|
||||
binding = mixInPushMethods({
|
||||
binding: binding,
|
||||
push: push,
|
||||
readBufferSize: settings.highWaterMark
|
||||
});
|
||||
|
||||
Object.defineProperties(this, {
|
||||
'binding': {
|
||||
enumerable: true,
|
||||
writable: false,
|
||||
value: binding
|
||||
},
|
||||
'path': {
|
||||
enumerable: true,
|
||||
writable: false,
|
||||
value: path
|
||||
}
|
||||
});
|
||||
|
||||
this.fd = null;
|
||||
this.paused = true;
|
||||
this.opening = false;
|
||||
this.closing = false;
|
||||
this.settings = settings;
|
||||
|
||||
if (process.platform !== 'win32') {
|
||||
this.bufferSize = settings.bufferSize;
|
||||
this.readable = true;
|
||||
this.reading = false;
|
||||
} else {
|
||||
settings.dataCallback = this._emitData.bind(this);
|
||||
}
|
||||
|
||||
this.options = settings;
|
||||
|
||||
if (this.options.autoOpen) {
|
||||
// is nextTick necessary?
|
||||
if (this.settings.autoOpen) {
|
||||
// not necessary
|
||||
process.nextTick(this.open.bind(this, callback));
|
||||
}
|
||||
}
|
||||
|
||||
util.inherits(SerialPort, stream.Stream);
|
||||
inherits(SerialPort, stream.Duplex);
|
||||
|
||||
/**
|
||||
* The `data` event's callback is called received data as it's received. If you're using a parser you want to use your parser's `data` event or `read()` function. Data will be a `Buffer` object with a varying amount of data in it. The `readLine` parser will provide a string of a received ASCII or UTF8 line. See the [parsers](#module_serialport--SerialPort.parsers) section for more information.
|
||||
* @event module:serialport#data
|
||||
*/
|
||||
Object.defineProperties(SerialPort.prototype, {
|
||||
'isOpen': {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this.binding.isOpen && !this.closing;
|
||||
}
|
||||
},
|
||||
'baudRate': {
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return this.settings.baudRate;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* The `error` event's callback is called with an error object whenever there is an error.
|
||||
|
|
@ -225,31 +233,13 @@ SerialPort.prototype.open = function(callback) {
|
|||
return this._error(new Error('Port is opening'), callback);
|
||||
}
|
||||
|
||||
this.paused = true;
|
||||
this.readable = true;
|
||||
this.reading = false;
|
||||
this.opening = true;
|
||||
|
||||
SerialPortBinding.open(this.path, this.options, function(err, fd) {
|
||||
this.binding.open(this.path, this.settings, function(err) {
|
||||
this.opening = false;
|
||||
if (err) {
|
||||
debug('SerialPortBinding.open had an error', err);
|
||||
debug('Binding #open had an error', err);
|
||||
return this._error(err, callback);
|
||||
}
|
||||
this.fd = fd;
|
||||
this.paused = false;
|
||||
|
||||
if (process.platform !== 'win32') {
|
||||
this.serialPoller = new SerialPortBinding.SerialportPoller(this.fd, function(err) {
|
||||
if (!err) {
|
||||
this._read();
|
||||
} else {
|
||||
this._disconnected(err);
|
||||
}
|
||||
}.bind(this));
|
||||
this.serialPoller.start();
|
||||
}
|
||||
|
||||
this.emit('open');
|
||||
if (callback) { callback.call(this, null) }
|
||||
}.bind(this));
|
||||
|
|
@ -268,9 +258,9 @@ SerialPort.prototype.update = function(options, callback) {
|
|||
}
|
||||
|
||||
var settings = assign({}, defaultSettings, options);
|
||||
this.options.baudRate = settings.baudRate;
|
||||
this.settings.baudRate = settings.baudRate;
|
||||
|
||||
SerialPortBinding.update(this.fd, this.options, function(err) {
|
||||
this.binding.update(this.settings, function(err) {
|
||||
if (err) {
|
||||
return this._error(err, callback);
|
||||
}
|
||||
|
|
@ -279,141 +269,74 @@ SerialPort.prototype.update = function(options, callback) {
|
|||
};
|
||||
|
||||
/**
|
||||
* Writes data to the given serial port.
|
||||
* Writes data to the given serial port. Buffers written data if the port is not open.
|
||||
|
||||
The write operation is non-blocking. When it returns, data may still have not actually been written to the serial port. See `drain()`.
|
||||
|
||||
Some devices like the Arduino reset when you open a connection to them. In these cases if you immediately write to the device they wont be ready to receive the data. This is often worked around by having the Arduino send a "ready" byte that your node program waits for before writing. You can also often get away with waiting around 400ms.
|
||||
|
||||
Even though serialport is a stream, when writing it can accept arrays of bytes in addition to strings and buffers. This extra functionality is pretty sweet.
|
||||
* @method module:serialport#write
|
||||
* @param {(string|array|buffer)} data Accepts a [`Buffer` ](http://nodejs.org/api/buffer.html) object, or a type that is accepted by the `Buffer` constructor (ex. an array of bytes or a string).
|
||||
* @param {module:serialport~errorCallback=} callback Called once the write operation returns.
|
||||
* @description The write operation is non-blocking. When it returns, data may still have not actually been written to the serial port. See `drain()`.
|
||||
* @description Some devices like the Arduino reset when you open a connection to them. In these cases if you immediately write to the device they wont be ready to receive the data. This is often worked around by having the Arduino send a "ready" byte that your node program waits for before writing. You can also often get away with waiting around 400ms.
|
||||
* @param {string=} encoding The encoding, if chunk is a String. Defaults to `'utf8'`. Also accepts `'ascii'`, `'base64'`, `'binary'`, `'hex'` See [Buffers and Character Encodings](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings) for all available options.
|
||||
* @param {function=} callback Called once the write operation finishes. Data may not yet be flushed to the underlying port, no arguments.
|
||||
* @returns {boolean} `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`.
|
||||
*/
|
||||
SerialPort.prototype.write = function(data, callback) {
|
||||
var superWrite = SerialPort.prototype.write;
|
||||
SerialPort.prototype.write = function(data, encoding, callback) {
|
||||
if (Array.isArray(data)) {
|
||||
data = new Buffer(data);
|
||||
}
|
||||
return superWrite.call(this, data, encoding, callback);
|
||||
};
|
||||
|
||||
SerialPort.prototype._write = function(data, encoding, callback) {
|
||||
if (!this.isOpen) {
|
||||
debug('write attempted, but port is not open');
|
||||
return this._error(new Error('Port is not open'), callback);
|
||||
return this.once('open', function() {
|
||||
this._write(data, encoding, callback);
|
||||
});
|
||||
}
|
||||
|
||||
if (!Buffer.isBuffer(data)) {
|
||||
data = new Buffer(data);
|
||||
data = new Buffer(data, encoding);
|
||||
}
|
||||
|
||||
debug('write ' + data.length + ' bytes of data');
|
||||
SerialPortBinding.write(this.fd, data, function(err) {
|
||||
if (err) {
|
||||
debug('SerialPortBinding.write had an error', err);
|
||||
return this._error(err, callback);
|
||||
}
|
||||
if (callback) { callback.call(this, null) }
|
||||
}.bind(this));
|
||||
debug('_write ' + data.length + ' bytes of data');
|
||||
this.binding.write(data, callback);
|
||||
};
|
||||
|
||||
SerialPort.prototype._emitData = function(data) {
|
||||
this.emit('data', data);
|
||||
SerialPort.prototype._writev = function(data, callback) {
|
||||
data = data.map(function(queuedWrite) {
|
||||
if (Buffer.isBuffer(queuedWrite.chunk)) {
|
||||
return queuedWrite.chunk;
|
||||
}
|
||||
return new Buffer(queuedWrite.chunk, queuedWrite.encoding);
|
||||
});
|
||||
data = Buffer.concat(data);
|
||||
this._write(data, null, callback);
|
||||
};
|
||||
|
||||
/**
|
||||
* Request a number of bytes from the SerialPort. The `read()` method pulls some data out of the internal buffer and returns it. If no data available to be read, null is returned. By default, the data will be returned as a Buffer object unless an encoding has been specified using the `.setEncoding()` method.
|
||||
* @method module:serialport#read
|
||||
* @param {number=} size size specify how many bytes of data to return if available.
|
||||
* @returns {(string|Buffer|null)} The data from internal buffers
|
||||
*/
|
||||
|
||||
if (process.platform !== 'win32') {
|
||||
SerialPort.prototype._read = function() {
|
||||
if (!this.readable || this.paused || this.reading || this.closing) {
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* The `data` event puts the port in flowing mode. data will be emitted as soon as it's received. Data will be a `Buffer` object with a varying amount of data in it. The `readLine` parser converts the data into string lines. See the [parsers](#module_serialport--SerialPort.parsers) section for more information on parsers and the [NodeJS stream documentation](https://nodejs.org/api/stream.html#stream_event_data) for more information on the data event.
|
||||
* @event module:serialport#data
|
||||
*/
|
||||
|
||||
this.reading = true;
|
||||
|
||||
if (!this.pool || this.pool.length - this.pool.used < kMinPoolSpace) {
|
||||
// discard the old pool. Can't add to the free list because
|
||||
// users might have references to slices on it.
|
||||
this.pool = new Buffer(kPoolSize);
|
||||
this.pool.used = 0;
|
||||
}
|
||||
|
||||
// Grab another reference to the pool in the case that while we're in the
|
||||
// thread pool another read() finishes up the pool, and allocates a new
|
||||
// one.
|
||||
var toRead = Math.min(this.pool.length - this.pool.used, ~~this.bufferSize);
|
||||
var start = this.pool.used;
|
||||
|
||||
var _afterRead = function(err, bytesRead, readPool, bytesRequested) {
|
||||
this.reading = false;
|
||||
if (err) {
|
||||
if (err.code && err.code === 'EAGAIN') {
|
||||
if (this.isOpen) {
|
||||
this.serialPoller.start();
|
||||
}
|
||||
// handle edge case were mac/unix doesn't clearly know the error.
|
||||
} else if (err.code && (err.code === 'EBADF' || err.code === 'ENXIO' || (err.errno === -1 || err.code === 'UNKNOWN'))) {
|
||||
this._disconnected(err);
|
||||
} else {
|
||||
this.fd = null;
|
||||
this.readable = false;
|
||||
this.emit('error', err);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Since we will often not read the number of bytes requested,
|
||||
// let's mark the ones we didn't need as available again.
|
||||
this.pool.used -= bytesRequested - bytesRead;
|
||||
|
||||
if (bytesRead === 0) {
|
||||
if (this.isOpen) {
|
||||
this.serialPoller.start();
|
||||
}
|
||||
} else {
|
||||
var b = this.pool.slice(start, start + bytesRead);
|
||||
|
||||
// do not emit events if the stream is paused
|
||||
if (this.paused) {
|
||||
if (!this.buffer) {
|
||||
this.buffer = new Buffer(0);
|
||||
}
|
||||
this.buffer = Buffer.concat([this.buffer, b]);
|
||||
return;
|
||||
}
|
||||
this._emitData(b);
|
||||
|
||||
// do not emit events anymore after we declared the stream unreadable
|
||||
if (!this.readable) {
|
||||
return;
|
||||
}
|
||||
this._read();
|
||||
}
|
||||
}.bind(this);
|
||||
|
||||
fs.read(this.fd, this.pool, this.pool.used, toRead, null, function(err, bytesRead) {
|
||||
var readPool = this.pool;
|
||||
var bytesRequested = toRead;
|
||||
_afterRead(err, bytesRead, readPool, bytesRequested);
|
||||
}.bind(this));
|
||||
|
||||
this.pool.used += toRead;
|
||||
};
|
||||
|
||||
/**
|
||||
* Pauses an open connection (unix only)
|
||||
*/
|
||||
SerialPort.prototype.pause = function() {
|
||||
this.paused = true;
|
||||
};
|
||||
|
||||
/**
|
||||
* Resumes a paused connection (unix only)
|
||||
*/
|
||||
SerialPort.prototype.resume = function() {
|
||||
this.paused = false;
|
||||
|
||||
if (this.buffer) {
|
||||
var buffer = this.buffer;
|
||||
this.buffer = null;
|
||||
this._emitData(buffer);
|
||||
}
|
||||
|
||||
// No longer open?
|
||||
if (!this.isOpen) {
|
||||
return;
|
||||
}
|
||||
|
||||
this._read();
|
||||
};
|
||||
} // if !'win32'
|
||||
SerialPort.prototype._read = function(bytes) {
|
||||
if(!this.isOpen) {
|
||||
this.once('open', function() {
|
||||
this.binding._read(bytes);
|
||||
});
|
||||
return;
|
||||
}
|
||||
this.binding._read(bytes);
|
||||
};
|
||||
|
||||
/**
|
||||
* The `disconnect` event's callback is called with an error object. This will always happen before a `close` event if a disconnection is detected.
|
||||
|
|
@ -421,30 +344,12 @@ if (process.platform !== 'win32') {
|
|||
*/
|
||||
|
||||
SerialPort.prototype._disconnected = function(err) {
|
||||
this.paused = true;
|
||||
debug('disconnected with', err);
|
||||
if (!this.isOpen) {
|
||||
return;
|
||||
}
|
||||
this.emit('disconnect', err);
|
||||
if (this.closing) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.fd === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.closing = true;
|
||||
if (process.platform !== 'win32') {
|
||||
this.readable = false;
|
||||
this.serialPoller.close();
|
||||
}
|
||||
|
||||
SerialPortBinding.close(this.fd, function(err) {
|
||||
this.closing = false;
|
||||
if (err) {
|
||||
debug('Disconnect close completed with error: ', err);
|
||||
}
|
||||
this.fd = null;
|
||||
this.emit('close');
|
||||
}.bind(this));
|
||||
this.close();
|
||||
};
|
||||
|
||||
/**
|
||||
|
|
@ -458,40 +363,26 @@ SerialPort.prototype._disconnected = function(err) {
|
|||
* @emits module:serialport#close
|
||||
*/
|
||||
SerialPort.prototype.close = function(callback) {
|
||||
this.paused = true;
|
||||
|
||||
if (this.closing) {
|
||||
debug('close attempted, but port is already closing');
|
||||
return this._error(new Error('Port is not open'), callback);
|
||||
}
|
||||
|
||||
if (!this.isOpen) {
|
||||
debug('close attempted, but port is not open');
|
||||
return this._error(new Error('Port is not open'), callback);
|
||||
}
|
||||
|
||||
this.closing = true;
|
||||
|
||||
// Stop polling before closing the port.
|
||||
if (process.platform !== 'win32') {
|
||||
this.readable = false;
|
||||
this.serialPoller.close();
|
||||
}
|
||||
SerialPortBinding.close(this.fd, function(err) {
|
||||
this.binding.close(function(err) {
|
||||
this.closing = false;
|
||||
if (err) {
|
||||
debug('SerialPortBinding.close had an error', err);
|
||||
debug('Binding #close had an error', err);
|
||||
return this._error(err, callback);
|
||||
}
|
||||
|
||||
this.fd = null;
|
||||
// TODO should we be calling this.push(null) here?
|
||||
this.emit('close');
|
||||
if (callback) { callback.call(this, null) }
|
||||
}.bind(this));
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets flags on an open port. Uses [`SetCommMask`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa363257(v=vs.85).aspx) for windows and [`ioctl`](http://linux.die.net/man/4/tty_ioctl) for mac and linux.
|
||||
* Set control flags on an open port. Uses [`SetCommMask`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa363257(v=vs.85).aspx) for windows and [`ioctl`](http://linux.die.net/man/4/tty_ioctl) for mac and linux.
|
||||
* @param {object=} options All options are operating system default when the port is opened. Every flag is set on each call to the provided or default values. If options isn't provided default options will be used.
|
||||
* @param {Boolean} [options.brk=false]
|
||||
* @param {Boolean} [options.cts=false]
|
||||
|
|
@ -522,9 +413,9 @@ SerialPort.prototype.set = function(options, callback) {
|
|||
}
|
||||
}
|
||||
|
||||
SerialPortBinding.set(this.fd, settings, function(err) {
|
||||
this.binding.set(settings, function(err) {
|
||||
if (err) {
|
||||
debug('SerialPortBinding.set had an error', err);
|
||||
debug('Binding #set had an error', err);
|
||||
return this._error(err, callback);
|
||||
}
|
||||
if (callback) { callback.call(this, null) }
|
||||
|
|
@ -532,7 +423,7 @@ SerialPort.prototype.set = function(options, callback) {
|
|||
};
|
||||
|
||||
/**
|
||||
* Returns the modem status bits (CTS, DSR, DCD) on the open port.
|
||||
* Returns the control flags (CTS, DSR, DCD) on the open port.
|
||||
* Uses [`GetCommModemStatus`](https://msdn.microsoft.com/en-us/library/windows/desktop/aa363258(v=vs.85).aspx) for windows and [`ioctl`](http://linux.die.net/man/4/tty_ioctl) for mac and linux.
|
||||
* @param {module:serialport~modemBitsCallback=} callback Called once the modem bits have been retrieved.
|
||||
*/
|
||||
|
|
@ -542,9 +433,9 @@ SerialPort.prototype.get = function(callback) {
|
|||
return this._error(new Error('Port is not open'), callback);
|
||||
}
|
||||
|
||||
SerialPortBinding.get(this.fd, function(err, status) {
|
||||
this.binding.get(function(err, status) {
|
||||
if (err) {
|
||||
debug('SerialPortBinding.get had an error', err);
|
||||
debug('Binding #get had an error', err);
|
||||
return this._error(err, callback);
|
||||
}
|
||||
if (callback) { callback.call(this, null, status) }
|
||||
|
|
@ -561,9 +452,9 @@ SerialPort.prototype.flush = function(callback) {
|
|||
return this._error(new Error('Port is not open'), callback);
|
||||
}
|
||||
|
||||
SerialPortBinding.flush(this.fd, function(err) {
|
||||
this.binding.flush(function(err) {
|
||||
if (err) {
|
||||
debug('SerialPortBinding.flush had an error', err);
|
||||
debug('Binding #flush had an error', err);
|
||||
return this._error(err, callback);
|
||||
}
|
||||
if (callback) { callback.call(this, null) }
|
||||
|
|
@ -576,7 +467,7 @@ SerialPort.prototype.flush = function(callback) {
|
|||
* @example
|
||||
Writes `data` and waits until it has finish transmitting to the target serial port before calling the callback.
|
||||
|
||||
```
|
||||
```js
|
||||
function writeAndDrain (data, callback) {
|
||||
sp.write(data, function () {
|
||||
sp.drain(callback);
|
||||
|
|
@ -590,18 +481,31 @@ SerialPort.prototype.drain = function(callback) {
|
|||
return this._error(new Error('Port is not open'), callback);
|
||||
}
|
||||
|
||||
SerialPortBinding.drain(this.fd, function(err) {
|
||||
this.binding.drain(function(err) {
|
||||
if (err) {
|
||||
debug('SerialPortBinding.drain had an error', err);
|
||||
debug('Binding #drain had an error', err);
|
||||
return this._error(err, callback);
|
||||
}
|
||||
if (callback) { callback.call(this, null) }
|
||||
}.bind(this));
|
||||
};
|
||||
|
||||
/**
|
||||
* The `pause()` method will cause a stream in flowing mode to stop emitting 'data' events, switching out of flowing mode. Any data that becomes available will remain in the internal buffer.
|
||||
* @method module:serialport#pause
|
||||
* @see module:serialport#resume
|
||||
* @returns `this`
|
||||
*/
|
||||
|
||||
/**
|
||||
* The `resume()` method causes an explicitly paused Readable stream to resume emitting 'data' events, switching the stream into flowing mode.
|
||||
* @method module:serialport#resume
|
||||
* @see module:serialport#pause
|
||||
* @returns `this`
|
||||
*/
|
||||
|
||||
/**
|
||||
* This callback type is called `requestCallback` and is displayed as a global symbol.
|
||||
*
|
||||
* @callback listCallback
|
||||
* @param {?error} error
|
||||
* @param {array} ports an array of objects with port info.
|
||||
|
|
@ -637,25 +541,11 @@ SerialPort.list(function (err, ports) {
|
|||
});
|
||||
```
|
||||
*/
|
||||
SerialPort.list = SerialPortBinding.list;
|
||||
|
||||
// Write a depreciation warning once
|
||||
Object.defineProperty(SerialPort, 'SerialPort', {
|
||||
get: function() {
|
||||
console.warn('DEPRECATION: Please use `require(\'serialport\')` instead of `require(\'serialport\').SerialPort`');
|
||||
Object.defineProperty(SerialPort, 'SerialPort', {
|
||||
value: SerialPort
|
||||
});
|
||||
return SerialPort;
|
||||
},
|
||||
configurable: true
|
||||
});
|
||||
SerialPort.parsers = {
|
||||
Readline: require('./parser-readline'),
|
||||
Delimiter: require('./parser-delimiter'),
|
||||
ByteLength: require('./parser-byte-length')
|
||||
SerialPort.list = function() {
|
||||
if (!SerialPort.Binding) {
|
||||
throw new TypeError('No Binding set on `SerialPort.Binding`');
|
||||
}
|
||||
return SerialPort.Binding.list.apply(SerialPort.Binding, arguments);
|
||||
};
|
||||
|
||||
SerialPort.parsers = parsers;
|
||||
|
||||
module.exports = SerialPort;
|
||||
|
|
|
|||
14
package.json
14
package.json
|
|
@ -12,7 +12,7 @@
|
|||
"module_path": "build/{configuration}/",
|
||||
"host": "https://github.com/EmergingTechnologyAdvisors/node-serialport/releases/download/5.0.0-beta2"
|
||||
},
|
||||
"main": "./lib/serialport",
|
||||
"main": "./lib",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git://github.com/EmergingTechnologyAdvisors/node-serialport.git"
|
||||
|
|
@ -73,7 +73,7 @@
|
|||
"jsdoc-to-markdown": "^2.0.1",
|
||||
"mocha": "^3.1.1",
|
||||
"node-pre-gyp-github": "^1.1.2",
|
||||
"sandboxed-module": "^2.0.3",
|
||||
"proxyquire": "^1.7.10",
|
||||
"sinon": "^1.17.3"
|
||||
},
|
||||
"bundledDependencies": [
|
||||
|
|
@ -88,15 +88,15 @@
|
|||
},
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"arduino-test":"TEST_PORT=$(./bin/find-arduino.js) npm test",
|
||||
"docs": "jsdoc2md --no-cache -t .docs/README.hbs --partial .docs/sig-name.hbs --partial .docs/sig-link.hbs --partial .docs/edit-warning.hbs -r table --separators --name-format lib/* > README.md",
|
||||
"docs:diff": "jsdoc2md --no-cache -t .docs/README.hbs --partial .docs/sig-name.hbs --partial .docs/sig-link.hbs --partial .docs/edit-warning.hbs -r table --separators --name-format lib/* | diff README.md - || (echo 'Docs out of date, run `npm run docs` and commit the new README.md' && false)",
|
||||
"docs:diff": "jsdoc2md --no-cache -t .docs/README.hbs --partial .docs/sig-name.hbs --partial .docs/sig-link.hbs --partial .docs/edit-warning.hbs -r table --separators --name-format lib/* | diff -q README.md - || (echo 'Docs out of date, run `npm run docs` and commit the new README.md' && false)",
|
||||
"install": "node-pre-gyp install --fallback-to-build",
|
||||
"lint": "eslint *.js lib/**/*.js test/**/*.js bin/**/*.js examples/**/*.js",
|
||||
"rebuild-all": "npm rebuild && node-gyp rebuild",
|
||||
"stress": "mocha --no-timeouts test/arduinoTest/stress.js",
|
||||
"lint": "eslint *.js lib/**/*.js test/**/*.js bin/**/*.js examples/**/*.js",
|
||||
"test": "istanbul cover ./node_modules/mocha/bin/_mocha test/*.js test/arduinoTest/integration.js test/integration-lite.js",
|
||||
"arduino-test":"TEST_PORT=$(./bin/find-arduino.js) npm test",
|
||||
"valgrind": "valgrind --leak-check=full --show-possibly-lost=no node --expose-gc --trace-gc node_modules/.bin/grunt test"
|
||||
"test": "istanbul cover ./node_modules/mocha/bin/_mocha",
|
||||
"valgrind": "valgrind --leak-check=full --show-possibly-lost=no npm test"
|
||||
},
|
||||
"gypfile": true
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,28 +1,44 @@
|
|||
// Copyright (C) 2013 Robert Giseburt <giseburt@gmail.com>
|
||||
// serialport_poller.cpp Written as a part of https://github.com/voodootikigod/node-serialport
|
||||
// poller.cpp Written as a part of https://github.com/voodootikigod/node-serialport
|
||||
// License to use this is the same as that of node-serialport.
|
||||
|
||||
#include <nan.h>
|
||||
#include "./serialport_poller.h"
|
||||
#include "./read-poller.h"
|
||||
|
||||
using namespace v8;
|
||||
|
||||
static Nan::Persistent<v8::FunctionTemplate> serialportpoller_constructor;
|
||||
static Nan::Persistent<v8::FunctionTemplate> poller_constructor;
|
||||
|
||||
SerialportPoller::SerialportPoller() : Nan::ObjectWrap() {}
|
||||
SerialportPoller::~SerialportPoller() {
|
||||
// printf("~SerialportPoller\n");
|
||||
delete callback_;
|
||||
void ReadPoller::Init(Handle<Object> target) {
|
||||
Nan::HandleScope scope;
|
||||
|
||||
// Prepare constructor template
|
||||
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
|
||||
tpl->SetClassName(Nan::New<String>("ReadPoller").ToLocalChecked());
|
||||
tpl->InstanceTemplate()->SetInternalFieldCount(1);
|
||||
|
||||
// Prototype
|
||||
// ReadPoller.close()
|
||||
Nan::SetPrototypeMethod(tpl, "close", Close);
|
||||
poller_constructor.Reset(tpl);
|
||||
|
||||
Nan::Set(target, Nan::New<String>("ReadPoller").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked());
|
||||
}
|
||||
|
||||
ReadPoller::ReadPoller() : Nan::ObjectWrap() {}
|
||||
ReadPoller::~ReadPoller() {
|
||||
// printf("~ReadPoller\n");
|
||||
// _close();
|
||||
}
|
||||
|
||||
void _serialportReadable(uv_poll_t *req, int status, int events) {
|
||||
SerialportPoller* sp = (SerialportPoller*) req->data;
|
||||
ReadPoller* sp = (ReadPoller*) req->data;
|
||||
// We can stop polling until we have read all of the data...
|
||||
sp->_stop();
|
||||
sp->callCallback(status);
|
||||
sp->_close();
|
||||
}
|
||||
|
||||
void SerialportPoller::callCallback(int status) {
|
||||
void ReadPoller::callCallback(int status) {
|
||||
Nan::HandleScope scope;
|
||||
// uv_work_t* req = new uv_work_t;
|
||||
|
||||
|
|
@ -47,78 +63,38 @@ void SerialportPoller::callCallback(int status) {
|
|||
callback_->Call(1, argv);
|
||||
}
|
||||
|
||||
|
||||
|
||||
void SerialportPoller::Init(Handle<Object> target) {
|
||||
Nan::HandleScope scope;
|
||||
|
||||
// Prepare constructor template
|
||||
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(New);
|
||||
tpl->SetClassName(Nan::New<String>("SerialportPoller").ToLocalChecked());
|
||||
tpl->InstanceTemplate()->SetInternalFieldCount(1);
|
||||
|
||||
|
||||
// Prototype
|
||||
|
||||
// SerialportPoller.close()
|
||||
Nan::SetPrototypeMethod(tpl, "close", Close);
|
||||
|
||||
// SerialportPoller.start()
|
||||
Nan::SetPrototypeMethod(tpl, "start", Start);
|
||||
|
||||
serialportpoller_constructor.Reset(tpl);
|
||||
|
||||
Nan::Set(target, Nan::New<String>("SerialportPoller").ToLocalChecked(), Nan::GetFunction(tpl).ToLocalChecked());
|
||||
}
|
||||
|
||||
NAN_METHOD(SerialportPoller::New) {
|
||||
NAN_METHOD(ReadPoller::New) {
|
||||
// printf("ReadPoller\n");
|
||||
if (!info[0]->IsInt32()) {
|
||||
Nan::ThrowTypeError("First argument must be an fd");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!info[1]->IsFunction()) {
|
||||
Nan::ThrowTypeError("Third argument must be a function");
|
||||
Nan::ThrowTypeError("Second argument must be a function");
|
||||
return;
|
||||
}
|
||||
|
||||
SerialportPoller* obj = new SerialportPoller();
|
||||
ReadPoller* obj = new ReadPoller();
|
||||
obj->fd_ = info[0]->ToInt32()->Int32Value();
|
||||
obj->callback_ = new Nan::Callback(info[1].As<v8::Function>());
|
||||
// obj->callCallback();
|
||||
|
||||
obj->Wrap(info.This());
|
||||
|
||||
obj->poll_handle_.data = obj;
|
||||
|
||||
uv_poll_init(uv_default_loop(), &obj->poll_handle_, obj->fd_);
|
||||
|
||||
uv_poll_start(&obj->poll_handle_, UV_READABLE, _serialportReadable);
|
||||
|
||||
info.GetReturnValue().Set(info.This());
|
||||
}
|
||||
|
||||
void SerialportPoller::_start() {
|
||||
uv_poll_start(&poll_handle_, UV_READABLE, _serialportReadable);
|
||||
}
|
||||
|
||||
void SerialportPoller::_stop() {
|
||||
void ReadPoller::_close() {
|
||||
// printf("ReadPoller::_close\n");
|
||||
uv_poll_stop(&poll_handle_);
|
||||
delete callback_;
|
||||
}
|
||||
|
||||
|
||||
NAN_METHOD(SerialportPoller::Start) {
|
||||
SerialportPoller* obj = Nan::ObjectWrap::Unwrap<SerialportPoller>(info.This());
|
||||
obj->_start();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
NAN_METHOD(SerialportPoller::Close) {
|
||||
SerialportPoller* obj = Nan::ObjectWrap::Unwrap<SerialportPoller>(info.This());
|
||||
obj->_stop();
|
||||
|
||||
// DO SOMETHING!
|
||||
|
||||
NAN_METHOD(ReadPoller::Close) {
|
||||
ReadPoller* obj = Nan::ObjectWrap::Unwrap<ReadPoller>(info.This());
|
||||
obj->_close();
|
||||
return;
|
||||
}
|
||||
|
|
@ -2,28 +2,27 @@
|
|||
// serialport_poller.h Written as a part of https://github.com/voodootikigod/node-serialport
|
||||
// License to use this is the same as that of node-serialport.
|
||||
|
||||
#ifndef SERIALPORT_POLLER_H
|
||||
#define SERIALPORT_POLLER_H
|
||||
#ifndef SRC_READ_POLLER_H_
|
||||
#define SRC_READ_POLLER_H_
|
||||
|
||||
#include <nan.h>
|
||||
#include "./serialport.h"
|
||||
|
||||
class SerialportPoller : public Nan::ObjectWrap {
|
||||
class ReadPoller : public Nan::ObjectWrap {
|
||||
public:
|
||||
static void Init(v8::Handle<v8::Object> target);
|
||||
|
||||
void callCallback(int status);
|
||||
|
||||
void _start();
|
||||
void _stop();
|
||||
void _close();
|
||||
|
||||
private:
|
||||
SerialportPoller();
|
||||
~SerialportPoller();
|
||||
ReadPoller();
|
||||
~ReadPoller();
|
||||
|
||||
static NAN_METHOD(New);
|
||||
static NAN_METHOD(Close);
|
||||
static NAN_METHOD(Start);
|
||||
|
||||
uv_poll_t poll_handle_;
|
||||
int fd_;
|
||||
|
|
@ -32,4 +31,4 @@ class SerialportPoller : public Nan::ObjectWrap {
|
|||
Nan::Callback* callback_;
|
||||
};
|
||||
|
||||
#endif
|
||||
#endif // SRC_READ_POLLER_H_
|
||||
|
|
@ -1,9 +1,9 @@
|
|||
#include "./serialport.h"
|
||||
|
||||
#ifdef WIN32
|
||||
#define strncasecmp strnicmp
|
||||
#define strncasecmp strnicmp
|
||||
#else
|
||||
#include "./serialport_poller.h"
|
||||
#include "./read-poller.h"
|
||||
#endif
|
||||
|
||||
struct _WriteQueue {
|
||||
|
|
@ -128,7 +128,6 @@ NAN_METHOD(Open) {
|
|||
strcpy(baton->path, *path);
|
||||
baton->baudRate = getIntFromObject(options, "baudRate");
|
||||
baton->dataBits = getIntFromObject(options, "dataBits");
|
||||
baton->bufferSize = getIntFromObject(options, "bufferSize");
|
||||
baton->parity = ToParityEnum(getStringFromObj(options, "parity"));
|
||||
baton->stopBits = ToStopBitEnum(getDoubleFromObject(options, "stopBits"));
|
||||
baton->rtscts = getBoolFromObject(options, "rtscts");
|
||||
|
|
@ -137,21 +136,17 @@ NAN_METHOD(Open) {
|
|||
baton->xany = getBoolFromObject(options, "xany");
|
||||
baton->hupcl = getBoolFromObject(options, "hupcl");
|
||||
baton->lock = getBoolFromObject(options, "lock");
|
||||
|
||||
v8::Local<v8::Object> platformOptions = getValueFromObject(options, "platformOptions")->ToObject();
|
||||
baton->platformOptions = ParsePlatformOptions(platformOptions);
|
||||
|
||||
baton->callback.Reset(info[2].As<v8::Function>());
|
||||
baton->dataCallback = new Nan::Callback(getValueFromObject(options, "dataCallback").As<v8::Function>());
|
||||
baton->disconnectedCallback = new Nan::Callback(getValueFromObject(options, "disconnectedCallback").As<v8::Function>());
|
||||
baton->errorCallback = new Nan::Callback(getValueFromObject(options, "errorCallback").As<v8::Function>());
|
||||
|
||||
#ifndef WIN32
|
||||
baton->vmin = getIntFromObject(options, "vmin");
|
||||
baton->vtime = getIntFromObject(options, "vtime");
|
||||
#endif
|
||||
|
||||
uv_work_t* req = new uv_work_t();
|
||||
req->data = baton;
|
||||
|
||||
uv_queue_work(uv_default_loop(), req, EIO_Open, (uv_after_work_cb)EIO_AfterOpen);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
void EIO_AfterOpen(uv_work_t* req) {
|
||||
|
|
@ -163,23 +158,15 @@ void EIO_AfterOpen(uv_work_t* req) {
|
|||
if (data->errorString[0]) {
|
||||
argv[0] = v8::Exception::Error(Nan::New<v8::String>(data->errorString).ToLocalChecked());
|
||||
argv[1] = Nan::Undefined();
|
||||
// not needed because we're not calling AfterOpenSuccess
|
||||
delete data->dataCallback;
|
||||
delete data->errorCallback;
|
||||
delete data->disconnectedCallback;
|
||||
} else {
|
||||
argv[0] = Nan::Null();
|
||||
argv[1] = Nan::New<v8::Int32>(data->result);
|
||||
|
||||
int fd = argv[1]->ToInt32()->Int32Value();
|
||||
newQForFD(fd);
|
||||
|
||||
AfterOpenSuccess(data->result, data->dataCallback, data->disconnectedCallback, data->errorCallback);
|
||||
}
|
||||
|
||||
data->callback.Call(2, argv);
|
||||
|
||||
delete data->platformOptions;
|
||||
delete data;
|
||||
delete req;
|
||||
}
|
||||
|
|
@ -221,8 +208,6 @@ NAN_METHOD(Update) {
|
|||
req->data = baton;
|
||||
|
||||
uv_queue_work(uv_default_loop(), req, EIO_Update, (uv_after_work_cb)EIO_AfterUpdate);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
void EIO_AfterUpdate(uv_work_t* req) {
|
||||
|
|
@ -266,23 +251,26 @@ NAN_METHOD(Write) {
|
|||
return;
|
||||
}
|
||||
|
||||
WriteBaton* baton = new WriteBaton();
|
||||
memset(baton, 0, sizeof(WriteBaton));
|
||||
baton->fd = fd;
|
||||
baton->buffer.Reset(buffer);
|
||||
baton->bufferData = bufferData;
|
||||
baton->bufferLength = bufferLength;
|
||||
baton->offset = 0;
|
||||
baton->callback.Reset(info[2].As<v8::Function>());
|
||||
WriteBaton* data = new WriteBaton();
|
||||
memset(data, 0, sizeof(WriteBaton));
|
||||
data->fd = fd;
|
||||
data->buffer.Reset(buffer);
|
||||
data->bufferData = bufferData;
|
||||
data->bufferLength = bufferLength;
|
||||
data->offset = 0;
|
||||
data->callback.Reset(info[2].As<v8::Function>());
|
||||
|
||||
QueuedWrite* queuedWrite = new QueuedWrite();
|
||||
memset(queuedWrite, 0, sizeof(QueuedWrite));
|
||||
queuedWrite->baton = baton;
|
||||
queuedWrite->baton = data;
|
||||
queuedWrite->req.data = queuedWrite;
|
||||
|
||||
_WriteQueue *q = qForFD(fd);
|
||||
if (!q) {
|
||||
Nan::ThrowTypeError("There's no write queue for that file descriptor (write)!");
|
||||
v8::Local<v8::Value> argv[1];
|
||||
argv[0] = v8::Exception::Error(Nan::New<v8::String>("There's no write queue for file descriptor").ToLocalChecked());
|
||||
data->callback.Call(1, argv);
|
||||
delete data;
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -296,8 +284,6 @@ NAN_METHOD(Write) {
|
|||
uv_queue_work(uv_default_loop(), &queuedWrite->req, EIO_Write, (uv_after_work_cb)EIO_AfterWrite);
|
||||
}
|
||||
q->unlock();
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
void EIO_AfterWrite(uv_work_t* req) {
|
||||
|
|
@ -317,7 +303,6 @@ void EIO_AfterWrite(uv_work_t* req) {
|
|||
// We're not done with this baton, so throw it right back onto the queue.
|
||||
// Don't re-push the write in the event loop if there was an error; because same error could occur again!
|
||||
// TODO: Add a uv_poll here for unix...
|
||||
// fprintf(stderr, "Write again...\n");
|
||||
uv_queue_work(uv_default_loop(), req, EIO_Write, (uv_after_work_cb)EIO_AfterWrite);
|
||||
return;
|
||||
}
|
||||
|
|
@ -372,8 +357,6 @@ NAN_METHOD(Close) {
|
|||
uv_work_t* req = new uv_work_t();
|
||||
req->data = baton;
|
||||
uv_queue_work(uv_default_loop(), req, EIO_Close, (uv_after_work_cb)EIO_AfterClose);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
void EIO_AfterClose(uv_work_t* req) {
|
||||
|
|
@ -420,8 +403,6 @@ NAN_METHOD(List) {
|
|||
uv_work_t* req = new uv_work_t();
|
||||
req->data = baton;
|
||||
uv_queue_work(uv_default_loop(), req, EIO_List, (uv_after_work_cb)EIO_AfterList);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
void setIfNotEmpty(v8::Local<v8::Object> item, std::string key, const char *value) {
|
||||
|
|
@ -431,7 +412,6 @@ void setIfNotEmpty(v8::Local<v8::Object> item, std::string key, const char *valu
|
|||
} else {
|
||||
Nan::Set(item, v8key, Nan::Undefined());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void EIO_AfterList(uv_work_t* req) {
|
||||
|
|
@ -494,8 +474,6 @@ NAN_METHOD(Flush) {
|
|||
uv_work_t* req = new uv_work_t();
|
||||
req->data = baton;
|
||||
uv_queue_work(uv_default_loop(), req, EIO_Flush, (uv_after_work_cb)EIO_AfterFlush);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
void EIO_AfterFlush(uv_work_t* req) {
|
||||
|
|
@ -552,8 +530,6 @@ NAN_METHOD(Set) {
|
|||
uv_work_t* req = new uv_work_t();
|
||||
req->data = baton;
|
||||
uv_queue_work(uv_default_loop(), req, EIO_Set, (uv_after_work_cb)EIO_AfterSet);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
void EIO_AfterSet(uv_work_t* req) {
|
||||
|
|
@ -599,8 +575,6 @@ NAN_METHOD(Get) {
|
|||
uv_work_t* req = new uv_work_t();
|
||||
req->data = baton;
|
||||
uv_queue_work(uv_default_loop(), req, EIO_Get, (uv_after_work_cb)EIO_AfterGet);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
void EIO_AfterGet(uv_work_t* req) {
|
||||
|
|
@ -650,8 +624,6 @@ NAN_METHOD(Drain) {
|
|||
uv_work_t* req = new uv_work_t();
|
||||
req->data = baton;
|
||||
uv_queue_work(uv_default_loop(), req, EIO_Drain, (uv_after_work_cb)EIO_AfterDrain);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
void EIO_AfterDrain(uv_work_t* req) {
|
||||
|
|
@ -715,7 +687,7 @@ extern "C" {
|
|||
Nan::SetMethod(target, "drain", Drain);
|
||||
|
||||
#ifndef WIN32
|
||||
SerialportPoller::Init(target);
|
||||
ReadPoller::Init(target);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
#ifndef _serialport_h_
|
||||
#define _serialport_h_
|
||||
#ifndef SRC_SERIALPORT_H_
|
||||
#define SRC_SERIALPORT_H_
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
|
@ -17,7 +17,6 @@ void EIO_AfterList(uv_work_t* req);
|
|||
NAN_METHOD(Open);
|
||||
void EIO_Open(uv_work_t* req);
|
||||
void EIO_AfterOpen(uv_work_t* req);
|
||||
void AfterOpenSuccess(int fd, Nan::Callback* dataCallback, Nan::Callback* disconnectedCallback, Nan::Callback* errorCallback);
|
||||
|
||||
NAN_METHOD(Update);
|
||||
void EIO_Update(uv_work_t* req);
|
||||
|
|
@ -64,9 +63,6 @@ enum SerialPortStopBits {
|
|||
SerialPortParity ToParityEnum(const v8::Local<v8::String>& str);
|
||||
SerialPortStopBits ToStopBitEnum(double stopBits);
|
||||
|
||||
struct OpenBatonPlatformOptions { };
|
||||
OpenBatonPlatformOptions* ParsePlatformOptions(const v8::Local<v8::Object>& options);
|
||||
|
||||
struct OpenBaton {
|
||||
char errorString[ERROR_STRING_SIZE];
|
||||
Nan::Callback callback;
|
||||
|
|
@ -75,7 +71,6 @@ struct OpenBaton {
|
|||
int result;
|
||||
int baudRate;
|
||||
int dataBits;
|
||||
int bufferSize;
|
||||
bool rtscts;
|
||||
bool xon;
|
||||
bool xoff;
|
||||
|
|
@ -83,12 +78,12 @@ struct OpenBaton {
|
|||
bool dsrdtr;
|
||||
bool hupcl;
|
||||
bool lock;
|
||||
Nan::Callback* dataCallback;
|
||||
Nan::Callback* disconnectedCallback;
|
||||
Nan::Callback* errorCallback;
|
||||
SerialPortParity parity;
|
||||
SerialPortStopBits stopBits;
|
||||
OpenBatonPlatformOptions* platformOptions;
|
||||
#ifndef WIN32
|
||||
uint8_t vmin;
|
||||
uint8_t vtime;
|
||||
#endif
|
||||
};
|
||||
|
||||
struct ConnectionOptionsBaton {
|
||||
|
|
@ -191,4 +186,4 @@ struct VoidBaton {
|
|||
|
||||
int setup(int fd, OpenBaton *data);
|
||||
int setBaudRate(ConnectionOptionsBaton *data);
|
||||
#endif
|
||||
#endif // SRC_SERIALPORT_H_
|
||||
|
|
|
|||
|
|
@ -1,5 +1,4 @@
|
|||
#include "./serialport.h"
|
||||
#include "./serialport_poller.h"
|
||||
#include <sys/file.h>
|
||||
#include <unistd.h>
|
||||
#include <fcntl.h>
|
||||
|
|
@ -32,31 +31,10 @@ Boolean lockInitialised = FALSE;
|
|||
#include <linux/serial.h>
|
||||
#endif
|
||||
|
||||
struct UnixPlatformOptions : OpenBatonPlatformOptions {
|
||||
uint8_t vmin;
|
||||
uint8_t vtime;
|
||||
};
|
||||
|
||||
OpenBatonPlatformOptions* ParsePlatformOptions(const v8::Local<v8::Object>& options) {
|
||||
Nan::HandleScope scope;
|
||||
|
||||
UnixPlatformOptions* result = new UnixPlatformOptions();
|
||||
result->vmin = Nan::Get(options, Nan::New<v8::String>("vmin").ToLocalChecked()).ToLocalChecked()->ToInt32()->Int32Value();
|
||||
result->vtime = Nan::Get(options, Nan::New<v8::String>("vtime").ToLocalChecked()).ToLocalChecked()->ToInt32()->Int32Value();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
int ToBaudConstant(int baudRate);
|
||||
int ToDataBitsConstant(int dataBits);
|
||||
int ToStopBitsConstant(SerialPortStopBits stopBits);
|
||||
|
||||
void AfterOpenSuccess(int fd, Nan::Callback* dataCallback, Nan::Callback* disconnectedCallback, Nan::Callback* errorCallback) {
|
||||
delete dataCallback;
|
||||
delete errorCallback;
|
||||
delete disconnectedCallback;
|
||||
}
|
||||
|
||||
int ToBaudConstant(int baudRate) {
|
||||
switch (baudRate) {
|
||||
case 0: return B0;
|
||||
|
|
@ -149,7 +127,10 @@ int setBaudRate(ConnectionOptionsBaton *data) {
|
|||
|
||||
// get port options
|
||||
struct termios options;
|
||||
tcgetattr(fd, &options);
|
||||
if (-1 == tcgetattr(fd, &options)) {
|
||||
snprintf(data->errorString, sizeof(data->errorString), "Error: %s setting custom baud rate of %d", strerror(errno), data->baudRate);
|
||||
return -1;
|
||||
}
|
||||
|
||||
// If there is a custom baud rate on linux you can do the following trick with B38400
|
||||
#if defined(__linux__) && defined(ASYNC_SPD_CUST)
|
||||
|
|
@ -207,8 +188,6 @@ void EIO_Update(uv_work_t* req) {
|
|||
}
|
||||
|
||||
int setup(int fd, OpenBaton *data) {
|
||||
UnixPlatformOptions* platformOptions = static_cast<UnixPlatformOptions*>(data->platformOptions);
|
||||
|
||||
int dataBits = ToDataBitsConstant(data->dataBits);
|
||||
if (-1 == dataBits) {
|
||||
snprintf(data->errorString, sizeof(data->errorString), "Invalid data bits setting %d", data->dataBits);
|
||||
|
|
@ -321,17 +300,19 @@ int setup(int fd, OpenBaton *data) {
|
|||
// ICANON makes partial lines not readable. It should be optional.
|
||||
// It works with ICRNL.
|
||||
options.c_lflag = 0; // ICANON;
|
||||
|
||||
options.c_cc[VMIN]= platformOptions->vmin;
|
||||
options.c_cc[VTIME]= platformOptions->vtime;
|
||||
options.c_cc[VMIN]= data->vmin;
|
||||
options.c_cc[VTIME]= data->vtime;
|
||||
|
||||
// why?
|
||||
tcflush(fd, TCIFLUSH);
|
||||
|
||||
// check for error?
|
||||
// Note that tcsetattr() returns success if any of the requested changes could be successfully carried out.
|
||||
// Therefore, when making multiple changes it may be necessary to follow this call with a further call to
|
||||
// tcgetattr() to check that all changes have been performed successfully.
|
||||
// This also fails on OSX
|
||||
tcsetattr(fd, TCSANOW, &options);
|
||||
|
||||
if (data->lock){
|
||||
if (data->lock) {
|
||||
if (-1 == flock(fd, LOCK_EX | LOCK_NB)) {
|
||||
snprintf(data->errorString, sizeof(data->errorString), "Error %s Cannot lock port", strerror(errno));
|
||||
return -1;
|
||||
|
|
@ -362,7 +343,7 @@ void EIO_Write(uv_work_t* req) {
|
|||
}
|
||||
|
||||
// Try again in another event loop
|
||||
if (errno == EAGAIN || errno == EWOULDBLOCK){
|
||||
if (errno == EAGAIN || errno == EWOULDBLOCK) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -10,19 +10,11 @@
|
|||
|
||||
#define MAX_BUFFER_SIZE 1000
|
||||
|
||||
struct WindowsPlatformOptions : OpenBatonPlatformOptions {
|
||||
};
|
||||
|
||||
OpenBatonPlatformOptions* ParsePlatformOptions(const v8::Local<v8::Object>& options) {
|
||||
// currently none
|
||||
return new WindowsPlatformOptions();
|
||||
}
|
||||
|
||||
// Declare type of pointer to CancelIoEx function
|
||||
typedef BOOL (WINAPI *CancelIoExType)(HANDLE hFile, LPOVERLAPPED lpOverlapped);
|
||||
|
||||
std::list<int> g_closingHandles;
|
||||
int bufferSize;
|
||||
|
||||
void ErrorCodeToString(const char* prefix, int errorCode, char *errorStr) {
|
||||
switch (errorCode) {
|
||||
case ERROR_FILE_NOT_FOUND:
|
||||
|
|
@ -77,11 +69,6 @@ void EIO_Open(uv_work_t* req) {
|
|||
return;
|
||||
}
|
||||
|
||||
bufferSize = data->bufferSize;
|
||||
if (bufferSize > MAX_BUFFER_SIZE) {
|
||||
bufferSize = MAX_BUFFER_SIZE;
|
||||
}
|
||||
|
||||
DCB dcb = { 0 };
|
||||
SecureZeroMemory(&dcb, sizeof(DCB));
|
||||
dcb.DCBlength = sizeof(DCB);
|
||||
|
|
@ -255,71 +242,6 @@ void EIO_Get(uv_work_t* req) {
|
|||
data->dcd = bits & MS_RLSD_ON;
|
||||
}
|
||||
|
||||
void EIO_WatchPort(uv_work_t* req) {
|
||||
WatchPortBaton* data = static_cast<WatchPortBaton*>(req->data);
|
||||
data->bytesRead = 0;
|
||||
data->disconnected = false;
|
||||
|
||||
// Event used by GetOverlappedResult(..., TRUE) to wait for incoming data or timeout
|
||||
// Event MUST be used if program has several simultaneous asynchronous operations
|
||||
// on the same handle (i.e. ReadFile and WriteFile)
|
||||
HANDLE hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
|
||||
|
||||
while (true) {
|
||||
OVERLAPPED ov = {0};
|
||||
ov.hEvent = hEvent;
|
||||
|
||||
// Start read operation - synchrounous or asynchronous
|
||||
DWORD bytesReadSync = 0;
|
||||
if (!ReadFile((HANDLE)data->fd, data->buffer, bufferSize, &bytesReadSync, &ov)) {
|
||||
data->errorCode = GetLastError();
|
||||
if (data->errorCode != ERROR_IO_PENDING) {
|
||||
// Read operation error
|
||||
if (data->errorCode == ERROR_OPERATION_ABORTED) {
|
||||
data->disconnected = true;
|
||||
} else {
|
||||
ErrorCodeToString("Reading from COM port (ReadFile)", data->errorCode, data->errorString);
|
||||
CloseHandle(hEvent);
|
||||
return;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
// Read operation is asynchronous and is pending
|
||||
// We MUST wait for operation completion before deallocation of OVERLAPPED struct
|
||||
// or read data buffer
|
||||
|
||||
// Wait for async read operation completion or timeout
|
||||
DWORD bytesReadAsync = 0;
|
||||
if (!GetOverlappedResult((HANDLE)data->fd, &ov, &bytesReadAsync, TRUE)) {
|
||||
// Read operation error
|
||||
data->errorCode = GetLastError();
|
||||
if (data->errorCode == ERROR_OPERATION_ABORTED) {
|
||||
data->disconnected = true;
|
||||
} else {
|
||||
ErrorCodeToString("Reading from COM port (GetOverlappedResult)", data->errorCode, data->errorString);
|
||||
CloseHandle(hEvent);
|
||||
return;
|
||||
}
|
||||
break;
|
||||
} else {
|
||||
// Read operation completed asynchronously
|
||||
data->bytesRead = bytesReadAsync;
|
||||
}
|
||||
} else {
|
||||
// Read operation completed synchronously
|
||||
data->bytesRead = bytesReadSync;
|
||||
}
|
||||
|
||||
// Return data received if any
|
||||
if (data->bytesRead > 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
CloseHandle(hEvent);
|
||||
}
|
||||
|
||||
bool IsClosingHandle(int fd) {
|
||||
for (std::list<int>::iterator it = g_closingHandles.begin(); it != g_closingHandles.end(); ++it) {
|
||||
if (fd == *it) {
|
||||
|
|
@ -346,56 +268,6 @@ static void FinalizerCallback(char* data, void* hint) {
|
|||
delete req;
|
||||
}
|
||||
|
||||
void EIO_AfterWatchPort(uv_work_t* req) {
|
||||
Nan::HandleScope scope;
|
||||
|
||||
WatchPortBaton* data = static_cast<WatchPortBaton*>(req->data);
|
||||
if (data->disconnected) {
|
||||
data->disconnectedCallback->Call(0, NULL);
|
||||
DisposeWatchPortCallbacks(data);
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
bool skipCleanup = false;
|
||||
if (data->bytesRead > 0) {
|
||||
v8::Local<v8::Value> argv[1];
|
||||
argv[0] = Nan::NewBuffer(data->buffer, data->bytesRead, FinalizerCallback, req).ToLocalChecked();
|
||||
skipCleanup = true;
|
||||
data->dataCallback->Call(1, argv);
|
||||
} else if (data->errorCode > 0) {
|
||||
if (data->errorCode == ERROR_INVALID_HANDLE && IsClosingHandle((int)data->fd)) {
|
||||
DisposeWatchPortCallbacks(data);
|
||||
goto cleanup;
|
||||
} else {
|
||||
v8::Local<v8::Value> argv[1];
|
||||
argv[0] = Nan::Error(data->errorString);
|
||||
data->errorCallback->Call(1, argv);
|
||||
Sleep(100); // prevent the errors from occurring too fast
|
||||
}
|
||||
}
|
||||
AfterOpenSuccess((int)data->fd, data->dataCallback, data->disconnectedCallback, data->errorCallback);
|
||||
|
||||
cleanup:
|
||||
if (!skipCleanup) {
|
||||
delete data;
|
||||
delete req;
|
||||
}
|
||||
}
|
||||
|
||||
void AfterOpenSuccess(int fd, Nan::Callback* dataCallback, Nan::Callback* disconnectedCallback, Nan::Callback* errorCallback) {
|
||||
WatchPortBaton* baton = new WatchPortBaton();
|
||||
memset(baton, 0, sizeof(WatchPortBaton));
|
||||
baton->fd = (HANDLE)fd;
|
||||
baton->dataCallback = dataCallback;
|
||||
baton->errorCallback = errorCallback;
|
||||
baton->disconnectedCallback = disconnectedCallback;
|
||||
|
||||
uv_work_t* req = new uv_work_t();
|
||||
req->data = baton;
|
||||
|
||||
uv_queue_work(uv_default_loop(), req, EIO_WatchPort, (uv_after_work_cb)EIO_AfterWatchPort);
|
||||
}
|
||||
|
||||
void EIO_Write(uv_work_t* req) {
|
||||
QueuedWrite* queuedWrite = static_cast<QueuedWrite*>(req->data);
|
||||
WriteBaton* data = static_cast<WriteBaton*>(queuedWrite->baton);
|
||||
|
|
|
|||
|
|
@ -1,81 +0,0 @@
|
|||
'use strict';
|
||||
var crypto = require('crypto');
|
||||
var assert = require('chai').assert;
|
||||
var SerialPort = require('../../');
|
||||
|
||||
var platform;
|
||||
switch (process.platform) {
|
||||
case 'win32':
|
||||
platform = 'win32';
|
||||
break;
|
||||
case 'darwin':
|
||||
platform = 'darwin';
|
||||
break;
|
||||
default:
|
||||
platform = 'unix';
|
||||
}
|
||||
|
||||
var testPort = process.env.TEST_PORT;
|
||||
|
||||
describe('SerialPort Integration Tests', function() {
|
||||
if (!testPort) {
|
||||
it('Requires an Arduino loaded with the arduinoEcho program on a serialport set to the TEST_PORT env var');
|
||||
return;
|
||||
}
|
||||
|
||||
it('.list', function(done) {
|
||||
SerialPort.list(function(err, ports) {
|
||||
var foundPort = false;
|
||||
ports.forEach(function(port) {
|
||||
if (port.comName === testPort) {
|
||||
foundPort = true;
|
||||
}
|
||||
});
|
||||
assert.isTrue(foundPort);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
// Be careful to close the ports when you're done with them
|
||||
// Ports are exclusively locked in windows and maybe other platforms eventually
|
||||
|
||||
describe('#update', function() {
|
||||
if (platform === 'win32') {
|
||||
return it("Isn't supported on windows yet");
|
||||
}
|
||||
|
||||
it('allows changing the baud rate of an open port', function(done) {
|
||||
var port = new SerialPort(testPort, function() {
|
||||
port.update({baudRate: 57600}, function(err) {
|
||||
assert.isNull(err);
|
||||
port.close(done);
|
||||
});
|
||||
});
|
||||
});
|
||||
it('can still read and write after a baud change');
|
||||
});
|
||||
|
||||
describe('#read and #write', function() {
|
||||
it('writes 5k and reads it back', function(done) {
|
||||
this.timeout(20000);
|
||||
// 5k of random ascii
|
||||
var output = new Buffer(crypto.randomBytes(5000).toString('ascii'));
|
||||
var expectedInput = Buffer.concat([new Buffer('READY'), output]);
|
||||
var port = new SerialPort(testPort);
|
||||
|
||||
// this will trigger from the "READY" the arduino sends when it's... ready
|
||||
port.once('data', function() {
|
||||
port.write(output);
|
||||
});
|
||||
|
||||
var input = new Buffer(0);
|
||||
port.on('data', function(data) {
|
||||
input = Buffer.concat([input, data]);
|
||||
if (input.length === expectedInput.length) {
|
||||
assert.deepEqual(expectedInput, input);
|
||||
port.close(done);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
1002
test/bindings.js
1002
test/bindings.js
File diff suppressed because it is too large
Load diff
|
|
@ -1,124 +0,0 @@
|
|||
'use strict';
|
||||
|
||||
// These tests require an empty serialport to exist. Nothing needs to respond on the other end.
|
||||
|
||||
var assert = require('chai').assert;
|
||||
var SerialPort = require('../');
|
||||
|
||||
var platform;
|
||||
switch (process.platform) {
|
||||
case 'win32':
|
||||
platform = 'win32';
|
||||
break;
|
||||
case 'darwin':
|
||||
platform = 'darwin';
|
||||
break;
|
||||
default:
|
||||
platform = 'unix';
|
||||
}
|
||||
|
||||
var testPort = process.env.TEST_PORT;
|
||||
|
||||
describe('SerialPort light integration', function() {
|
||||
describe('Initialization', function() {
|
||||
it('Throws an error in callback when trying to open an invalid port', function(done) {
|
||||
this.port = new SerialPort('COM99', function(err) {
|
||||
assert.instanceOf(err, Error);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('Emits an error in an event when trying to open an invalid port', function(done) {
|
||||
var port = new SerialPort('COM99');
|
||||
port.on('error', function(err) {
|
||||
assert.instanceOf(err, Error);
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('.list', function(done) {
|
||||
SerialPort.list(done);
|
||||
});
|
||||
|
||||
// Be careful to close the ports when you're done with them
|
||||
// Ports are exclusively locked in windows and maybe other platforms eventually
|
||||
describe('with an actual port', function() {
|
||||
if (!testPort) {
|
||||
it('Cannot be tested further. Set the TEST_PORT env var with an available serialport for more testing.');
|
||||
return;
|
||||
}
|
||||
|
||||
describe('opening and closing', function() {
|
||||
it('can open and close', function(done) {
|
||||
var port = new SerialPort(testPort);
|
||||
port.on('open', function() {
|
||||
assert.isTrue(port.isOpen);
|
||||
port.close();
|
||||
});
|
||||
port.on('close', function() {
|
||||
assert.isFalse(port.isOpen);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('cannot be opened twice in the callback', function(done) {
|
||||
var port = new SerialPort(testPort, function(err) {
|
||||
assert.isNull(err);
|
||||
port.open(function(err) {
|
||||
assert.instanceOf(err, Error);
|
||||
port.close(done);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('cannot be opened twice', function(done) {
|
||||
var port = new SerialPort(testPort, { autoOpen: false });
|
||||
var calls = 0;
|
||||
var errors = 0;
|
||||
var spy = function(err) {
|
||||
calls++;
|
||||
if (err) {
|
||||
errors++;
|
||||
assert.instanceOf(err, Error);
|
||||
}
|
||||
if (calls === 2) {
|
||||
assert.strictEqual(errors, 1);
|
||||
port.close(done);
|
||||
}
|
||||
};
|
||||
port.open(spy);
|
||||
port.open(spy);
|
||||
});
|
||||
|
||||
it('can open and close ports repetitively', function(done) {
|
||||
var port = new SerialPort(testPort, { autoOpen: false });
|
||||
port.open(function(err) {
|
||||
assert.isNull(err);
|
||||
port.close(function(err) {
|
||||
assert.isNull(err);
|
||||
port.open(function(err) {
|
||||
assert.isNull(err);
|
||||
port.close(done);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('#update', function() {
|
||||
if (platform === 'win32') {
|
||||
return it("Isn't supported on windows yet");
|
||||
}
|
||||
|
||||
it('allows changing the baud rate of an open port', function(done) {
|
||||
var port = new SerialPort(testPort, function() {
|
||||
port.update({baudRate: 57600}, function(err) {
|
||||
assert.isNull(err);
|
||||
port.close(done);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
177
test/integration.js
Normal file
177
test/integration.js
Normal file
|
|
@ -0,0 +1,177 @@
|
|||
'use strict';
|
||||
var crypto = require('crypto');
|
||||
var assert = require('chai').assert;
|
||||
var SerialPort = require('../');
|
||||
|
||||
var platform;
|
||||
switch (process.platform) {
|
||||
case 'win32':
|
||||
platform = 'win32';
|
||||
break;
|
||||
case 'darwin':
|
||||
platform = 'darwin';
|
||||
break;
|
||||
default:
|
||||
platform = 'unix';
|
||||
}
|
||||
|
||||
var readyData = new Buffer('READY');
|
||||
|
||||
// test everything on our mock biding and natively
|
||||
var defaultBinding = SerialPort.Binding;
|
||||
var mockBinding = require('../lib/bindings-mock');
|
||||
|
||||
var mockTestPort = '/dev/exists';
|
||||
mockBinding.createPort(mockTestPort, { echo: true, readyData: readyData });
|
||||
|
||||
// eslint-disable-next-line no-use-before-define
|
||||
integrationTest('mock', mockTestPort, mockBinding);
|
||||
|
||||
// eslint-disable-next-line no-use-before-define
|
||||
integrationTest(platform, process.env.TEST_PORT, defaultBinding);
|
||||
|
||||
// Be careful to close the ports when you're done with them
|
||||
// Ports are by default exclusively locked so a failure fails all tests
|
||||
function integrationTest(platform, testPort, binding) {
|
||||
describe(platform + ' SerialPort Integration Tests', function() {
|
||||
if (!testPort) {
|
||||
it(platform + ' tests requires an Arduino loaded with the arduinoEcho program on a serialport set to the TEST_PORT env var');
|
||||
return;
|
||||
}
|
||||
|
||||
beforeEach(function() {
|
||||
SerialPort.Binding = binding;
|
||||
});
|
||||
|
||||
describe('static Method', function() {
|
||||
describe('.list', function() {
|
||||
it('contains the test port', function(done) {
|
||||
function lastPath(name) {
|
||||
var parts = name.split('.');
|
||||
return parts[parts.length - 1];
|
||||
}
|
||||
|
||||
SerialPort.list(function(err, ports) {
|
||||
var foundPort = false;
|
||||
ports.forEach(function(port) {
|
||||
if (lastPath(port.comName) === lastPath(testPort)) {
|
||||
foundPort = true;
|
||||
}
|
||||
});
|
||||
assert.isTrue(foundPort);
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('constructor', function() {
|
||||
it('provides an error in callback when trying to open an invalid port', function(done) {
|
||||
this.port = new SerialPort('COMBAD', function(err) {
|
||||
assert.instanceOf(err, Error);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('emits an error event when trying to open an invalid port', function(done) {
|
||||
var port = new SerialPort('COM99');
|
||||
port.on('error', function(err) {
|
||||
assert.instanceOf(err, Error);
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('opening and closing', function() {
|
||||
it('can open and close', function(done) {
|
||||
var port = new SerialPort(testPort);
|
||||
port.on('open', function() {
|
||||
assert.isTrue(port.isOpen);
|
||||
port.close();
|
||||
});
|
||||
port.on('close', function() {
|
||||
assert.isFalse(port.isOpen);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('cannot be opened again after open', function(done) {
|
||||
var port = new SerialPort(testPort, function(err) {
|
||||
assert.isNull(err);
|
||||
port.open(function(err) {
|
||||
assert.instanceOf(err, Error);
|
||||
port.close(done);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('cannot be opened while opening', function(done) {
|
||||
var port = new SerialPort(testPort, { autoOpen: false });
|
||||
port.open(function(err) {
|
||||
assert.isNull(err);
|
||||
});
|
||||
port.open(function(err) {
|
||||
assert.instanceOf(err, Error);
|
||||
assert.strictEqual(err.message, 'Port is opening');
|
||||
});
|
||||
port.on('open', function() {
|
||||
port.close(done);
|
||||
});
|
||||
});
|
||||
|
||||
it('can open and close ports repetitively', function(done) {
|
||||
var port = new SerialPort(testPort, { autoOpen: false });
|
||||
port.open(function(err) {
|
||||
assert.isNull(err);
|
||||
port.close(function(err) {
|
||||
assert.isNull(err);
|
||||
port.open(function(err) {
|
||||
assert.isNull(err);
|
||||
port.close(done);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('#update', function() {
|
||||
if (platform === 'win32') {
|
||||
return it("Isn't supported on windows yet");
|
||||
}
|
||||
|
||||
it('allows changing the baud rate of an open port', function(done) {
|
||||
var port = new SerialPort(testPort, function() {
|
||||
port.update({baudRate: 57600}, function(err) {
|
||||
assert.isNull(err);
|
||||
port.close(done);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('#read and #write', function() {
|
||||
it('5k test', function(done) {
|
||||
this.timeout(20000);
|
||||
// 5k of random ascii
|
||||
var output = new Buffer(crypto.randomBytes(5120).toString('ascii'));
|
||||
var expectedInput = Buffer.concat([readyData, output]);
|
||||
var port = new SerialPort(testPort);
|
||||
|
||||
// this will trigger from the "READY" the arduino sends when it's... ready
|
||||
port.once('data', function() {
|
||||
port.write(output);
|
||||
});
|
||||
|
||||
var input = new Buffer(0);
|
||||
port.on('data', function(data) {
|
||||
input = Buffer.concat([input, data]);
|
||||
if (input.length >= expectedInput.length) {
|
||||
assert.equal(input.length, expectedInput.length);
|
||||
assert.deepEqual(input, expectedInput);
|
||||
port.close(done);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
|
@ -1,226 +0,0 @@
|
|||
// This takes a serial-port factory and mocks it in complete isolation
|
||||
|
||||
'use strict';
|
||||
|
||||
function callLater() {
|
||||
var args = Array.prototype.slice.call(arguments);
|
||||
var callback = args.shift();
|
||||
process.nextTick(function() {
|
||||
callback && callback.apply(null, args);
|
||||
});
|
||||
}
|
||||
|
||||
var mockSerialportPoller = function(hardware) {
|
||||
var Poller = function(fd, cb) {
|
||||
this.port = hardware.fds[fd];
|
||||
if (!this.port) {
|
||||
throw new Error(fd + ' does not exist - please call hardware.createPort(path) first');
|
||||
}
|
||||
this.port.poller = this;
|
||||
this.polling = null;
|
||||
this.cb = cb;
|
||||
};
|
||||
Poller.prototype.start = function() {
|
||||
this.polling = true;
|
||||
};
|
||||
Poller.prototype.close = function() {
|
||||
this.polling = false;
|
||||
};
|
||||
Poller.prototype.detectRead = function() {
|
||||
this.cb();
|
||||
};
|
||||
return Poller;
|
||||
};
|
||||
|
||||
var Hardware = function() {
|
||||
this.nextFd = 0;
|
||||
this.fds = {};
|
||||
this.ports = {};
|
||||
this.mockBinding = {
|
||||
close: this.close.bind(this),
|
||||
drain: this.drain.bind(this),
|
||||
flush: this.flush.bind(this),
|
||||
list: this.list.bind(this),
|
||||
open: this.open.bind(this),
|
||||
SerialportPoller: mockSerialportPoller(this),
|
||||
set: this.set.bind(this),
|
||||
get: this.get.bind(this),
|
||||
update: this.update.bind(this),
|
||||
write: this.write.bind(this)
|
||||
};
|
||||
};
|
||||
|
||||
Hardware.prototype.reset = function() {
|
||||
this.ports = {};
|
||||
this.fds = {};
|
||||
this.nextFd = 0;
|
||||
};
|
||||
|
||||
Hardware.prototype.createPort = function(path) {
|
||||
if (this.ports[path]) {
|
||||
delete this.fds[this.ports[path].fd];
|
||||
}
|
||||
var fd = this.nextFd++;
|
||||
this.ports[path] = {
|
||||
data: new Buffer(0),
|
||||
lastWrite: null,
|
||||
open: false,
|
||||
poller: null,
|
||||
info: {
|
||||
comName: path,
|
||||
manufacturer: '',
|
||||
serialNumber: '',
|
||||
pnpId: '',
|
||||
locationId: '',
|
||||
vendorId: '',
|
||||
productId: ''
|
||||
},
|
||||
fd: fd
|
||||
};
|
||||
this.fds[fd] = this.ports[path];
|
||||
};
|
||||
|
||||
Hardware.prototype.emitData = function(path, data) {
|
||||
var port = this.ports[path];
|
||||
if (!port) {
|
||||
throw new Error(path + ' does not exist - please call hardware.createPort(path) first');
|
||||
}
|
||||
port.data = Buffer.concat([port.data, data]);
|
||||
port.poller && port.poller.detectRead();
|
||||
};
|
||||
|
||||
Hardware.prototype.disconnect = function(path) {
|
||||
var port = this.ports[path];
|
||||
if (!port) {
|
||||
throw new Error(path + ' does not exist - please call hardware.createPort(path) first');
|
||||
}
|
||||
var err = new Error('disconnected');
|
||||
port.openOpt.disconnectedCallback(err);
|
||||
};
|
||||
|
||||
Hardware.prototype.list = function(cb) {
|
||||
var ports = this.ports;
|
||||
var info = Object.keys(ports).map(function(path) {
|
||||
return ports[path].info;
|
||||
});
|
||||
callLater(cb, null, info);
|
||||
};
|
||||
|
||||
Hardware.prototype.open = function(path, opt, cb) {
|
||||
var port = this.ports[path];
|
||||
if (!port) {
|
||||
return cb(new Error(path + ' does not exist - please call hardware.createPort(path) first'));
|
||||
}
|
||||
port.open = true;
|
||||
port.openOpt = opt;
|
||||
callLater(cb, null, port.fd);
|
||||
};
|
||||
|
||||
Hardware.prototype.update = function(fd, opt, cb) {
|
||||
var port = this.fds[fd];
|
||||
if (!port) {
|
||||
return cb(new Error(fd + ' does not exist - please call hardware.createPort(path) first'));
|
||||
}
|
||||
callLater(cb, null);
|
||||
};
|
||||
|
||||
Hardware.prototype.write = function(fd, buffer, cb) {
|
||||
var port = this.fds[fd];
|
||||
if (!port) {
|
||||
return cb(new Error(fd + ' does not exist - please call hardware.createPort(path) first'));
|
||||
}
|
||||
port.lastWrite = new Buffer(buffer); // copy
|
||||
callLater(cb, null, buffer.length);
|
||||
};
|
||||
|
||||
Hardware.prototype.close = function(fd, cb) {
|
||||
var port = this.fds[fd];
|
||||
if (!port) {
|
||||
return cb(new Error(fd + ' does not exist - please call hardware.createPort(path) first'));
|
||||
}
|
||||
if (!port.open) {
|
||||
return cb(new Error(fd + ' fd is already closed'));
|
||||
}
|
||||
port.open = false;
|
||||
callLater(cb, null);
|
||||
};
|
||||
|
||||
Hardware.prototype.flush = function(fd, cb) {
|
||||
var port = this.fds[fd];
|
||||
if (!port) {
|
||||
return cb(new Error(fd + ' does not exist - please call hardware.createPort(path) first'));
|
||||
}
|
||||
callLater(cb, null, undefined);
|
||||
};
|
||||
|
||||
Hardware.prototype.set = function(fd, options, cb) {
|
||||
var port = this.fds[fd];
|
||||
if (!port) {
|
||||
return cb(new Error(fd + ' does not exist - please call hardware.createPort(path) first'));
|
||||
}
|
||||
callLater(cb, null, undefined);
|
||||
};
|
||||
|
||||
Hardware.prototype.get = function(fd, cb) {
|
||||
var port = this.fds[fd];
|
||||
if (!port) {
|
||||
return cb(new Error(fd + ' does not exist - please call hardware.createPort(path) first'));
|
||||
}
|
||||
callLater(cb, null, {
|
||||
cts: false,
|
||||
dsr: false,
|
||||
dcd: false
|
||||
});
|
||||
};
|
||||
|
||||
Hardware.prototype.drain = function(fd, cb) {
|
||||
var port = this.fds[fd];
|
||||
if (!port) {
|
||||
return cb(new Error(fd + ' does not exist - please call hardware.createPort(path) first'));
|
||||
}
|
||||
callLater(cb, null, undefined);
|
||||
};
|
||||
|
||||
Hardware.prototype.fakeRead = function(fd, buffer, offset, length, position, cb) {
|
||||
var port = this.fds[fd];
|
||||
if (!port) {
|
||||
return cb(new Error(fd + ' does not exist - please call hardware.createPort(path) first'));
|
||||
}
|
||||
if (port.data.length === 0) {
|
||||
return cb(null, 0, buffer);
|
||||
}
|
||||
if ((offset + length) > buffer.length) {
|
||||
throw new Error('Length extends beyond buffer');
|
||||
}
|
||||
|
||||
// node v0.8 doesn't like a slice that is bigger then available data
|
||||
length = port.data.length < length ? port.data.length : length;
|
||||
var read = port.data.slice(0, length);
|
||||
port.data = port.data.slice(length);
|
||||
read.copy(buffer, offset);
|
||||
callLater(cb, null, read.length, buffer);
|
||||
};
|
||||
|
||||
var hardware = new Hardware();
|
||||
|
||||
var SandboxedModule = require('sandboxed-module');
|
||||
|
||||
var SerialPort = SandboxedModule.require('../../', {
|
||||
requires: {
|
||||
fs: {
|
||||
read: hardware.fakeRead.bind(hardware)
|
||||
},
|
||||
'./bindings': hardware.mockBinding
|
||||
},
|
||||
singleOnly: true,
|
||||
globals: {
|
||||
process: {
|
||||
platform: 'darwin',
|
||||
nextTick: process.nextTick
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
SerialPort.hardware = hardware;
|
||||
|
||||
module.exports = SerialPort;
|
||||
|
|
@ -2,44 +2,42 @@
|
|||
|
||||
'use strict';
|
||||
|
||||
var SandboxedModule = require('sandboxed-module');
|
||||
var proxyquire = require('proxyquire');
|
||||
|
||||
var mockPorts = {};
|
||||
var characterDevice = true;
|
||||
var error = false;
|
||||
|
||||
var listLinux = SandboxedModule.require('../../lib/list-linux', {
|
||||
requires: {
|
||||
fs: {
|
||||
readdir: function(path, cb) {
|
||||
if (error) {
|
||||
return process.nextTick(function() {
|
||||
cb(new Error('bad'));
|
||||
});
|
||||
}
|
||||
process.nextTick(function() {
|
||||
cb(null, Object.keys(mockPorts));
|
||||
});
|
||||
},
|
||||
stat: function(path, cb) {
|
||||
process.nextTick(function() {
|
||||
cb(null, { isCharacterDevice: function() { return characterDevice } });
|
||||
var listLinux = proxyquire('../../lib/list-linux', {
|
||||
fs: {
|
||||
readdir: function(path, cb) {
|
||||
if (error) {
|
||||
return process.nextTick(function() {
|
||||
cb(new Error('bad'));
|
||||
});
|
||||
}
|
||||
process.nextTick(function() {
|
||||
cb(null, Object.keys(mockPorts));
|
||||
});
|
||||
},
|
||||
path: {
|
||||
// needed for testing on windows
|
||||
join: function() {
|
||||
return Array.prototype.join.call(arguments, '/');
|
||||
}
|
||||
},
|
||||
child_process: {
|
||||
exec: function(cmd, cb) {
|
||||
var port = cmd.split(/\/dev\/(.*)\)/)[1];
|
||||
process.nextTick(function() {
|
||||
cb(null, mockPorts[port]);
|
||||
});
|
||||
}
|
||||
stat: function(path, cb) {
|
||||
process.nextTick(function() {
|
||||
cb(null, { isCharacterDevice: function() { return characterDevice } });
|
||||
});
|
||||
}
|
||||
},
|
||||
path: {
|
||||
// needed for testing on windows
|
||||
join: function() {
|
||||
return Array.prototype.join.call(arguments, '/');
|
||||
}
|
||||
},
|
||||
child_process: {
|
||||
exec: function(cmd, cb) {
|
||||
var port = cmd.split(/\/dev\/(.*)\)/)[1];
|
||||
process.nextTick(function() {
|
||||
cb(null, mockPorts[port]);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
|
|
|||
85
test/push-methods.js
Normal file
85
test/push-methods.js
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
'use strict';
|
||||
|
||||
var assert = require('chai').assert;
|
||||
var pushBindingWrap = require('../lib/push-methods');
|
||||
var MockBinding = require('../lib/bindings-mock');
|
||||
|
||||
describe('pushBindingWrap()', function() {
|
||||
it('throws when not passed a binding', function(done) {
|
||||
try {
|
||||
pushBindingWrap({push: function() {}});
|
||||
} catch (e) {
|
||||
assert.instanceOf(e, TypeError);
|
||||
done();
|
||||
}
|
||||
});
|
||||
|
||||
it('throws when not passed a push function', function(done) {
|
||||
try {
|
||||
pushBindingWrap({binding: {}});
|
||||
} catch (e) {
|
||||
assert.instanceOf(e, TypeError);
|
||||
done();
|
||||
}
|
||||
});
|
||||
|
||||
it('assigns `_read()` only if not already a method', function(done) {
|
||||
var mockBinding = new MockBinding({disconnect: function() {}});
|
||||
assert.isUndefined(mockBinding._read);
|
||||
pushBindingWrap({ binding: mockBinding, push: function() {}});
|
||||
assert.equal(typeof mockBinding._read, 'function');
|
||||
|
||||
var _read = function() {};
|
||||
var fakeBinding = { _read: _read};
|
||||
pushBindingWrap({ binding: fakeBinding, push: function() {}});
|
||||
assert.equal(fakeBinding._read, _read);
|
||||
done();
|
||||
});
|
||||
|
||||
it('assigns `push()` only if not already a method', function(done) {
|
||||
var mockBinding = new MockBinding({disconnect: function() {}});
|
||||
assert.isUndefined(mockBinding.push);
|
||||
pushBindingWrap({ binding: mockBinding, push: function() {}});
|
||||
assert.equal(typeof mockBinding.push, 'function');
|
||||
|
||||
var push = function() {};
|
||||
var fakeBinding = { push: push};
|
||||
pushBindingWrap({ binding: fakeBinding, push: function() {}});
|
||||
assert.equal(fakeBinding.push, push);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
describe('_read()', function() {
|
||||
it('calls `read()` with the right arguments', function(done) {
|
||||
var bytesToRead = 5;
|
||||
var fakeBinding = {
|
||||
read: function(buffer, offset, bytes) {
|
||||
assert.instanceOf(buffer, Buffer);
|
||||
assert.isNumber(offset);
|
||||
assert.isNumber(bytes);
|
||||
assert(bytes > 0);
|
||||
done();
|
||||
}
|
||||
};
|
||||
pushBindingWrap({binding: fakeBinding, push: function() {}});
|
||||
fakeBinding._read(bytesToRead);
|
||||
});
|
||||
|
||||
it('calls push with available data', function(done) {
|
||||
var readData = new Buffer('12345!');
|
||||
var fakeBinding = {
|
||||
read: function(buffer, offset, bytes, cb) {
|
||||
readData.copy(buffer, offset);
|
||||
process.nextTick(cb.bind(null, null, readData.length, buffer));
|
||||
},
|
||||
push: function(data) {
|
||||
assert.deepEqual(data, readData);
|
||||
done();
|
||||
return false;
|
||||
}
|
||||
};
|
||||
pushBindingWrap({binding: fakeBinding, push: function() {}});
|
||||
fakeBinding._read(6);
|
||||
});
|
||||
});
|
||||
|
|
@ -5,41 +5,26 @@ var chai = require('chai');
|
|||
chai.use(require('chai-subset'));
|
||||
var assert = chai.assert;
|
||||
|
||||
var SerialPort = require('./mocks/darwin-hardware');
|
||||
var hardware = SerialPort.hardware;
|
||||
var bindings = hardware.mockBinding;
|
||||
var SerialPort = require('../lib/serialport');
|
||||
var mockBinding = require('../lib/bindings-mock');
|
||||
|
||||
describe('SerialPort', function() {
|
||||
var sandbox;
|
||||
|
||||
beforeEach(function() {
|
||||
SerialPort.Binding = mockBinding;
|
||||
sandbox = sinon.sandbox.create();
|
||||
|
||||
// Create a port for fun and profit
|
||||
hardware.reset();
|
||||
hardware.createPort('/dev/exists');
|
||||
mockBinding.reset();
|
||||
mockBinding.createPort('/dev/exists', { echo: true, readyData: new Buffer(0) });
|
||||
});
|
||||
|
||||
afterEach(function() {
|
||||
sandbox.restore();
|
||||
});
|
||||
|
||||
describe('Deprecated options', function() {
|
||||
it('legacy constructor still works', function(done){
|
||||
this.port = new SerialPort.SerialPort('/dev/exists', done);
|
||||
});
|
||||
|
||||
it('throws when `openImmediately` is set', function(done) {
|
||||
try {
|
||||
this.port = new SerialPort('/dev/exists', {}, false);
|
||||
} catch (e) {
|
||||
assert.instanceOf(e, TypeError);
|
||||
done();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('Constructor', function() {
|
||||
describe('constructor', function() {
|
||||
it('provides auto construction', function(done) {
|
||||
var serialPort = SerialPort;
|
||||
this.port = serialPort('/dev/exists', done);
|
||||
|
|
@ -67,6 +52,7 @@ describe('SerialPort', function() {
|
|||
});
|
||||
});
|
||||
|
||||
// needs to be passes the callback to open
|
||||
it('passes the error to the callback when an bad port is provided', function(done) {
|
||||
this.port = new SerialPort('/bad/port', function(err) {
|
||||
assert.instanceOf(err, Error);
|
||||
|
|
@ -74,6 +60,7 @@ describe('SerialPort', function() {
|
|||
});
|
||||
});
|
||||
|
||||
// is this a test for open?
|
||||
it('emits an error when an bad port is provided', function(done) {
|
||||
var port = new SerialPort('/bad/port');
|
||||
port.once('error', function(err) {
|
||||
|
|
@ -82,6 +69,16 @@ describe('SerialPort', function() {
|
|||
});
|
||||
});
|
||||
|
||||
it('throws an error when bindings are missing', function(done) {
|
||||
SerialPort.Binding = undefined;
|
||||
try {
|
||||
this.port = new SerialPort('/dev/exists');
|
||||
} catch(err) {
|
||||
assert.instanceOf(err, Error);
|
||||
done();
|
||||
}
|
||||
});
|
||||
|
||||
it('throws an error when no port is provided', function(done) {
|
||||
try {
|
||||
this.port = new SerialPort('');
|
||||
|
|
@ -154,10 +151,10 @@ describe('SerialPort', function() {
|
|||
autoOpen: false
|
||||
};
|
||||
var port = new SerialPort('/dev/exists', options);
|
||||
assert.isTrue(port.options.xon);
|
||||
assert.isTrue(port.options.xoff);
|
||||
assert.isTrue(port.options.xany);
|
||||
assert.isTrue(port.options.rtscts);
|
||||
assert.isTrue(port.settings.xon);
|
||||
assert.isTrue(port.settings.xoff);
|
||||
assert.isTrue(port.settings.xany);
|
||||
assert.isTrue(port.settings.rtscts);
|
||||
done();
|
||||
});
|
||||
|
||||
|
|
@ -166,7 +163,20 @@ describe('SerialPort', function() {
|
|||
});
|
||||
});
|
||||
|
||||
describe('Properties', function() {
|
||||
describe('property', function() {
|
||||
describe('.baudRate', function() {
|
||||
it('is a read only property set during construction', function() {
|
||||
var port = new SerialPort('/dev/exists', {autoOpen: false, baudRate: 14400 });
|
||||
assert.equal(port.baudRate, 14400);
|
||||
try {
|
||||
port.baudRate = 9600;
|
||||
} catch(e) {
|
||||
assert.instanceOf(e, TypeError);
|
||||
}
|
||||
assert.equal(port.baudRate, 14400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('.path', function() {
|
||||
it('is a read only property set during construction', function() {
|
||||
var port = new SerialPort('/dev/exists', {autoOpen: false});
|
||||
|
|
@ -181,7 +191,7 @@ describe('SerialPort', function() {
|
|||
});
|
||||
|
||||
describe('.isOpen', function() {
|
||||
it('is a read only property', function(){
|
||||
it('is a read only property', function() {
|
||||
var port = new SerialPort('/dev/exists', {autoOpen: false});
|
||||
assert.equal(port.isOpen, false);
|
||||
try {
|
||||
|
|
@ -200,7 +210,7 @@ describe('SerialPort', function() {
|
|||
|
||||
it('returns false when the port is opening', function(done) {
|
||||
var port = new SerialPort('/dev/exists', { autoOpen: false });
|
||||
sandbox.stub(bindings, 'open', function() {
|
||||
sandbox.stub(port.binding, 'open', function() {
|
||||
assert.isTrue(port.opening);
|
||||
assert.isFalse(port.isOpen);
|
||||
done();
|
||||
|
|
@ -217,12 +227,11 @@ describe('SerialPort', function() {
|
|||
|
||||
it('returns false when the port is closing', function(done) {
|
||||
var port;
|
||||
sandbox.stub(bindings, 'close', function() {
|
||||
assert.isTrue(port.closing);
|
||||
assert.isFalse(port.isOpen);
|
||||
done();
|
||||
});
|
||||
port = new SerialPort('/dev/exists', {}, function() {
|
||||
sandbox.stub(this.binding, 'close', function() {
|
||||
assert.isFalse(port.isOpen);
|
||||
done();
|
||||
});
|
||||
port.close();
|
||||
});
|
||||
});
|
||||
|
|
@ -239,11 +248,11 @@ describe('SerialPort', function() {
|
|||
});
|
||||
});
|
||||
|
||||
describe('Methods', function() {
|
||||
describe('instance method', function() {
|
||||
describe('#open', function() {
|
||||
it('passes the port to the bindings', function(done) {
|
||||
var openSpy = sandbox.spy(bindings, 'open');
|
||||
var port = new SerialPort('/dev/exists', { autoOpen: false });
|
||||
var openSpy = sandbox.spy(port.binding, 'open');
|
||||
assert.isFalse(port.isOpen);
|
||||
port.open(function(err) {
|
||||
assert.isNull(err);
|
||||
|
|
@ -263,16 +272,15 @@ describe('SerialPort', function() {
|
|||
rtscts: false,
|
||||
hupcl: true,
|
||||
dataBits: 8,
|
||||
stopBits: 1,
|
||||
bufferSize: 65536
|
||||
stopBits: 1
|
||||
};
|
||||
sandbox.stub(bindings, 'open', function(path, opt, cb) {
|
||||
var port = new SerialPort('/dev/exists', { autoOpen: false });
|
||||
sandbox.stub(port.binding, 'open', function(path, opt, cb) {
|
||||
assert.equal(path, '/dev/exists');
|
||||
assert.containSubset(opt, defaultOptions);
|
||||
assert.isFunction(cb);
|
||||
done();
|
||||
});
|
||||
var port = new SerialPort('/dev/exists', { autoOpen: false });
|
||||
port.open();
|
||||
});
|
||||
|
||||
|
|
@ -289,17 +297,18 @@ describe('SerialPort', function() {
|
|||
var port = new SerialPort('/dev/exists', function() {
|
||||
port.close(function() {
|
||||
port.open(function() {
|
||||
port.once('data', function(res) {
|
||||
assert.deepEqual(res, data);
|
||||
done();
|
||||
port.binding.write(data, function() {
|
||||
});
|
||||
hardware.emitData('/dev/exists', data);
|
||||
});
|
||||
});
|
||||
});
|
||||
port.once('data', function(res) {
|
||||
assert.deepEqual(res, data);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('cannot be opened twice in the callback', function(done) {
|
||||
it('cannot be opened again after open', function(done) {
|
||||
var port = new SerialPort('/dev/exists', function() {
|
||||
port.open(function(err) {
|
||||
assert.instanceOf(err, Error);
|
||||
|
|
@ -308,31 +317,23 @@ describe('SerialPort', function() {
|
|||
});
|
||||
});
|
||||
|
||||
it('cannot be opened twice', function(done) {
|
||||
it('cannot be opened while opening', function(done) {
|
||||
var port = new SerialPort('/dev/exists', { autoOpen: false });
|
||||
var calls = 0;
|
||||
var errors = 0;
|
||||
var spy = function(err) {
|
||||
calls++;
|
||||
if (err) {
|
||||
errors++;
|
||||
assert.instanceOf(err, Error);
|
||||
assert.strictEqual(err.message, 'Port is opening');
|
||||
}
|
||||
if (calls === 2) {
|
||||
assert.strictEqual(errors, 1);
|
||||
done();
|
||||
}
|
||||
};
|
||||
port.open(spy);
|
||||
port.open(spy);
|
||||
port.open(function(err) {
|
||||
assert.isNull(err);
|
||||
});
|
||||
port.open(function(err) {
|
||||
assert.instanceOf(err, Error);
|
||||
assert.strictEqual(err.message, 'Port is opening');
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('allows opening after an open error', function(done) {
|
||||
var stub = sandbox.stub(bindings, 'open', function(path, opt, cb) {
|
||||
var port = new SerialPort('/dev/exists', { autoOpen: false });
|
||||
var stub = sandbox.stub(port.binding, 'open', function(path, opt, cb) {
|
||||
cb(new Error('haha no'));
|
||||
});
|
||||
var port = new SerialPort('/dev/exists', { autoOpen: false });
|
||||
port.open(function(err) {
|
||||
assert.instanceOf(err, Error);
|
||||
stub.restore();
|
||||
|
|
@ -341,6 +342,55 @@ describe('SerialPort', function() {
|
|||
});
|
||||
});
|
||||
|
||||
describe('#write', function() {
|
||||
it('writes to the bindings layer', function(done) {
|
||||
var data = new Buffer('Crazy!');
|
||||
var port = new SerialPort('/dev/exists');
|
||||
port.on('open', function() {
|
||||
port.write(data, function() {
|
||||
assert.deepEqual(data, port.binding.port.lastWrite);
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('converts strings to buffers', function(done) {
|
||||
var port = new SerialPort('/dev/exists');
|
||||
port.on('open', function() {
|
||||
var data = 'Crazy!';
|
||||
port.write(data, function() {
|
||||
var lastWrite = port.binding.port.lastWrite;
|
||||
assert.deepEqual(new Buffer(data), lastWrite);
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('converts strings with encodings to buffers', function(done) {
|
||||
var port = new SerialPort('/dev/exists');
|
||||
port.on('open', function() {
|
||||
var data = 'COFFEE';
|
||||
port.write(data, 'hex', function() {
|
||||
var lastWrite = port.binding.port.lastWrite;
|
||||
assert.deepEqual(new Buffer(data, 'hex'), lastWrite);
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('converts arrays to buffers', function(done) {
|
||||
var port = new SerialPort('/dev/exists');
|
||||
port.on('open', function() {
|
||||
var data = [0,32,44,88];
|
||||
port.write(data, function() {
|
||||
var lastWrite = port.binding.port.lastWrite;
|
||||
assert.deepEqual(new Buffer(data), lastWrite);
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('#close', function() {
|
||||
it('emits a close event', function(done) {
|
||||
var port = new SerialPort('/dev/exists', function() {
|
||||
|
|
@ -411,47 +461,21 @@ describe('SerialPort', function() {
|
|||
});
|
||||
});
|
||||
|
||||
describe('#write', function() {
|
||||
describe('#update', function() {
|
||||
it('errors when the port is not open', function(done) {
|
||||
var cb = function() {};
|
||||
var port = new SerialPort('/dev/exists', {autoOpen: false}, cb);
|
||||
port.write(null, function(err) {
|
||||
var port = new SerialPort('/dev/exists', {autoOpen: false});
|
||||
port.update({}, function(err) {
|
||||
assert.instanceOf(err, Error);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('writes to the bindings layer', function(done){
|
||||
var port = new SerialPort('/dev/exists');
|
||||
port.on('open', function(){
|
||||
var data = new Buffer('Crazy!');
|
||||
port.write(data, function(){
|
||||
var lastWrite = hardware.fds[port.fd].lastWrite;
|
||||
assert.deepEqual(data, lastWrite);
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('converts strings to buffers', function(done){
|
||||
var port = new SerialPort('/dev/exists');
|
||||
port.on('open', function(){
|
||||
var data = 'Crazy!';
|
||||
port.write(data, function(){
|
||||
var lastWrite = hardware.fds[port.fd].lastWrite;
|
||||
assert.deepEqual(new Buffer(data), lastWrite);
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('converts arrays to buffers', function(done){
|
||||
var port = new SerialPort('/dev/exists');
|
||||
port.on('open', function(){
|
||||
var data = [0,32,44,88];
|
||||
port.write(data, function(){
|
||||
var lastWrite = hardware.fds[port.fd].lastWrite;
|
||||
assert.deepEqual(new Buffer(data), lastWrite);
|
||||
it('sets the baudRate on the port', function(done) {
|
||||
new SerialPort('/dev/exists', function() {
|
||||
assert.equal(this.baudRate, 9600);
|
||||
this.update({ baudRate: 14400 }, function(err) {
|
||||
assert.equal(this.baudRate, 14400);
|
||||
assert.isNull(err);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
|
@ -477,12 +501,11 @@ describe('SerialPort', function() {
|
|||
rts: true
|
||||
};
|
||||
|
||||
sandbox.stub(bindings, 'set', function(fd, options) {
|
||||
assert.deepEqual(options, settings);
|
||||
done();
|
||||
});
|
||||
|
||||
var port = new SerialPort('/dev/exists', function() {
|
||||
sandbox.stub(port.binding, 'set', function(options) {
|
||||
assert.deepEqual(options, settings);
|
||||
done();
|
||||
});
|
||||
port.set(settings);
|
||||
});
|
||||
});
|
||||
|
|
@ -501,12 +524,12 @@ describe('SerialPort', function() {
|
|||
dts: true,
|
||||
rts: false
|
||||
};
|
||||
sandbox.stub(bindings, 'set', function(fd, options) {
|
||||
assert.deepEqual(options, filledWithMissing);
|
||||
done();
|
||||
});
|
||||
|
||||
var port = new SerialPort('/dev/exists', function() {
|
||||
sandbox.stub(port.binding, 'set', function(options) {
|
||||
assert.deepEqual(options, filledWithMissing);
|
||||
done();
|
||||
});
|
||||
port.set(settings);
|
||||
});
|
||||
});
|
||||
|
|
@ -519,21 +542,40 @@ describe('SerialPort', function() {
|
|||
dts: false,
|
||||
rts: true
|
||||
};
|
||||
sandbox.stub(bindings, 'set', function(fd, options) {
|
||||
assert.deepEqual(options, defaults);
|
||||
done();
|
||||
});
|
||||
|
||||
var port = new SerialPort('/dev/exists', function() {
|
||||
sandbox.stub(port.binding, 'set', function(options) {
|
||||
assert.deepEqual(options, defaults);
|
||||
done();
|
||||
});
|
||||
port.set();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('#flush', function() {
|
||||
it('errors when serialport not open', function(done) {
|
||||
var port = new SerialPort('/dev/exists', { autoOpen: false });
|
||||
port.flush(function(err) {
|
||||
assert.instanceOf(err, Error);
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('#drain', function() {
|
||||
it('drain errors when serialport not open', function(done) {
|
||||
var port = new SerialPort('/dev/exists', { autoOpen: false });
|
||||
port.drain(function(err) {
|
||||
assert.instanceOf(err, Error);
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('#get', function() {
|
||||
it('errors when serialport not open', function(done) {
|
||||
var cb = function() {};
|
||||
var port = new SerialPort('/dev/exists', { autoOpen: false }, cb);
|
||||
var port = new SerialPort('/dev/exists', { autoOpen: false });
|
||||
port.get(function(err) {
|
||||
assert.instanceOf(err, Error);
|
||||
done();
|
||||
|
|
@ -547,55 +589,18 @@ describe('SerialPort', function() {
|
|||
dcd: true
|
||||
};
|
||||
|
||||
sandbox.stub(bindings, 'get', function(fd, cb) {
|
||||
cb(status);
|
||||
});
|
||||
|
||||
var port = new SerialPort('/dev/exists', function() {
|
||||
port.get(function(modemStatus) {
|
||||
port.get(function(err, modemStatus) {
|
||||
assert.deepEqual(modemStatus, status);
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it('flush errors when serialport not open', function(done) {
|
||||
var cb = function() {};
|
||||
var port = new SerialPort('/dev/exists', { autoOpen: false }, cb);
|
||||
port.flush(function(err) {
|
||||
assert.instanceOf(err, Error);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('drain errors when serialport not open', function(done) {
|
||||
var cb = function() {};
|
||||
var port = new SerialPort('/dev/exists', { autoOpen: false }, cb);
|
||||
port.drain(function(err) {
|
||||
assert.instanceOf(err, Error);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('flush should consider 0 to be a valid fd', function(done) {
|
||||
var port = new SerialPort('/dev/exists', function() {
|
||||
assert.strictEqual(port.fd, 0);
|
||||
port.flush(done);
|
||||
});
|
||||
});
|
||||
|
||||
it('drain should consider 0 to be a valid fd', function(done) {
|
||||
var port = new SerialPort('/dev/exists', function() {
|
||||
assert.strictEqual(port.fd, 0);
|
||||
port.drain(done);
|
||||
});
|
||||
});
|
||||
|
||||
it('update should consider 0 a valid file descriptor', function() {
|
||||
var port = new SerialPort('/dev/exists', function(done) {
|
||||
assert.strictEqual(port.fd, 0);
|
||||
port.update({}, done);
|
||||
sandbox.stub(port.binding, 'get', function(cb) {
|
||||
process.nextTick(function() {
|
||||
cb(null, status);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -608,7 +613,7 @@ describe('SerialPort', function() {
|
|||
assert.deepEqual(recvData, testData);
|
||||
done();
|
||||
});
|
||||
hardware.emitData('/dev/exists', testData);
|
||||
port.binding.write(testData, function() {});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -617,7 +622,7 @@ describe('SerialPort', function() {
|
|||
it('emits a disconnect event and closes the port', function(done) {
|
||||
var port = new SerialPort('/dev/exists', function() {
|
||||
assert.isTrue(port.isOpen);
|
||||
hardware.disconnect('/dev/exists');
|
||||
port.binding.disconnect('/dev/exists');
|
||||
});
|
||||
var spy = sandbox.spy();
|
||||
port.on('disconnect', spy);
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue