UNPKG

59.3 kBMarkdownView Raw
1# Node Serialport
2
3<!-- STOP! WAIT! BEFORE YOU EDIT!
4
5README.md is a generated file. Please don't edit it!
6
7This file is generated from .docs/README.hbs and the JavaScript files themselves.
8See our contributing guide for more information.
9
10https://github.com/EmergingTechnologyAdvisors/node-serialport/blob/master/CONTRIBUTING.md#writing-docs
11
12-->
13
14[![npm](https://img.shields.io/npm/dm/serialport.svg?maxAge=2592000)](http://npmjs.com/package/serialport)
15[![Gitter chat](https://badges.gitter.im/EmergingTechnologyAdvisors/node-serialport.svg)](https://gitter.im/EmergingTechnologyAdvisors/node-serialport)
16[![Dependency Status](https://david-dm.org/EmergingTechnologyAdvisors/node-serialport.svg)](https://david-dm.org/EmergingTechnologyAdvisors/node-serialport)
17[![codecov](https://codecov.io/gh/EmergingTechnologyAdvisors/node-serialport/branch/master/graph/badge.svg)](https://codecov.io/gh/EmergingTechnologyAdvisors/node-serialport)
18[![Build Status](https://travis-ci.org/EmergingTechnologyAdvisors/node-serialport.svg?branch=master)](https://travis-ci.org/EmergingTechnologyAdvisors/node-serialport)
19[![Build status](https://ci.appveyor.com/api/projects/status/u6xe3iao2crd7akn/branch/master?svg=true)](https://ci.appveyor.com/project/j5js/node-serialport/branch/master)
20[![Greenkeeper badge](https://badges.greenkeeper.io/EmergingTechnologyAdvisors/node-serialport.svg)](https://greenkeeper.io/)
21
22## Intro to Node-Serialport
23
24Imagine a world in which you can write JavaScript to control blenders, lights, security systems, or even robots. That's right—robots! Thanks to Node Serialport, that world is here.
25
26Node-Serialport provides a stream interface for the low-level serial port code necessary to controll [Arduino](http://www.arduino.cc/) chipsets, X10 interfaces, [Zigbee](http://www.zigbee.org/) radios, highway signs, lcd screens, cash drawers, motor controllers, sensor packages, fork lifts, modems, drones, CNC machines, plotters, vending machines, ccTalk coin accecptors, SMS Gateways, RFID scanners and much more. If if you have a hardware device with an [UART](https://en.wikipedia.org/wiki/Universal_asynchronous_receiver/transmitter) we can speak to it. The physical world is your oyster with this goodie.
27
28For a full breakdown of why we made Node-Serialport, please read [NodeBots - The Rise of JS Robotics](http://www.voodootikigod.com/nodebots-the-rise-of-js-robotics). It explains why one would want to program robots in JS in the first place.
29
30We're not against firmware but we're better than it.
31
32## Quick Answers to Important Questions
33- **For support**, open a [GitHub issue](https://github.com/EmergingTechnologyAdvisors/node-serialport/issues/new).
34- **For discussions, design ideas, and clarifications**, please join our [Gitter chat room](https://gitter.im/EmergingTechnologyAdvisors/node-serialport).
35- **To test Node-Serialport**, we recommend two related projects—[Browser Serialport](https://github.com/garrows/browser-serialport) ("just like Node Serialport, but for browser apps") and [Serialport Test Piliot](https://github.com/j5js/serialport-test-pilot).
36- **To contribute**, please review our [contribution guide](CONTRIBUTING.md) and [Code of Conduct](CODE_OF_CONDUCT.md). You might want to check out our [roadmap](https://github.com/EmergingTechnologyAdvisors/node-serialport/issues/746). We also have issues tagged ["good first PR"](https://github.com/EmergingTechnologyAdvisors/node-serialport/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+pr%22), if you'd like to start somewhere specific. We'll do our best to support you until we merge your PR.
37
38***
39
40## For which version of Node-Serialport would you like documentation?
41
42You're reading the README for Node-Serialport's master branch. You probably want to see the README for our most recent release. See our [changelog](CHANGELOG.md) for what's new, and our [upgrade guide](UPGRADE_GUIDE.md) for a walk-through on differences between major versions.
43
44- [`serialport@6.0.0` docs](https://github.com/EmergingTechnologyAdvisors/node-serialport/blob/v6.0.0/README.md) the latest `6.x` release.
45- [`serialport@4.0.7` docs](https://github.com/EmergingTechnologyAdvisors/node-serialport/blob/4.0.7/README.md) the latest `4.x` release.
46
47Older versions are no longer supported but their docs can be found by looking through release tags.
48
49***
50## Helpful Resources for Getting Started with Node-Serialport
51
52In addition to reading the [article mentioned above](http://www.voodootikigod.com/nodebots-the-rise-of-js-robotics), these others might help you:
53* [Johnny-Five](http://johnny-five.io/#hello-world): The Johnny-Five Robotics and IoT platform's six-line "Hello World" (awesome).
54* [Arduino Node Security Sensor Hacking](http://nexxylove.tumblr.com/post/20159263403/arduino-node-security-sensor-hacking): A great all-around "how do I use this" article.
55
56***
57## Table of Contents
58
59* [Platform Support](#platform-support)
60* [Installation](#installation-instructions)
61* [Installation Special Cases](#installation-special-cases)
62 * [Alpine Linux](#alpine-linux)
63 * [Electron](#electron)
64 * [Illegal Instruction](#illegal-instruction)
65 * [Mac OS X](#mac-os-x)
66 * [Raspberry Pi Linux](#raspberry-pi-linux)
67 * [sudo / root](#sudo--root)
68 * [Ubuntu/Debian Linux](#ubuntudebian-linux)
69 * [Windows](#windows)
70* [Usage](#usage)
71 * [Opening a Port](#opening-a-port)
72 * [Testing](#testing)
73 * [Debugging](#debugging)
74 * [Error Handling](#error-handling)
75* [SerialPort](#exp_module_serialport--SerialPort) ⏏
76 * [`new SerialPort(path, [options], [openCallback])`](#new_module_serialport--SerialPort_new)
77 * _instance_
78 * [`.open([callback])`](#module_serialport--SerialPort+open)
79 * [`.update([options], [callback])`](#module_serialport--SerialPort+update)
80 * [`.write(data, [encoding], [callback])`](#module_serialport--SerialPort+write) ⇒ <code>boolean</code>
81 * [`.read([size])`](#module_serialport--SerialPort+read) ⇒ <code>string</code> &#124; <code>Buffer</code> &#124; <code>null</code>
82 * [`.close(callback)`](#module_serialport--SerialPort+close)
83 * [`.set([options], [callback])`](#module_serialport--SerialPort+set)
84 * [`.get([callback])`](#module_serialport--SerialPort+get)
85 * [`.flush([callback])`](#module_serialport--SerialPort+flush)
86 * [`.drain([callback])`](#module_serialport--SerialPort+drain)
87 * [`.pause()`](#module_serialport--SerialPort+pause) ⇒
88 * [`.resume()`](#module_serialport--SerialPort+resume) ⇒
89 * [`Event: "error"`](#module_serialport--SerialPort+event_error)
90 * [`Event: "open"`](#module_serialport--SerialPort+event_open)
91 * [`Event: "data"`](#module_serialport--SerialPort+event_data)
92 * [`Event: "close"`](#module_serialport--SerialPort+event_close)
93 * _static_
94 * [`.Binding`](#module_serialport--SerialPort.Binding) : [<code>BaseBinding</code>](#module_serialport--SerialPort..BaseBinding)
95 * [`.parsers`](#module_serialport--SerialPort.parsers) : <code>object</code>
96 * [`.list([callback])`](#module_serialport--SerialPort.list) ⇒ <code>Promise</code>
97 * _inner_
98 * [~BaseBinding](#module_serialport--SerialPort..BaseBinding)
99 * [`new BaseBinding(options)`](#new_module_serialport--SerialPort..BaseBinding_new)
100 * _instance_
101 * [`.open(path, openOptions)`](#module_serialport--SerialPort..BaseBinding+open) ⇒ <code>Promise</code>
102 * [`.close()`](#module_serialport--SerialPort..BaseBinding+close) ⇒ <code>Promise</code>
103 * [`.read(data, offset, length)`](#module_serialport--SerialPort..BaseBinding+read) ⇒ <code>Promise</code>
104 * [`.write(data)`](#module_serialport--SerialPort..BaseBinding+write) ⇒ <code>Promise</code>
105 * [`.update([options])`](#module_serialport--SerialPort..BaseBinding+update) ⇒ <code>Promise</code>
106 * [`.set([options])`](#module_serialport--SerialPort..BaseBinding+set) ⇒ <code>Promise</code>
107 * [`.get()`](#module_serialport--SerialPort..BaseBinding+get) ⇒ <code>Promise</code>
108 * [`.flush()`](#module_serialport--SerialPort..BaseBinding+flush) ⇒ <code>Promise</code>
109 * [`.drain()`](#module_serialport--SerialPort..BaseBinding+drain) ⇒ <code>Promise</code>
110 * _static_
111 * [`.list()`](#module_serialport--SerialPort..BaseBinding.list) ⇒ <code>Promise</code>
112 * [`~errorCallback`](#module_serialport--SerialPort..errorCallback) : <code>function</code>
113 * [`~modemBitsCallback`](#module_serialport--SerialPort..modemBitsCallback) : <code>function</code>
114 * [`~openOptions`](#module_serialport--SerialPort..openOptions) : <code>Object</code>
115 * [`~listCallback`](#module_serialport--SerialPort..listCallback) : <code>function</code>
116* [Command Line Tools](#command-line-tools)
117 * [Serial Port List](#serial-port-list)
118 * [Serial Port Terminal](#serial-port-terminal)
119 * [Serial Port Repl](#serial-port-repl)
120* [License](#license)
121
122***
123
124### Platform Support
125`serialport` supports NodeJS v4 and upwards. For versions 0.10 and 0.12, use `serialport@4`. The platforms, architectures and Node versions that `serialport` supports are the following;
126
127| Platform / Arch | Node v4.x | Node v6.x | Node v8.x |
128| --- | --- | --- | --- |
129| Linux / ia32 | ☑ | ☑ | ☑ |
130| Linux / x64 | ☑ | ☑ | ☑ |
131| Linux / ARM v6¹ | ☐ | ☐ | ☐ |
132| Linux / ARM v7¹ | ☐ | ☐ | ☐ |
133| Linux / ARM v8¹ | ☐ | ☐ | ☐ |
134| Linux / MIPSel¹ | ☐ | ☐ | ☐ |
135| Linux / PPC64¹ | ☐ | ☐ | ☐ |
136| Windows² / x86 | ☐ | ☑ | ☑ |
137| Windows² / x64 | ☑ | ☑ | ☑ |
138| OSX³ / x64 | ☑ | ☑ | ☑ |
139
140¹ ARM, MIPSel and PPC64¹ platforms are not currently part of our testing or build matrix, but are known to work.
141
142² Windows 7, 8, 10, and 10 IoT are supported, but our CI tests only Windows Server 2012 R2.
143
144³ OSX 10.4 Tiger and above are supported, but our CI tests only 10.9.5 Mavericks with Xcode 6.1.
145
146## Installation Instructions
147
148For most "standard" use cases (Node v4.x on Mac, Linux, or Windows on a x86 or x64 processor), Node-Serialport will install nice and easy with:
149
150```
151npm install serialport
152```
153
154### Installation Special Cases
155
156We use [prebuild](https://github.com/mafintosh/prebuild) to compile and post binaries of the library for most common use cases (Linux, Mac, Windows on standard processor platforms). If you have a special case, Node-Serialport will work, but it will compile the binary during the install. Compiling with nodejs is done via `node-gyp` which requires Python 2.x, so please ensure you have it installed and in your path for all operating systems. Python 3.x will not work.
157
158This assumes you have everything on your system necessary to compile ANY native module for Node.js. If you don't, then please ensure the following are true for your system before filing a "Does not install" issue.
159
160#### Alpine Linux
161
162[Alpine](http://www.alpinelinux.org/) is a (very) small distro, but it uses the [musl](https://www.musl-libc.org/) standard library instead of [glibc](https://www.gnu.org/software/libc/) (used by most other Linux distros) so it requires compilation. It's commonly used with Docker. A user has confirmed that Node-Serialport works with [alpine-node](https://github.com/mhart/alpine-node).
163
164```
165# If you don't have node/npm already, add that first
166sudo apk add --no-cache nodejs
167
168# Add the necessary build and runtime dependencies
169sudo apk add --no-cache make gcc g++ python linux-headers udev
170
171# Then we can install serialport, forcing it to compile
172npm install serialport --build-from-source
173
174# If you're installing as root, you'll also need to use the --unsafe-perm flag
175```
176
177#### Electron
178
179[Electron](https://electron.atom.io/) is a framework for creating cross-platform desktop applications. It comes with its own version of the Node.js runtime.
180
181If you require `serialport` as a dependency for an Electron project, you must compile it for the version of Electron your project's using.
182
183When you first install `serialport` it will compile against the version of Node.js on your machine, not against the Node.js runtime bundled with Electron.
184
185To recompile `serialport` (or any native Node.js module) for Electron, you can use `electron-rebuild`; more info at Electron's [README](https://github.com/electron/electron-rebuild/blob/master/README.md).
186
1871. `npm install --save-dev electron-rebuild`
1882. Add `electron-rebuild` to your project's package.json's install hook
1893. Run `npm install`
190
191For an example project, check out [`electron-serialport`](https://github.com/johnny-five-io/electron-serialport).
192
193#### Illegal Instruction
194
195The pre-compiled binaries assume a fully capable chip. Intel's [Galileo 2](https://software.intel.com/en-us/iot/hardware/galileo), for example, lacks a few instruction sets from the `ia32` architecture. A few other platforms have similar issues. If you get `Illegal Instruction` when trying to run Node-Serialport, you'll need to ask npm to rebuild the Serialport binary.
196
197```bash
198# Will ask npm to build serialport during install time
199npm install serialport --build-from-source
200
201# If you have a package that depends on serialport, you can ask npm to rebuild it specifically...
202npm rebuild serialport --build-from-source
203```
204
205#### Mac OS X
206
207Ensure that you have at a minimum the xCode Command Line Tools installed appropriate for your system configuration. If you recently upgraded the OS, it probably removed your installation of Command Line Tools, please verify before submitting a ticket. To compile `node-serialport` with Node.js 4.x+, you will need to use g++ v4.8 or higher.
208
209#### Raspberry Pi Linux
210
211Follow the instructions for [setting up a Raspberry pi for use with Johnny-Five and Raspi IO](https://github.com/nebrius/raspi-io/wiki/Getting-a-Raspberry-Pi-ready-for-NodeBots). These projects use Node Serialport under the hood.
212
213| Revision | CPU | Arm Version |
214| ---- | --- | --- |
215| A, A+, B, B+ | 32-bit ARM1176JZF-S | ARMv6 |
216| Compute Module | 32-bit ARM1176JZF-S | ARMv6 |
217| Zero | 32-bit ARM1176JZF-S | ARMv6 |
218| B2 | 32-bit ARM Cortex-A7 | ARMv7 |
219| B3 | 32-bit ARM Cortex-A53 | ARMv8 |
220
221#### sudo / root
222If you're going to use `sudo` or root to install Node-Serialport, `npm` will require you to use the unsafe parameters flag.
223
224```bash
225sudo npm install serialport --unsafe-perm --build-from-source
226```
227
228Failure to use the flag results in an error like this:
229
230```bash
231root@rpi3:~# npm install -g serialport
232/usr/bin/serialport-list -> /usr/lib/node_modules/serialport/bin/serialport-list.js
233/usr/bin/serialport-term -> /usr/lib/node_modules/serialport/bin/serialport-terminal.js
234
235
236> serialport@6.0.0-beta1 install /Users/wizard/src/node-serialport
237> prebuild-install || node-gyp rebuild
238
239prebuild-install info begin Prebuild-install version 2.2.1
240prebuild-install info install installing standalone, skipping download.
241
242gyp WARN EACCES user "root" does not have permission to access the dev dir "/root/.node-gyp/6.9.1"
243gyp WARN EACCES attempting to reinstall using temporary dev dir "/usr/lib/node_modules/serialport/.node-gyp"
244make: Entering directory '/usr/lib/node_modules/serialport/build'
245make: *** No rule to make target '../.node-gyp/6.9.1/include/node/common.gypi', needed by 'Makefile'. Stop.
246make: Leaving directory '/usr/lib/node_modules/serialport/build'
247gyp ERR! build error
248gyp ERR! stack Error: `make` failed with exit code: 2
249
250```
251
252#### Ubuntu/Debian Linux
253
254The best way to install any version of Node.js is to use the [NodeSource Node.js binary distributions](https://github.com/nodesource/distributions#installation-instructions). Older versions of Ubuntu install Node.js with the wrong version and binary name. If your Node binary is `nodejs` instead of `node`, or if your Node version is [`v0.10.29`](https://github.com/fivdi/onoff/wiki/Node.js-v0.10.29-and-native-addons-on-the-Raspberry-Pi), then you should follow these instructions.
255
256You'll need the package `build-essential` to compile `serialport`. If there's a binary for your platform, you won't need it. Keep rocking!
257
258```
259# Using Ubuntu and Node 6
260curl -sL https://deb.nodesource.com/setup_7.x | sudo -E bash -
261sudo apt-get install -y nodejs
262
263# Using Debian and Node 6 as root
264curl -sL https://deb.nodesource.com/setup_7.x | bash -
265apt-get install -y nodejs
266```
267
268#### Windows
269Node-Serialport supports Windows 7, 8.1, 10, and 10 IoT. Precompiled binaries are available, but if you want to build it from source you'll need to follow the [node-gyp installation](https://github.com/nodejs/node-gyp#installation) instructions. Once you've got things working, you can install Node-Serialport from source with:
270
271```powershell
272npm install serialport --build-from-source
273```
274
275Node-gyp's documentation doesn't mention it, but it sometimes helps to create a C++ project in [Visual Studio](https://www.visualstudio.com/) so that it will install any necessary components not already installed during the past two hours of setup. This will solve some instances of `Failed to locate: "CL.exe"`.
276
277An old issue that you may still run into. When working with multiple Serial Ports you can set the `UV_THREADPOOL_SIZE` environment variable to be set to 1 + the number of ports you wish to open at a time. (Defaults to `4` which supports 3 open ports).
278
279## Usage
280
281### Opening a Port
282
283```js
284var SerialPort = require('serialport');
285var port = new SerialPort('/dev/tty-usbserial1', {
286 baudRate: 57600
287});
288```
289
290When opening a serial port, specify (in this order)
291
2921. Path to Serial Port - required.
2931. Options - optional and described below.
294
295Constructing a `SerialPort` object immediately opens a port. While you can read and write at any time (it will be queued until the port is open), most port functions require an open port. There are three ways to detect when a port is opened.
296
297- The `open` event is always emitted when the port is opened.
298- The constructor's openCallback is passed to `.open()`, if you haven't disabled the `autoOpen` option. If you have disabled it, the callback is ignored.
299- The `.open()` function takes a callback that is called after the port is opened. You can use this if you've disabled the `autoOpen` option or have previously closed an open port.
300
301```js
302var SerialPort = require('serialport');
303var port = new SerialPort('/dev/tty-usbserial1');
304
305port.write('main screen turn on', function(err) {
306 if (err) {
307 return console.log('Error on write: ', err.message);
308 }
309 console.log('message written');
310});
311
312// Open errors will be emitted as an error event
313port.on('error', function(err) {
314 console.log('Error: ', err.message);
315})
316```
317
318Detecting open errors can be moved to the constructor's callback.
319```js
320var SerialPort = require('serialport');
321var port = new SerialPort('/dev/tty-usbserial1', function (err) {
322 if (err) {
323 return console.log('Error: ', err.message);
324 }
325});
326
327port.write('main screen turn on', function(err) {
328 if (err) {
329 return console.log('Error on write: ', err.message);
330 }
331 console.log('message written');
332});
333
334```
335
336When disabling the `autoOpen` option you'll need to open the port on your own.
337
338```js
339var SerialPort = require('serialport');
340var port = new SerialPort('/dev/tty-usbserial1', { autoOpen: false });
341
342port.open(function (err) {
343 if (err) {
344 return console.log('Error opening port: ', err.message);
345 }
346
347 // Because there's no callback to write, write errors will be emitted on the port:
348 port.write('main screen turn on');
349});
350
351// The open event is always emitted
352port.on('open', function() {
353 // open logic
354});
355```
356
357Get updates of new data from the serial port as follows:
358
359```js
360// Switches the port into "flowing mode"
361port.on('data', function (data) {
362 console.log('Data:', data);
363});
364
365// Read data that is available but keep the stream from entering "flowing mode"
366port.on('readable', function () {
367 console.log('Data:', port.read());
368});
369```
370
371You can write to the serial port by sending a string or buffer to the write method:
372
373```js
374port.write('Hi Mom!');
375port.write(Buffer.from('Hi Mom!'));
376```
377
378Enjoy and do cool things with this code.
379
380### Testing
381
382Testing is an important feature of any library. To aid in our own tests we've developed a `MockBinding` a fake hardware binding that doesn't actually need any hardware to run. This class passes all of the same tests as our hardware based bindings and provides a few additional test related interfaces. To use the mock binding check out the example [here](/examples/mocking.js).
383
384```js
385const SerialPort = require('serialport/test');
386const MockBinding = SerialPort.Binding;
387
388// Create a port and enable the echo and recording.
389MockBinding.createPort('/dev/ROBOT', { echo: true, record: true })
390const port = new SerialPort('/dev/ROBOT')
391```
392
393### Debugging
394
395We use the [debug](https://www.npmjs.com/package/debug) package and log under the `serialport` namespace:
396
397 - `serialport:main` for all high-level/main logging
398 - `serialport:binding` for all low-level logging
399
400You can enable logging through environment variables. Check the [debug](https://www.npmjs.com/package/debug) docs for info.
401
402```bash
403DEBUG=serialport:main node myapp.js
404DEBUG=serialport:* node myapp.js
405DEBUG=* node myapp.js
406```
407
408You can enable core dumps on osx with;
409```bash
410ulimit -c unlimited for core dumps
411```
412
413You can "console.log" from c++ with;
414```c++
415fprintf(stdout, "Hellow World num=%d str=%s\n", 4, "hi");
416```
417
418You can make use of the `serialport-repl` command with;
419```bash
420serialport-repl # to auto detect an arduino
421serialport-repl /path/name # to connect to a specific port
422```
423
424It will load a serialport object with debugging turned on.
425
426### Error Handling
427
428All functions in Node-Serialport follow two conventions:
429
430- Argument errors throw a `TypeError` object. You'll see these when functions are called with invalid arguments.
431- Runtime errors provide `Error` objects to the function's callback or emit an [`error event`](#module_serialport--SerialPort+event_error) if no callback is provided. You'll see these when a runtime error occurs, like trying to open a bad port or setting an unsupported baud rate.
432
433You should never have to wrap a Node-Serialport object in a try/catch statement if you call the functions with the correct arguments.
434
435<a name="exp_module_serialport--SerialPort"></a>
436
437### SerialPort ⏏
438**Kind**: Exported class
439**Emits**: [<code>open</code>](#module_serialport--SerialPort+event_open), [<code>data</code>](#module_serialport--SerialPort+event_data), [<code>close</code>](#module_serialport--SerialPort+event_close), [<code>error</code>](#module_serialport--SerialPort+event_error)
440**Properties**
441
442| Name | Type | Description |
443| --- | --- | --- |
444| baudRate | <code>number</code> | The port's baudRate. Use `.update` to change it. Read-only. |
445| binding | <code>object</code> | The binding object backing the port. Read-only. |
446| isOpen | <code>boolean</code> | `true` if the port is open, `false` otherwise. Read-only. (`since 5.0.0`) |
447| path | <code>string</code> | The system path or name of the serial port. Read-only. |
448
449
450* * *
451
452<a name="new_module_serialport--SerialPort_new"></a>
453
454#### `new SerialPort(path, [options], [openCallback])`
455Create 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. You can disable this by setting the option `autoOpen` to `false`.
456
457**Throws**:
458
459- <code>TypeError</code> When given invalid arguments, a `TypeError` will be thrown.
460
461
462| Param | Type | Description |
463| --- | --- | --- |
464| path | <code>string</code> | The system path of the serial port you want to open. For example, `/dev/tty.XXX` on Mac/Linux, or `COM1` on Windows. |
465| [options] | [<code>openOptions</code>](#module_serialport--SerialPort..openOptions) | Port configuration options |
466| [openCallback] | [<code>errorCallback</code>](#module_serialport--SerialPort..errorCallback) | Called after a connection is opened. If this is not provided and an error occurs, it will be emitted on the port's `error` event. The callback will NOT be called if `autoOpen` is set to `false` in the `openOptions` as the open will not be performed. |
467
468
469* * *
470
471<a name="module_serialport--SerialPort+open"></a>
472
473#### `serialPort.open([callback])`
474Opens a connection to the given serial port.
475
476**Kind**: instance method of [<code>SerialPort</code>](#exp_module_serialport--SerialPort)
477**Emits**: [<code>open</code>](#module_serialport--SerialPort+event_open)
478
479| Param | Type | Description |
480| --- | --- | --- |
481| [callback] | [<code>errorCallback</code>](#module_serialport--SerialPort..errorCallback) | Called after a connection is opened. If this is not provided and an error occurs, it will be emitted on the port's `error` event. |
482
483
484* * *
485
486<a name="module_serialport--SerialPort+update"></a>
487
488#### `serialPort.update([options], [callback])`
489Changes the baud rate for an open port. Throws if you provide a bad argument. Emits an error or calls the callback if the baud rate isn't supported.
490
491**Kind**: instance method of [<code>SerialPort</code>](#exp_module_serialport--SerialPort)
492
493| Param | Type | Description |
494| --- | --- | --- |
495| [options] | <code>object</code> | Only supports `baudRate`. |
496| [options.baudRate] | <code>number</code> | The baud rate of the port to be opened. This should match one of the commonly available baud rates, such as 110, 300, 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, or 115200. Custom rates are supported best effort per platform. The device connected to the serial port is not guaranteed to support the requested baud rate, even if the port itself supports that baud rate. |
497| [callback] | [<code>errorCallback</code>](#module_serialport--SerialPort..errorCallback) | Called once the port's baud rate changes. If `.update` is called without a callback, and there is an error, an error event is emitted. |
498
499
500* * *
501
502<a name="module_serialport--SerialPort+write"></a>
503
504#### `serialPort.write(data, [encoding], [callback])` ⇒ <code>boolean</code>
505Writes data to the given serial port. Buffers written data if the port is not open.
506
507The write operation is non-blocking. When it returns, data might still not have been written to the serial port. See `drain()`.
508
509Some devices, like the Arduino, reset when you open a connection to them. In such cases, immediately writing to the device will cause lost data as 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.
510
511If a port is disconnected during a write, the write will error in addition to the `close` event.
512
513From the [stream docs](https://nodejs.org/api/stream.html#stream_writable_write_chunk_encoding_callback) write errors don't always provide the error in the callback, sometimes they use the error event.
514> If an error occurs, the callback may or may not be called with the error as its first argument. To reliably detect write errors, add a listener for the 'error' event.
515
516In addition to the usual `stream.write` arguments (`String` and `Buffer`), `write()` can accept arrays of bytes (positive numbers under 256) which is passed to `Buffer.from([])` for conversion. This extra functionality is pretty sweet.
517
518**Kind**: instance method of [<code>SerialPort</code>](#exp_module_serialport--SerialPort)
519**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`.
520**Since**: 5.0.0
521
522| Param | Type | Description |
523| --- | --- | --- |
524| 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 (e.g. an array of bytes or a string). |
525| [encoding] | <code>string</code> | The encoding, if chunk is a string. Defaults to `'utf8'`. Also accepts `'ascii'`, `'base64'`, `'binary'`, and `'hex'` See [Buffers and Character Encodings](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings) for all available options. |
526| [callback] | <code>function</code> | Called once the write operation finishes. Data may not yet be flushed to the underlying port. No arguments. |
527
528
529* * *
530
531<a name="module_serialport--SerialPort+read"></a>
532
533#### `serialPort.read([size])` ⇒ <code>string</code> &#124; <code>Buffer</code> &#124; <code>null</code>
534Request a number of bytes from the SerialPort. The `read()` method pulls some data out of the internal buffer and returns it. If no data is available to be read, null is returned. By default, the data is returned as a `Buffer` object unless an encoding has been specified using the `.setEncoding()` method.
535
536**Kind**: instance method of [<code>SerialPort</code>](#exp_module_serialport--SerialPort)
537**Returns**: <code>string</code> \| <code>Buffer</code> \| <code>null</code> - The data from internal buffers
538**Since**: 5.0.0
539
540| Param | Type | Description |
541| --- | --- | --- |
542| [size] | <code>number</code> | Specify how many bytes of data to return, if available |
543
544
545* * *
546
547<a name="module_serialport--SerialPort+close"></a>
548
549#### `serialPort.close(callback)`
550Closes an open connection.
551
552If there are in progress writes when the port is closed the writes will error.
553
554**Kind**: instance method of [<code>SerialPort</code>](#exp_module_serialport--SerialPort)
555**Emits**: [<code>close</code>](#module_serialport--SerialPort+event_close)
556
557| Param | Type | Description |
558| --- | --- | --- |
559| callback | <code>errorCallback</code> | Called once a connection is closed. |
560
561
562* * *
563
564<a name="module_serialport--SerialPort+set"></a>
565
566#### `serialPort.set([options], [callback])`
567Set 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 OS X and Linux.
568
569**Kind**: instance method of [<code>SerialPort</code>](#exp_module_serialport--SerialPort)
570**Since**: 5.0.0
571
572| Param | Type | Default | Description |
573| --- | --- | --- | --- |
574| [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. If options isn't provided default options is used. |
575| [options.brk] | <code>Boolean</code> | <code>false</code> | |
576| [options.cts] | <code>Boolean</code> | <code>false</code> | |
577| [options.dsr] | <code>Boolean</code> | <code>false</code> | |
578| [options.dtr] | <code>Boolean</code> | <code>true</code> | |
579| [options.rts] | <code>Boolean</code> | <code>true</code> | |
580| [callback] | [<code>errorCallback</code>](#module_serialport--SerialPort..errorCallback) | | Called once the port's flags have been set. |
581
582
583* * *
584
585<a name="module_serialport--SerialPort+get"></a>
586
587#### `serialPort.get([callback])`
588Returns the control flags (CTS, DSR, DCD) on the open port.
589Uses [`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.
590
591**Kind**: instance method of [<code>SerialPort</code>](#exp_module_serialport--SerialPort)
592
593| Param | Type | Description |
594| --- | --- | --- |
595| [callback] | [<code>modemBitsCallback</code>](#module_serialport--SerialPort..modemBitsCallback) | Called once the modem bits are retrieved. |
596
597
598* * *
599
600<a name="module_serialport--SerialPort+flush"></a>
601
602#### `serialPort.flush([callback])`
603Flush discards data received but not read, and written but not transmitted by the operating system. For more technical details, see [`tcflush(fd, TCIOFLUSH)`](http://linux.die.net/man/3/tcflush) for Mac/Linux and [`FlushFileBuffers`](http://msdn.microsoft.com/en-us/library/windows/desktop/aa364439) for Windows.
604
605**Kind**: instance method of [<code>SerialPort</code>](#exp_module_serialport--SerialPort)
606
607| Param | Type | Description |
608| --- | --- | --- |
609| [callback] | [<code>errorCallback</code>](#module_serialport--SerialPort..errorCallback) | Called once the flush operation finishes. |
610
611
612* * *
613
614<a name="module_serialport--SerialPort+drain"></a>
615
616#### `serialPort.drain([callback])`
617Waits until all output data is transmitted to the serial port. After any pending write has completed it calls [`tcdrain()`](http://linux.die.net/man/3/tcdrain) or [FlushFileBuffers()](https://msdn.microsoft.com/en-us/library/windows/desktop/aa364439(v=vs.85).aspx) to ensure it has been written to the device.
618
619**Kind**: instance method of [<code>SerialPort</code>](#exp_module_serialport--SerialPort)
620
621| Param | Type | Description |
622| --- | --- | --- |
623| [callback] | [<code>errorCallback</code>](#module_serialport--SerialPort..errorCallback) | Called once the drain operation returns. |
624
625**Example**
626Write the `data` and wait until it has finished transmitting to the target serial port before calling the callback. This will queue until the port is open and writes are finished.
627
628```js
629function writeAndDrain (data, callback) {
630 port.write(data);
631 port.drain(callback);
632}
633```
634
635* * *
636
637<a name="module_serialport--SerialPort+pause"></a>
638
639#### `serialPort.pause()` ⇒
640The `pause()` method causes a stream in flowing mode to stop emitting 'data' events, switching out of flowing mode. Any data that becomes available remains in the internal buffer.
641
642**Kind**: instance method of [<code>SerialPort</code>](#exp_module_serialport--SerialPort)
643**Returns**: `this`
644**See**: module:serialport#resume
645**Since**: 5.0.0
646
647* * *
648
649<a name="module_serialport--SerialPort+resume"></a>
650
651#### `serialPort.resume()` ⇒
652The `resume()` method causes an explicitly paused, `Readable` stream to resume emitting 'data' events, switching the stream into flowing mode.
653
654**Kind**: instance method of [<code>SerialPort</code>](#exp_module_serialport--SerialPort)
655**Returns**: `this`
656**See**: module:serialport#pause
657**Since**: 5.0.0
658
659* * *
660
661<a name="module_serialport--SerialPort+event_error"></a>
662
663#### `Event: "error"`
664The `error` event's callback is called with an error object whenever there is an error.
665
666**Kind**: event emitted by [<code>SerialPort</code>](#exp_module_serialport--SerialPort)
667
668* * *
669
670<a name="module_serialport--SerialPort+event_open"></a>
671
672#### `Event: "open"`
673The `open` event's callback is called with no arguments when the port is opened and ready for writing. This happens if you have the constructor open immediately (which opens in the next tick) or if you open the port manually with `open()`. See [Useage/Opening a Port](#opening-a-port) for more information.
674
675**Kind**: event emitted by [<code>SerialPort</code>](#exp_module_serialport--SerialPort)
676
677* * *
678
679<a name="module_serialport--SerialPort+event_data"></a>
680
681#### `Event: "data"`
682The `data` event puts the port in flowing mode. Data is emitted as soon as it's received. Data is 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 [Node.js stream documentation](https://nodejs.org/api/stream.html#stream_event_data) for more information on the data event.
683
684**Kind**: event emitted by [<code>SerialPort</code>](#exp_module_serialport--SerialPort)
685
686* * *
687
688<a name="module_serialport--SerialPort+event_close"></a>
689
690#### `Event: "close"`
691The `close` event's callback is called with no arguments when the port is closed. In the case of a disconnect it will be called with a Disconnect Error object (`err.disconnected == true`). In the event of a close error (unlikely), an error event is triggered.
692
693**Kind**: event emitted by [<code>SerialPort</code>](#exp_module_serialport--SerialPort)
694
695* * *
696
697<a name="module_serialport--SerialPort.Binding"></a>
698
699#### `SerialPort.Binding` : [<code>BaseBinding</code>](#module_serialport--SerialPort..BaseBinding)
700The `Binding` is how Node-SerialPort talks to the underlying system. By default, we auto detect Windows, Linux and OS X, and load the appropriate module for your system. You can assign `SerialPort.Binding` to any binding you like. Find more by searching at [npm](https://npmjs.org/).
701 Prevent auto loading the default bindings by requiring SerialPort with:
702 ```js
703 var SerialPort = require('serialport/lib/serialport');
704 SerialPort.Binding = MyBindingClass;
705 ```
706
707**Kind**: static property of [<code>SerialPort</code>](#exp_module_serialport--SerialPort)
708**Since**: 5.0.0
709
710* * *
711
712<a name="module_serialport--SerialPort.parsers"></a>
713
714#### `SerialPort.parsers` : <code>object</code>
715The default `Parsers` are [Transform streams](https://nodejs.org/api/stream.html#stream_class_stream_transform) that parse data in different ways to transform incoming data.
716
717 To use the parsers, you must create them and then pipe the Serialport to the parser. Be careful to only write to the SerialPort object and not the parser.
718
719**Kind**: static property of [<code>SerialPort</code>](#exp_module_serialport--SerialPort)
720**Since**: 5.0.0
721**Properties**
722
723| Name | Type | Description |
724| --- | --- | --- |
725| ByteLength | <code>Class</code> | is a transform stream that emits data as a buffer after a specific number of bytes are received. |
726| Delimiter | <code>Class</code> | is a transform stream that emits data each time a byte sequence is received. |
727| Readline | <code>Class</code> | is a transform stream that emits data after a newline delimiter is received. |
728| Ready | <code>Class</code> | is a transform stream that waits for a sequence of "ready" bytes before emitting a ready event and emitting data events |
729| Regex | <code>Class</code> | is a transform stream that uses a regular expression to split the incoming text upon. |
730
731**Example**
732```js
733const SerialPort = require('serialport');
734const Readline = SerialPort.parsers.Readline;
735const port = new SerialPort('/dev/tty-usbserial1');
736const parser = new Readline();
737port.pipe(parser);
738parser.on('data', console.log);
739port.write('ROBOT PLEASE RESPOND\n');
740
741// Creating the parser and piping can be shortened to
742// const parser = port.pipe(new Readline());
743```
744
745To use the `ByteLength` parser, provide the length of the number of bytes:
746```js
747const SerialPort = require('serialport');
748const ByteLength = SerialPort.parsers.ByteLength
749const port = new SerialPort('/dev/tty-usbserial1');
750const parser = port.pipe(new ByteLength({length: 8}));
751parser.on('data', console.log);
752```
753
754To use the `Delimiter` parser, provide a delimiter as a string, buffer, or array of bytes:
755```js
756const SerialPort = require('serialport');
757const Delimiter = SerialPort.parsers.Delimiter;
758const port = new SerialPort('/dev/tty-usbserial1');
759const parser = port.pipe(new Delimiter({ delimiter: Buffer.from('EOL') }));
760parser.on('data', console.log);
761```
762
763To use the `Readline` parser, provide a delimiter (defaults to '\n'). Data is emitted as string controllable by the `encoding` option (defaults to `utf8`).
764```js
765const SerialPort = require('serialport');
766const Readline = SerialPort.parsers.Readline;
767const port = new SerialPort('/dev/tty-usbserial1');
768const parser = port.pipe(new Readline({ delimiter: '\r\n' }));
769parser.on('data', console.log);
770```
771
772To use the `Ready` parser provide a byte start sequence. After the bytes have been received a ready event is fired and data events are passed through.
773```js
774const SerialPort = require('serialport');
775const Ready = SerialPort.parsers.Ready;
776const port = new SerialPort('/dev/tty-usbserial1');
777const parser = port.pipe(new Ready({ data: 'READY' }));
778parser.on('ready', () => console.log('the ready byte sequence has been received'))
779parser.on('data', console.log); // all data after READY is received
780```
781
782To use the `Regex` parser provide a regular expression to split the incoming text upon. Data is emitted as string controllable by the `encoding` option (defaults to `utf8`).
783```js
784const SerialPort = require('serialport');
785const Regex = SerialPort.parsers.Regex;
786const port = new SerialPort('/dev/tty-usbserial1');
787const parser = port.pipe(new Regex({ regex: /[\r\n]+/ }));
788parser.on('data', console.log);
789```
790
791To use the `CCTalk` parser you need to provide nothing. CCTalk Messages get emitted as buffer.
792```js
793const SerialPort = require('serialport');
794const CCTalk = SerialPort.parsers.CCTalk;
795const port = new SerialPort('/dev/ttyUSB0');
796const parser = port.pipe(new CCtalk());
797parser.on('data', console.log);
798```
799
800* * *
801
802<a name="module_serialport--SerialPort.list"></a>
803
804#### `SerialPort.list([callback])` ⇒ <code>Promise</code>
805Retrieves a list of available serial ports with metadata. Only the `comName` is guaranteed. If unavailable the other fields will be undefined. The `comName` is either the path or an identifier (eg `COM1`) used to open the SerialPort.
806
807We make an effort to identify the hardware attached and have consistent results between systems. Linux and OS X are mostly consistent. Windows relies on 3rd party device drivers for the information and is unable to guarantee the information. On windows If you have a USB connected device can we provide a serial number otherwise it will be `undefined`. The `pnpId` and `locationId` are not the same or present on all systems. The examples below were run with the same Arduino Uno.
808
809**Kind**: static method of [<code>SerialPort</code>](#exp_module_serialport--SerialPort)
810**Returns**: <code>Promise</code> - Resolves with the list of available serial ports.
811
812| Param | Type |
813| --- | --- |
814| [callback] | <code>listCallback</code> |
815
816**Example**
817```js
818// OSX example port
819{
820 comName: '/dev/tty.usbmodem1421',
821 manufacturer: 'Arduino (www.arduino.cc)',
822 serialNumber: '752303138333518011C1',
823 pnpId: undefined,
824 locationId: '14500000',
825 productId: '0043',
826 vendorId: '2341'
827}
828
829// Linux example port
830{
831 comName: '/dev/ttyACM0',
832 manufacturer: 'Arduino (www.arduino.cc)',
833 serialNumber: '752303138333518011C1',
834 pnpId: 'usb-Arduino__www.arduino.cc__0043_752303138333518011C1-if00',
835 locationId: undefined,
836 productId: '0043',
837 vendorId: '2341'
838}
839
840// Windows example port
841{
842 comName: 'COM3',
843 manufacturer: 'Arduino LLC (www.arduino.cc)',
844 serialNumber: '752303138333518011C1',
845 pnpId: 'USB\\VID_2341&PID_0043\\752303138333518011C1',
846 locationId: 'Port_#0003.Hub_#0001',
847 productId: '0043',
848 vendorId: '2341'
849}
850```
851
852```js
853var SerialPort = require('serialport');
854// callback approach
855SerialPort.list(function (err, ports) {
856 ports.forEach(function(port) {
857 console.log(port.comName);
858 console.log(port.pnpId);
859 console.log(port.manufacturer);
860 });
861});
862
863// promise approach
864SerialPort.list()
865 .then(ports) {...});
866 .catch(err) {...});
867```
868
869* * *
870
871<a name="module_serialport--SerialPort..BaseBinding"></a>
872
873#### SerialPort~BaseBinding
874You never have to use `Binding` objects directly. SerialPort uses them to access the underlying hardware. This documentation is geared towards people who are making bindings for different platforms. This class can be inherited from to get type checking for each method.
875
876**Kind**: inner class of [<code>SerialPort</code>](#exp_module_serialport--SerialPort)
877**Since**: 5.0.0
878**Properties**
879
880| Name | Type | Description |
881| --- | --- | --- |
882| isOpen | <code>boolean</code> | Required property. `true` if the port is open, `false` otherwise. Should be read-only. |
883
884
885* [~BaseBinding](#module_serialport--SerialPort..BaseBinding)
886 * [`new BaseBinding(options)`](#new_module_serialport--SerialPort..BaseBinding_new)
887 * _instance_
888 * [`.open(path, openOptions)`](#module_serialport--SerialPort..BaseBinding+open) ⇒ <code>Promise</code>
889 * [`.close()`](#module_serialport--SerialPort..BaseBinding+close) ⇒ <code>Promise</code>
890 * [`.read(data, offset, length)`](#module_serialport--SerialPort..BaseBinding+read) ⇒ <code>Promise</code>
891 * [`.write(data)`](#module_serialport--SerialPort..BaseBinding+write) ⇒ <code>Promise</code>
892 * [`.update([options])`](#module_serialport--SerialPort..BaseBinding+update) ⇒ <code>Promise</code>
893 * [`.set([options])`](#module_serialport--SerialPort..BaseBinding+set) ⇒ <code>Promise</code>
894 * [`.get()`](#module_serialport--SerialPort..BaseBinding+get) ⇒ <code>Promise</code>
895 * [`.flush()`](#module_serialport--SerialPort..BaseBinding+flush) ⇒ <code>Promise</code>
896 * [`.drain()`](#module_serialport--SerialPort..BaseBinding+drain) ⇒ <code>Promise</code>
897 * _static_
898 * [`.list()`](#module_serialport--SerialPort..BaseBinding.list) ⇒ <code>Promise</code>
899
900
901* * *
902
903<a name="new_module_serialport--SerialPort..BaseBinding_new"></a>
904
905##### `new BaseBinding(options)`
906**Throws**:
907
908- <code>TypeError</code> When given invalid arguments, a `TypeError` is thrown.
909
910
911| Param | Type |
912| --- | --- |
913| options | <code>object</code> |
914
915
916* * *
917
918<a name="module_serialport--SerialPort..BaseBinding+open"></a>
919
920##### `baseBinding.open(path, openOptions)` ⇒ <code>Promise</code>
921Opens a connection to the serial port referenced by the path.
922
923**Kind**: instance method of [<code>BaseBinding</code>](#module_serialport--SerialPort..BaseBinding)
924**Returns**: <code>Promise</code> - Resolves after the port is opened and configured.
925**Throws**:
926
927- <code>TypeError</code> When given invalid arguments, a `TypeError` is thrown.
928
929
930| Param | Type |
931| --- | --- |
932| path | <code>string</code> |
933| openOptions | [<code>openOptions</code>](#module_serialport--SerialPort..openOptions) |
934
935
936* * *
937
938<a name="module_serialport--SerialPort..BaseBinding+close"></a>
939
940##### `baseBinding.close()` ⇒ <code>Promise</code>
941Closes an open connection
942
943**Kind**: instance method of [<code>BaseBinding</code>](#module_serialport--SerialPort..BaseBinding)
944**Returns**: <code>Promise</code> - Resolves once the connection is closed.
945**Throws**:
946
947- <code>TypeError</code> When given invalid arguments, a `TypeError` is thrown.
948
949
950* * *
951
952<a name="module_serialport--SerialPort..BaseBinding+read"></a>
953
954##### `baseBinding.read(data, offset, length)` ⇒ <code>Promise</code>
955Request a number of bytes from the SerialPort. This function is similar to Node's [`fs.read`](http://nodejs.org/api/fs.html#fs_fs_read_fd_buffer_offset_length_position_callback) except it will always return at least one byte.
956
957The in progress reads must error when the port is closed with an error object that has the property `canceled` equal to `true`. Any other error will cause a disconnection.
958
959**Kind**: instance method of [<code>BaseBinding</code>](#module_serialport--SerialPort..BaseBinding)
960**Returns**: <code>Promise</code> - Resolves with the number of bytes read after a read operation.
961**Throws**:
962
963- <code>TypeError</code> When given invalid arguments, a `TypeError` is thrown.
964
965
966| Param | Type | Description |
967| --- | --- | --- |
968| data | <code>buffer</code> | Accepts a [`Buffer`](http://nodejs.org/api/buffer.html) object. |
969| offset | <code>integer</code> | The offset in the buffer to start writing at. |
970| length | <code>integer</code> | Specifies the maximum number of bytes to read. |
971
972
973* * *
974
975<a name="module_serialport--SerialPort..BaseBinding+write"></a>
976
977##### `baseBinding.write(data)` ⇒ <code>Promise</code>
978Write bytes to the SerialPort. Only called when there is no pending write operation.
979
980The in progress writes must error when the port is closed with an error object that has the property `canceled` equal to `true`. Any other error will cause a disconnection.
981
982**Kind**: instance method of [<code>BaseBinding</code>](#module_serialport--SerialPort..BaseBinding)
983**Returns**: <code>Promise</code> - Resolves after the data is passed to the operating system for writing.
984**Throws**:
985
986- <code>TypeError</code> When given invalid arguments, a `TypeError` is thrown.
987
988
989| Param | Type | Description |
990| --- | --- | --- |
991| data | <code>buffer</code> | Accepts a [`Buffer`](http://nodejs.org/api/buffer.html) object. |
992
993
994* * *
995
996<a name="module_serialport--SerialPort..BaseBinding+update"></a>
997
998##### `baseBinding.update([options])` ⇒ <code>Promise</code>
999Changes connection settings on an open port. Only `baudRate` is supported.
1000
1001**Kind**: instance method of [<code>BaseBinding</code>](#module_serialport--SerialPort..BaseBinding)
1002**Returns**: <code>Promise</code> - Resolves once the port's baud rate changes.
1003**Throws**:
1004
1005- <code>TypeError</code> When given invalid arguments, a `TypeError` is thrown.
1006
1007
1008| Param | Type | Description |
1009| --- | --- | --- |
1010| [options] | <code>object</code> | Only supports `baudRate`. |
1011| [options.baudRate] | <code>number</code> | If provided a baud rate that the bindings do not support, it should pass an error to the callback. |
1012
1013
1014* * *
1015
1016<a name="module_serialport--SerialPort..BaseBinding+set"></a>
1017
1018##### `baseBinding.set([options])` ⇒ <code>Promise</code>
1019Set control flags on an open port.
1020
1021**Kind**: instance method of [<code>BaseBinding</code>](#module_serialport--SerialPort..BaseBinding)
1022**Returns**: <code>Promise</code> - Resolves once the port's flags are set.
1023**Throws**:
1024
1025- <code>TypeError</code> When given invalid arguments, a `TypeError` is thrown.
1026
1027
1028| Param | Type | Default | Description |
1029| --- | --- | --- | --- |
1030| [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 are always provided. |
1031| [options.brk] | <code>Boolean</code> | <code>false</code> | |
1032| [options.cts] | <code>Boolean</code> | <code>false</code> | |
1033| [options.dsr] | <code>Boolean</code> | <code>false</code> | |
1034| [options.dtr] | <code>Boolean</code> | <code>true</code> | |
1035| [options.rts] | <code>Boolean</code> | <code>true</code> | |
1036
1037
1038* * *
1039
1040<a name="module_serialport--SerialPort..BaseBinding+get"></a>
1041
1042##### `baseBinding.get()` ⇒ <code>Promise</code>
1043Get the control flags (CTS, DSR, DCD) on the open port.
1044
1045**Kind**: instance method of [<code>BaseBinding</code>](#module_serialport--SerialPort..BaseBinding)
1046**Returns**: <code>Promise</code> - Resolves with the retrieved flags.
1047**Throws**:
1048
1049- <code>TypeError</code> When given invalid arguments, a `TypeError` is thrown.
1050
1051
1052* * *
1053
1054<a name="module_serialport--SerialPort..BaseBinding+flush"></a>
1055
1056##### `baseBinding.flush()` ⇒ <code>Promise</code>
1057Flush (discard) data received but not read, and written but not transmitted.
1058
1059**Kind**: instance method of [<code>BaseBinding</code>](#module_serialport--SerialPort..BaseBinding)
1060**Returns**: <code>Promise</code> - Resolves once the flush operation finishes.
1061**Throws**:
1062
1063- <code>TypeError</code> When given invalid arguments, a `TypeError` is thrown.
1064
1065
1066* * *
1067
1068<a name="module_serialport--SerialPort..BaseBinding+drain"></a>
1069
1070##### `baseBinding.drain()` ⇒ <code>Promise</code>
1071Drain waits until all output data is transmitted to the serial port. An in progress write should be completed before this returns.
1072
1073**Kind**: instance method of [<code>BaseBinding</code>](#module_serialport--SerialPort..BaseBinding)
1074**Returns**: <code>Promise</code> - Resolves once the drain operation finishes.
1075**Throws**:
1076
1077- <code>TypeError</code> When given invalid arguments, a `TypeError` is thrown.
1078
1079
1080* * *
1081
1082<a name="module_serialport--SerialPort..BaseBinding.list"></a>
1083
1084##### `BaseBinding.list()` ⇒ <code>Promise</code>
1085Retrieves a list of available serial ports with metadata. The `comName` must be guaranteed, and all other fields should be undefined if unavailable. The `comName` is either the path or an identifier (eg `COM1`) used to open the serialport.
1086
1087**Kind**: static method of [<code>BaseBinding</code>](#module_serialport--SerialPort..BaseBinding)
1088**Returns**: <code>Promise</code> - resolves to an array of port [info objects](#module_serialport--SerialPort.list).
1089
1090* * *
1091
1092<a name="module_serialport--SerialPort..errorCallback"></a>
1093
1094#### `SerialPort~errorCallback` : <code>function</code>
1095A callback called with an error or null.
1096
1097**Kind**: inner typedef of [<code>SerialPort</code>](#exp_module_serialport--SerialPort)
1098
1099| Param | Type |
1100| --- | --- |
1101| error | <code>error</code> |
1102
1103
1104* * *
1105
1106<a name="module_serialport--SerialPort..modemBitsCallback"></a>
1107
1108#### `SerialPort~modemBitsCallback` : <code>function</code>
1109A callback called with an error or an object with the modem line values (cts, dsr, dcd).
1110
1111**Kind**: inner typedef of [<code>SerialPort</code>](#exp_module_serialport--SerialPort)
1112
1113| Param | Type | Default |
1114| --- | --- | --- |
1115| error | <code>error</code> | |
1116| status | <code>object</code> | |
1117| [status.cts] | <code>boolean</code> | <code>false</code> |
1118| [status.dsr] | <code>boolean</code> | <code>false</code> |
1119| [status.dcd] | <code>boolean</code> | <code>false</code> |
1120
1121
1122* * *
1123
1124<a name="module_serialport--SerialPort..openOptions"></a>
1125
1126#### `SerialPort~openOptions` : <code>Object</code>
1127**Kind**: inner typedef of [<code>SerialPort</code>](#exp_module_serialport--SerialPort)
1128**Properties**
1129
1130| Name | Type | Default | Description |
1131| --- | --- | --- | --- |
1132| autoOpen | <code>boolean</code> | <code>true</code> | Automatically opens the port on `nextTick`. |
1133| baudRate | <code>number</code> | <code>9600</code> | The baud rate of the port to be opened. This should match one of the commonly available baud rates, such as 110, 300, 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, or 115200. Custom rates are supported best effort per platform. The device connected to the serial port is not guaranteed to support the requested baud rate, even if the port itself supports that baud rate. |
1134| dataBits | <code>number</code> | <code>8</code> | Must be one of these: 8, 7, 6, or 5. |
1135| highWaterMark | <code>number</code> | <code>65536</code> | The size of the read and write buffers defaults to 64k. |
1136| lock | <code>boolean</code> | <code>true</code> | Prevent other processes from opening the port. Windows does not currently support `false`. |
1137| stopBits | <code>number</code> | <code>1</code> | Must be one of these: 1 or 2. |
1138| parity | <code>string</code> | <code>&quot;none&quot;</code> | Must be one of these: 'none', 'even', 'mark', 'odd', 'space'. |
1139| rtscts | <code>boolean</code> | <code>false</code> | flow control setting |
1140| xon | <code>boolean</code> | <code>false</code> | flow control setting |
1141| xoff | <code>boolean</code> | <code>false</code> | flow control setting |
1142| xany | <code>boolean</code> | <code>false</code> | flow control setting |
1143| bindingOptions | <code>object</code> | | sets binding-specific options |
1144| Binding | <code>module:serialport~Binding</code> | | The hardware access binding. `Bindings` are how Node-Serialport talks to the underlying system. By default we auto detect Windows (`WindowsBinding`), Linux (`LinuxBinding`) and OS X (`DarwinBinding`) and load the appropriate module for your system. |
1145| bindingOptions.vmin | <code>number</code> | <code>1</code> | see [`man termios`](http://linux.die.net/man/3/termios) LinuxBinding and DarwinBinding |
1146| bindingOptions.vtime | <code>number</code> | <code>0</code> | see [`man termios`](http://linux.die.net/man/3/termios) LinuxBinding and DarwinBinding |
1147
1148
1149* * *
1150
1151<a name="module_serialport--SerialPort..listCallback"></a>
1152
1153#### `SerialPort~listCallback` : <code>function</code>
1154This callback type is called `requestCallback`.
1155
1156**Kind**: inner typedef of [<code>SerialPort</code>](#exp_module_serialport--SerialPort)
1157
1158| Param | Type | Description |
1159| --- | --- | --- |
1160| error | <code>error</code> | |
1161| ports | <code>array</code> | an array of objects with port info |
1162
1163
1164* * *
1165
1166
1167## Command Line Tools
1168If you install `serialport` globally (e.g., `npm install -g serialport`), you'll receive two command line tools.
1169
1170### Serial Port List
1171`serialport-list` will list all available serial ports in different formats.
1172
1173```bash
1174$ serialport-list -h
1175
1176 Usage: serialport-list [options]
1177
1178 List available serial ports
1179
1180 Options:
1181
1182 -h, --help output usage information
1183 -V, --version output the version number
1184 -f, --format <type> Format the output as text, json, or jsonline. default: text
1185
1186
1187$ serialport-list
1188/dev/tty.Bluetooth-Incoming-Port
1189/dev/tty.usbmodem1421 Arduino (www.arduino.cc)
1190
1191$ serialport-list -f json
1192[{"comName":"/dev/tty.Bluetooth-Incoming-Port"},{"comName":"/dev/tty.usbmodem1421","manufacturer":"Arduino (www.arduino.cc)","serialNumber":"752303138333518011C1","locationId":"14200000","vendorId":"2341","productId":"0043"}]
1193
1194$ serialport-list -f jsonline
1195{"comName":"/dev/tty.Bluetooth-Incoming-Port"}
1196{"comName":"/dev/tty.usbmodem1421","manufacturer":"Arduino (www.arduino.cc)","serialNumber":"752303138333518011C1","locationId":"14200000","vendorId":"2341","productId":"0043"}
1197```
1198
1199### Serial Port Terminal
1200`serialport-term` provides a basic terminal interface for communicating over a serial port. `ctrl+c` will exit.
1201
1202```bash
1203$ serialport-term -h
1204
1205 Usage: serialport-term -p <port> [options]
1206
1207 A basic terminal interface for communicating over a serial port. Pressing ctrl+c exits.
1208
1209 Options:
1210
1211 -h, --help output usage information
1212 -V, --version output the version number
1213 -l --list List available ports then exit
1214 -p, --port, --portname <port> Path or name of serial port
1215 -b, --baud <baudrate> Baud rate default: 9600
1216 --databits <databits> Data bits default: 8
1217 --parity <parity> Parity default: none
1218 --stopbits <bits> Stop bits default: 1
1219 --echo --localecho Print characters as you type them
1220
1221$ serialport-term -l
1222/dev/tty.Bluetooth-Incoming-Port
1223/dev/tty.usbmodem1421 Arduino (www.arduino.cc)
1224```
1225
1226### Serial Port Repl
1227`serialport-repl` provides a nodejs repl for working with serialport. This is valuable when debugging.
1228
1229You can make use of the `serialport-repl` command with;
1230```bash
1231$ serialport-repl # to auto detect an arduino
1232$ serialport-repl /dev/tty.usbmodem1421 # to connect to a specific port
1233```
1234
1235It will load a serialport object with debugging turned on.
1236```
1237 serialport:binding:auto-detect loading DarwinBinding +0ms
1238port = SerialPort("/dev/tty.usbmodem1421", { autoOpen: false })
1239globals { SerialPort, portName, port }
1240> SerialPort.list()
1241 serialport:main .list +6s
1242[ { comName: '/dev/tty.usbmodem1421',
1243 manufacturer: 'Arduino (www.arduino.cc)',
1244 serialNumber: '752303138333518011C1',
1245 pnpId: undefined,
1246 locationId: '14200000',
1247 vendorId: '2341',
1248 productId: '0043' } ]
1249> port.write('Calling all Autobots!')
1250true
1251> port.read()
1252 serialport:main _read queueing _read for after open +1m
1253null
1254> port.open()
1255 serialport:main opening path: /dev/tty.usbmodem1421 +30s
1256 serialport:bindings open +1ms
1257```
1258
1259## License
1260SerialPort is [MIT licensed](LICENSE) and all it's dependencies are MIT or BSD licensed.