diff --git a/.docs/README.hbs b/.docs/README.hbs
index ff69607..75f1fca 100644
--- a/.docs/README.hbs
+++ b/.docs/README.hbs
@@ -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.
diff --git a/README.md b/README.md
index f1c5a57..60cf408 100644
--- a/README.md
+++ b/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) ⇒ boolean
+ * [`.read([size])`](#module_serialport--SerialPort+read) ⇒ string | Buffer | null
* [`.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) : [Binding](#module_serialport--SerialPort..Binding)
* [`.parsers`](#module_serialport--SerialPort.parsers) : object
- * [`.list`](#module_serialport--SerialPort.list) : function
+ * [`.list(callback)`](#module_serialport--SerialPort.list) : function
* _inner_
+ * [~Binding](#module_serialport--SerialPort..Binding) : Class
+ * [`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) : function
* [`~errorCallback`](#module_serialport--SerialPort..errorCallback) : function
* [`~modemBitsCallback`](#module_serialport--SerialPort..modemBitsCallback) : function
* [`~openOptions`](#module_serialport--SerialPort..openOptions) : Object
@@ -354,8 +368,10 @@ Enjoy and do cool things with this code.
| Name | Type | Description |
| --- | --- | --- |
+| baudRate | number | The port's baudRate, use `.update` to change it. Read Only. |
+| binding | object | The binding object backing the port Read Only. |
+| isOpen | boolean | `true` if the port is open, `false` otherwise. Read Only. |
| path | string | The system path or name of the serial port. Read Only. |
-| isOpen | boolean | 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
-#### `serialPort.write(data, [callback])`
+#### `serialPort.write(data, [encoding], [callback])` ⇒ boolean
+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 [SerialPort](#exp_module_serialport--SerialPort)
+**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`.
| Param | Type | Description |
| --- | --- | --- |
| data | string | array | buffer | 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] | [errorCallback](#module_serialport--SerialPort..errorCallback) | Called once the write operation returns. |
+| [encoding] | string | 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] | function | Called once the write operation finishes. Data may not yet be flushed to the underlying port, no arguments. |
-
-
+
-#### `serialPort.pause()`
-Pauses an open connection (unix only)
+#### `serialPort.read([size])` ⇒ string | Buffer | null
+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 [SerialPort](#exp_module_serialport--SerialPort)
+**Returns**: string | Buffer | null - The data from internal buffers
--
+| Param | Type | Description |
+| --- | --- | --- |
+| [size] | number | size specify how many bytes of data to return if available. |
-
-
-#### `serialPort.resume()`
-Resumes a paused connection (unix only)
-
-**Kind**: instance method of [SerialPort](#exp_module_serialport--SerialPort)
-
@@ -461,7 +482,7 @@ Closes an open connection
#### `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 [SerialPort](#exp_module_serialport--SerialPort)
@@ -481,7 +502,7 @@ Sets flags on an open port. Uses [`SetCommMask`](https://msdn.microsoft.com/en-u
#### `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 [SerialPort](#exp_module_serialport--SerialPort)
@@ -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) {
-
-
+
-#### `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 [SerialPort](#exp_module_serialport--SerialPort)
+**Kind**: instance method of [SerialPort](#exp_module_serialport--SerialPort)
+**Returns**: `this`
+**See**: module:serialport#resume
+
+-
+
+
+
+#### `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 [SerialPort](#exp_module_serialport--SerialPort)
+**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
-
+
+
+#### `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 [SerialPort](#exp_module_serialport--SerialPort)
+
+-
+
#### `Event: "disconnect"`
@@ -576,6 +619,21 @@ The `close` event's callback is called with no arguments when the port is closed
-
+
+
+#### `SerialPort.Binding` : [Binding](#module_serialport--SerialPort..Binding)
+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 [SerialPort](#exp_module_serialport--SerialPort)
+
+-
+
#### `SerialPort.parsers` : object
@@ -637,10 +695,10 @@ parser.on('data', console.log);
-#### `SerialPort.list` : function
+#### `SerialPort.list(callback)` : function
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 [SerialPort](#exp_module_serialport--SerialPort)
+**Kind**: static method of [SerialPort](#exp_module_serialport--SerialPort)
| Param | Type |
| --- | --- |
@@ -672,6 +730,240 @@ SerialPort.list(function (err, ports) {
});
```
+-
+
+
+
+#### SerialPort~Binding : Class
+**Kind**: inner class of [SerialPort](#exp_module_serialport--SerialPort)
+**Properties**
+
+| Name | Type | Description |
+| --- | --- | --- |
+| isOpen | boolean | Required property. `true` if the port is open, `false` otherwise. Should be read only. |
+
+
+* [~Binding](#module_serialport--SerialPort..Binding) : Class
+ * [`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)
+
+
+-
+
+
+
+##### `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**:
+
+- TypeError When given invalid arguments a TypeError will be thrown.
+
+
+| Param | Type | Description |
+| --- | --- | --- |
+| options | object | |
+| options.disconnect | function | 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. |
+
+
+-
+
+
+
+##### `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 [Binding](#module_serialport--SerialPort..Binding)
+
+| Param | Type |
+| --- | --- |
+| callback | [listCallback](#module_serialport--SerialPort..listCallback) |
+
+
+-
+
+
+
+##### `binding.open(path, openOptions, openCallback)`
+Opens a connection to the serial port referenced by the path.
+
+**Kind**: instance method of [Binding](#module_serialport--SerialPort..Binding)
+**Throws**:
+
+- TypeError When given invalid arguments a TypeError will be thrown.
+
+
+| Param | Type | Description |
+| --- | --- | --- |
+| path | string | |
+| openOptions | [openOptions](#module_serialport--SerialPort..openOptions) | |
+| openCallback | [errorCallback](#module_serialport--SerialPort..errorCallback) | 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. |
+
+
+-
+
+
+
+##### `binding.close(callback)`
+Closes an open connection
+
+**Kind**: instance method of [Binding](#module_serialport--SerialPort..Binding)
+**Throws**:
+
+- TypeError When given invalid arguments a TypeError will be thrown.
+
+
+| Param | Type | Description |
+| --- | --- | --- |
+| callback | [errorCallback](#module_serialport--SerialPort..errorCallback) | Called once a connection is closed. |
+
+
+-
+
+
+
+##### `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 [Binding](#module_serialport--SerialPort..Binding)
+**Throws**:
+
+- TypeError When given invalid arguments a TypeError will be thrown.
+
+**Params**: integer offset - is the offset in the buffer to start writing at.
+
+| Param | Type | Description |
+| --- | --- | --- |
+| data | buffer | Accepts a [`Buffer`](http://nodejs.org/api/buffer.html) object. |
+| length | integer | specifying the maximum number of bytes to read. |
+| readCallback | [readCallback](#module_serialport--SerialPort..readCallback) | is called after a read operation |
+
+
+-
+
+
+
+##### `binding.write(data, writeCallback)`
+Write a number of bytes to the SerialPort
+
+**Kind**: instance method of [Binding](#module_serialport--SerialPort..Binding)
+**Throws**:
+
+- TypeError When given invalid arguments a TypeError will be thrown.
+
+
+| Param | Type | Description |
+| --- | --- | --- |
+| data | buffer | Accepts a [`Buffer`](http://nodejs.org/api/buffer.html) object. |
+| writeCallback | [errorCallback](#module_serialport--SerialPort..errorCallback) | 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. |
+
+
+-
+
+
+
+##### `binding.set([options], callback)`
+Set control flags on an open port.
+
+**Kind**: instance method of [Binding](#module_serialport--SerialPort..Binding)
+**Throws**:
+
+- TypeError When given invalid arguments a TypeError will be thrown.
+
+
+| Param | Type | Default | Description |
+| --- | --- | --- | --- |
+| [options] | object | | 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] | Boolean | false | |
+| [options.cts] | Boolean | false | |
+| [options.dsr] | Boolean | false | |
+| [options.dtr] | Boolean | true | |
+| [options.rts] | Boolean | true | |
+| callback | [errorCallback](#module_serialport--SerialPort..errorCallback) | | Called once the port's flags have been set. |
+
+
+-
+
+
+
+##### `binding.get([callback])`
+Get the control flags (CTS, DSR, DCD) on the open port.
+
+**Kind**: instance method of [Binding](#module_serialport--SerialPort..Binding)
+**Throws**:
+
+- TypeError When given invalid arguments a TypeError will be thrown.
+
+
+| Param | Type | Description |
+| --- | --- | --- |
+| [callback] | [modemBitsCallback](#module_serialport--SerialPort..modemBitsCallback) | Called once the flags have been retrieved. |
+
+
+-
+
+
+
+##### `binding.flush(callback)`
+Flush (discard) data received but not read and written but not transmitted.
+
+**Kind**: instance method of [Binding](#module_serialport--SerialPort..Binding)
+**Throws**:
+
+- TypeError When given invalid arguments a TypeError will be thrown.
+
+
+| Param | Type | Description |
+| --- | --- | --- |
+| callback | [errorCallback](#module_serialport--SerialPort..errorCallback) | Called once the flush operation finishes. |
+
+
+-
+
+
+
+##### `binding.drain(callback)`
+Drain waits until all output data has been transmitted to the serial port.
+
+**Kind**: instance method of [Binding](#module_serialport--SerialPort..Binding)
+**Throws**:
+
+- TypeError When given invalid arguments a TypeError will be thrown.
+
+
+| Param | Type | Description |
+| --- | --- | --- |
+| callback | [errorCallback](#module_serialport--SerialPort..errorCallback) | Called once the drain operation finishes. |
+
+
+-
+
+
+
+#### `SerialPort~readCallback` : function
+A callback called with an error or null.
+
+**Kind**: inner typedef of [SerialPort](#exp_module_serialport--SerialPort)
+**Throws**:
+
+- TypeError When given invalid arguments a TypeError will be thrown.
+
+
+| Param | Type | Description |
+| --- | --- | --- |
+| error | error | |
+| bytesRead | integer | the number of bytes that have been written into the buffer |
+| buffer | buffer | the buffer that data was written into, same object that was passed into `read`. |
+
+
-
@@ -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 | [Binding](#new_module_serialport--SerialPort..Binding_new) | | 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 | boolean | true | Automatically opens the port on `nextTick` |
| lock | boolean | true | Prevent other processes from opening the port. false is not currently supported on windows. |
| baudRate | number | 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. |
| dataBits | number | 8 | Must be one of: 8, 7, 6, or 5. |
| stopBits | number | 1 | Must be one of: 1 or 2. |
+| highWaterMark | number | 16384 | The size of the read and write buffers defaults to 16k |
| parity | string | "none" | Must be one of: 'none', 'even', 'mark', 'odd', 'space' |
| rtscts | boolean | false | flow control setting |
| xon | boolean | false | flow control setting |
| xoff | boolean | false | flow control setting |
| xany | boolean | false | flow control setting |
-| bufferSize | number | 65536 | Size of read buffer |
-| platformOptions | object | | sets platform specific options |
-| platformOptions.vmin | number | 1 | see [`man termios`](http://linux.die.net/man/3/termios) |
-| platformOptions.vtime | number | 0 | see [`man termios`](http://linux.die.net/man/3/termios) |
+| bindingOptions | object | | sets binding specific options |
+| bindingOptions.vmin | number | 1 | see [`man termios`](http://linux.die.net/man/3/termios) LinuxBinding and DarwinBinding |
+| bindingOptions.vtime | number | 0 | see [`man termios`](http://linux.die.net/man/3/termios) LinuxBinding and DarwinBinding |
-
diff --git a/binding.gyp b/binding.gyp
index d5bc26d..630068f 100644
--- a/binding.gyp
+++ b/binding.gyp
@@ -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',
],
}
],
diff --git a/lib/bindings-auto-detect.js b/lib/bindings-auto-detect.js
new file mode 100644
index 0000000..2e61e61
--- /dev/null
+++ b/lib/bindings-auto-detect.js
@@ -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.
+ */
diff --git a/lib/bindings-darwin.js b/lib/bindings-darwin.js
new file mode 100644
index 0000000..8777de7
--- /dev/null
+++ b/lib/bindings-darwin.js
@@ -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;
diff --git a/lib/bindings-linux.js b/lib/bindings-linux.js
new file mode 100644
index 0000000..7163fa2
--- /dev/null
+++ b/lib/bindings-linux.js
@@ -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;
diff --git a/lib/bindings-mock.js b/lib/bindings-mock.js
new file mode 100644
index 0000000..36339f4
--- /dev/null
+++ b/lib/bindings-mock.js
@@ -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;
diff --git a/lib/bindings-win32.js b/lib/bindings-win32.js
new file mode 100644
index 0000000..07db1b8
--- /dev/null
+++ b/lib/bindings-win32.js
@@ -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;
diff --git a/lib/bindings.js b/lib/bindings.js
deleted file mode 100644
index 64dce2c..0000000
--- a/lib/bindings.js
+++ /dev/null
@@ -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
-};
diff --git a/lib/index.js b/lib/index.js
new file mode 100644
index 0000000..52b4e16
--- /dev/null
+++ b/lib/index.js
@@ -0,0 +1,15 @@
+'use strict';
+
+/**
+ * @module serialport
+ * @copyright Chris Williams
+ */
+
+var SerialPort = require('./serialport');
+var Binding = require('./bindings-auto-detect');
+var parsers = require('./parsers');
+
+SerialPort.Binding = Binding;
+SerialPort.parsers = parsers;
+
+module.exports = SerialPort;
diff --git a/lib/push-methods.js b/lib/push-methods.js
new file mode 100644
index 0000000..313aa1f
--- /dev/null
+++ b/lib/push-methods.js
@@ -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;
diff --git a/lib/read-unix.js b/lib/read-unix.js
new file mode 100644
index 0000000..f0d8739
--- /dev/null
+++ b/lib/read-unix.js
@@ -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));
+};
diff --git a/lib/serialport.js b/lib/serialport.js
index 3436e05..a11e679 100644
--- a/lib/serialport.js
+++ b/lib/serialport.js
@@ -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;
diff --git a/package.json b/package.json
index c9fe107..c5a86d5 100644
--- a/package.json
+++ b/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
}
diff --git a/src/serialport_poller.cpp b/src/read-poller.cpp
similarity index 55%
rename from src/serialport_poller.cpp
rename to src/read-poller.cpp
index b1d2a84..b3c2e3d 100644
--- a/src/serialport_poller.cpp
+++ b/src/read-poller.cpp
@@ -1,28 +1,44 @@
// Copyright (C) 2013 Robert Giseburt
-// 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
-#include "./serialport_poller.h"
+#include "./read-poller.h"
using namespace v8;
-static Nan::Persistent serialportpoller_constructor;
+static Nan::Persistent poller_constructor;
-SerialportPoller::SerialportPoller() : Nan::ObjectWrap() {}
-SerialportPoller::~SerialportPoller() {
- // printf("~SerialportPoller\n");
- delete callback_;
+void ReadPoller::Init(Handle