UNPKG

22.4 kBMarkdownView Raw
1# Node Serialport
2
3[![npm](https://img.shields.io/npm/dm/serialport.svg?maxAge=2592000)](http://npmjs.com/package/serialport)
4[![Gitter chat](https://badges.gitter.im/EmergingTechnologyAdvisors/node-serialport.svg)](https://gitter.im/EmergingTechnologyAdvisors/node-serialport)
5[![Known Vulnerabilities](https://snyk.io/test/github/node-serialport/node-serialport/badge.svg)](https://snyk.io/test/github/node-serialport/node-serialport)
6[![codecov](https://codecov.io/gh/node-serialport/node-serialport/branch/master/graph/badge.svg)](https://codecov.io/gh/node-serialport/node-serialport)
7[![Build Status](https://travis-ci.org/node-serialport/node-serialport.svg?branch=master)](https://travis-ci.org/node-serialport/node-serialport)
8[![Build status](https://ci.appveyor.com/api/projects/status/u6xe3iao2crd7akn/branch/master?svg=true)](https://ci.appveyor.com/project/serialport/node-serialport/branch/master)
9[![Greenkeeper badge](https://badges.greenkeeper.io/node-serialport/node-serialport.svg)](https://greenkeeper.io/)
10
11## Intro to Node-Serialport
12
13Imagine 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.
14
15Node-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.
16
17For 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.
18
19We're not against firmware but we're better than it.
20
21## Quick Answers to Important Questions
22- [**API Docs**](https://doclets.io/node-serialport/node-serialport/)
23- **For support**, open a [GitHub issue](https://github.com/node-serialport/node-serialport/issues/new).
24- **For discussions, design ideas, and clarifications**, please join our [Gitter chat room](https://gitter.im/EmergingTechnologyAdvisors/node-serialport).
25- **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).
26- **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/node-serialport/node-serialport/issues/746). We also have issues tagged ["good first PR"](https://github.com/node-serialport/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.
27
28***
29
30## API Documentation
31
32Can be found at https://doclets.io/node-serialport/node-serialport/
33
34See our [changelog](CHANGELOG.md) for what's new, and our [upgrade guide](UPGRADE_GUIDE.md) for a walk-through on differences between major versions.
35
36Older versions are no longer supported but their docs can be found by looking through release tags.
37
38You can generate the docs by running
39
40```bash
41npm run docs
42```
43
44And browsing to `./docs/index.html`.
45
46***
47## Helpful Resources for Getting Started with Node-Serialport
48
49In addition to reading the [article mentioned above](http://www.voodootikigod.com/nodebots-the-rise-of-js-robotics), these others might help you:
50* [Johnny-Five](http://johnny-five.io/#hello-world): The Johnny-Five Robotics and IoT platform's six-line "Hello World" (awesome).
51* [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.
52
53***
54## Table of Contents
55
56* [Platform Support](#platform-support)
57* [Installation](#installation-instructions)
58* [Installation Special Cases](#installation-special-cases)
59 * [Alpine Linux](#alpine-linux)
60 * [Electron](#electron)
61 * [Illegal Instruction](#illegal-instruction)
62 * [Mac OS X](#mac-os-x)
63 * [Raspberry Pi Linux](#raspberry-pi-linux)
64 * [sudo / root](#sudo--root)
65 * [Ubuntu/Debian Linux](#ubuntudebian-linux)
66 * [Windows](#windows)
67* [Usage](#usage)
68 * [Opening a Port](#opening-a-port)
69 * [Testing](#testing)
70 * [Debugging](#debugging)
71 * [Error Handling](#error-handling)
72d* [Command Line Tools](#command-line-tools)
73 * [Serial Port List](#serial-port-list)
74 * [Srial Port Terminal](#serial-port-terminal)
75 * [Serial Port Repl](#serial-port-repl)
76* [License](#license)
77
78***
79
80### Platform Support
81`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;
82
83| Platform / Arch | Node v4.x | Node v6.x | Node v8.x | Node v9.x |
84| --- | --- | --- | --- | --- |
85| Linux / ia32 | ☑ | ☑ | ☑ | ☐ |
86| Linux / x64 | ☑ | ☑ | ☑ | ☐ |
87| Linux / ARM v6¹ | ☐ | ☐ | ☐ | ☐ |
88| Linux / ARM v7¹ | ☐ | ☐ | ☐ | ☐ |
89| Linux / ARM v8¹ | ☐ | ☐ | ☐ | ☐ |
90| Linux / MIPSel¹ | ☐ | ☐ | ☐ | ☐ |
91| Linux / PPC64¹ | ☐ | ☐ | ☐ | ☐ |
92| Windows² / x86 | ☐ | ☑ | ☑ | ☐ |
93| Windows² / x64 | ☑ | ☑ | ☑ | ☐ |
94| OSX³ / x64 | ☑ | ☑ | ☑ | ☐ |
95
96¹ ARM, MIPSel and PPC64¹ platforms are not currently part of our testing or build matrix, but are known to work.
97
98² Windows 7, 8, 10, and 10 IoT are supported, but our CI tests only Windows Server 2012 R2.
99
100³ OSX 10.4 Tiger and above are supported, but our CI tests only 10.9.5 Mavericks with Xcode 6.1.
101
102⁴ Node 9 is not supported but we're providing builds for it.
103
104## Installation Instructions
105
106For 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:
107
108```
109npm install serialport
110```
111
112### Installation Special Cases
113
114We 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.
115
116This 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.
117
118#### Alpine Linux
119
120[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).
121
122```
123# If you don't have node/npm already, add that first
124sudo apk add --no-cache nodejs
125
126# Add the necessary build and runtime dependencies
127sudo apk add --no-cache make gcc g++ python linux-headers udev
128
129# Then we can install serialport, forcing it to compile
130npm install serialport --build-from-source
131
132# If you're installing as root, you'll also need to use the --unsafe-perm flag
133```
134
135#### Electron
136
137[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.
138
139If you require `serialport` as a dependency for an Electron project, you must compile it for the version of Electron your project's using.
140
141When 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.
142
143To 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).
144
1451. `npm install --save-dev electron-rebuild`
1462. Add `electron-rebuild` to your project's package.json's install hook
1473. Run `npm install`
148
149For an example project, check out [`electron-serialport`](https://github.com/johnny-five-io/electron-serialport).
150
151#### NW.js
152
153[NW.js](https://nwjs.io/) is an app runtime based on Chromium and node.js.
154
155Like Electron, NW.js also requires compilation against its own specific headers.
156
157To instruct `prebuild` to build against the correct headers, place a file named `.prebuildrc` on your package root with the following content:
158
159```
160build_from_source=true
161runtime=node-webkit
162target=<target_version>
163```
164
165Where `<target_version>` is the NW.js version you are building against (for example, `0.26.6`).
166
167OBS: NW.js support requires `prebuild >= 7.3.0`.
168
169#### Illegal Instruction
170
171The 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.
172
173```bash
174# Will ask npm to build serialport during install time
175npm install serialport --build-from-source
176
177# If you have a package that depends on serialport, you can ask npm to rebuild it specifically...
178npm rebuild serialport --build-from-source
179```
180
181#### Mac OS X
182
183Ensure 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.
184
185#### Raspberry Pi Linux
186
187Follow 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.
188
189| Revision | CPU | Arm Version |
190| ---- | --- | --- |
191| A, A+, B, B+ | 32-bit ARM1176JZF-S | ARMv6 |
192| Compute Module | 32-bit ARM1176JZF-S | ARMv6 |
193| Zero | 32-bit ARM1176JZF-S | ARMv6 |
194| B2 | 32-bit ARM Cortex-A7 | ARMv7 |
195| B3 | 32-bit ARM Cortex-A53 | ARMv8 |
196
197#### sudo / root
198If you're going to use `sudo` or root to install Node-Serialport, `npm` will require you to use the unsafe parameters flag.
199
200```bash
201sudo npm install serialport --unsafe-perm --build-from-source
202```
203
204Failure to use the flag results in an error like this:
205
206```bash
207root@rpi3:~# npm install -g serialport
208/usr/bin/serialport-list -> /usr/lib/node_modules/serialport/bin/serialport-list.js
209/usr/bin/serialport-term -> /usr/lib/node_modules/serialport/bin/serialport-terminal.js
210
211
212> serialport@6.0.0-beta1 install /Users/wizard/src/node-serialport
213> prebuild-install || node-gyp rebuild
214
215prebuild-install info begin Prebuild-install version 2.2.1
216prebuild-install info install installing standalone, skipping download.
217
218gyp WARN EACCES user "root" does not have permission to access the dev dir "/root/.node-gyp/6.9.1"
219gyp WARN EACCES attempting to reinstall using temporary dev dir "/usr/lib/node_modules/serialport/.node-gyp"
220make: Entering directory '/usr/lib/node_modules/serialport/build'
221make: *** No rule to make target '../.node-gyp/6.9.1/include/node/common.gypi', needed by 'Makefile'. Stop.
222make: Leaving directory '/usr/lib/node_modules/serialport/build'
223gyp ERR! build error
224gyp ERR! stack Error: `make` failed with exit code: 2
225
226```
227
228#### Ubuntu/Debian Linux
229
230The 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.
231
232You'll need the package `build-essential` to compile `serialport`. If there's a binary for your platform, you won't need it. Keep rocking!
233
234```
235# Using Ubuntu and Node 6
236curl -sL https://deb.nodesource.com/setup_7.x | sudo -E bash -
237sudo apt-get install -y nodejs
238
239# Using Debian and Node 6 as root
240curl -sL https://deb.nodesource.com/setup_7.x | bash -
241apt-get install -y nodejs
242```
243
244#### Windows
245Node-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:
246
247```powershell
248npm install serialport --build-from-source
249```
250
251Node-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"`.
252
253An 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).
254
255## Usage
256
257### Opening a Port
258
259```js
260var SerialPort = require('serialport');
261var port = new SerialPort('/dev/tty-usbserial1', {
262 baudRate: 57600
263});
264```
265
266When opening a serial port, specify (in this order)
267
2681. Path to Serial Port - required.
2691. Options - optional and described below.
270
271Constructing 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.
272
273- The `open` event is always emitted when the port is opened.
274- 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.
275- 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.
276
277```js
278var SerialPort = require('serialport');
279var port = new SerialPort('/dev/tty-usbserial1');
280
281port.write('main screen turn on', function(err) {
282 if (err) {
283 return console.log('Error on write: ', err.message);
284 }
285 console.log('message written');
286});
287
288// Open errors will be emitted as an error event
289port.on('error', function(err) {
290 console.log('Error: ', err.message);
291})
292```
293
294Detecting open errors can be moved to the constructor's callback.
295```js
296var SerialPort = require('serialport');
297var port = new SerialPort('/dev/tty-usbserial1', function (err) {
298 if (err) {
299 return console.log('Error: ', err.message);
300 }
301});
302
303port.write('main screen turn on', function(err) {
304 if (err) {
305 return console.log('Error on write: ', err.message);
306 }
307 console.log('message written');
308});
309
310```
311
312When disabling the `autoOpen` option you'll need to open the port on your own.
313
314```js
315var SerialPort = require('serialport');
316var port = new SerialPort('/dev/tty-usbserial1', { autoOpen: false });
317
318port.open(function (err) {
319 if (err) {
320 return console.log('Error opening port: ', err.message);
321 }
322
323 // Because there's no callback to write, write errors will be emitted on the port:
324 port.write('main screen turn on');
325});
326
327// The open event is always emitted
328port.on('open', function() {
329 // open logic
330});
331```
332
333Get updates of new data from the serial port as follows:
334
335```js
336// Switches the port into "flowing mode"
337port.on('data', function (data) {
338 console.log('Data:', data);
339});
340
341// Read data that is available but keep the stream from entering "flowing mode"
342port.on('readable', function () {
343 console.log('Data:', port.read());
344});
345```
346
347You can write to the serial port by sending a string or buffer to the write method:
348
349```js
350port.write('Hi Mom!');
351port.write(Buffer.from('Hi Mom!'));
352```
353
354Enjoy and do cool things with this code.
355
356### Testing
357
358Testing 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).
359
360```js
361const SerialPort = require('serialport/test');
362const MockBinding = SerialPort.Binding;
363
364// Create a port and enable the echo and recording.
365MockBinding.createPort('/dev/ROBOT', { echo: true, record: true })
366const port = new SerialPort('/dev/ROBOT')
367```
368
369### Debugging
370
371We use the [debug](https://www.npmjs.com/package/debug) package and log under the `serialport` namespace:
372
373 - `serialport:main` for all high-level/main logging
374 - `serialport:binding` for all low-level logging
375
376You can enable logging through environment variables. Check the [debug](https://www.npmjs.com/package/debug) docs for info.
377
378```bash
379DEBUG=serialport:main node myapp.js
380DEBUG=serialport:* node myapp.js
381DEBUG=* node myapp.js
382```
383
384You can enable core dumps on osx with;
385```bash
386ulimit -c unlimited for core dumps
387```
388
389You can "console.log" from c++ with;
390```c++
391fprintf(stdout, "Hellow World num=%d str=%s\n", 4, "hi");
392```
393
394You can make use of the `serialport-repl` command with;
395```bash
396serialport-repl # to auto detect an arduino
397serialport-repl /path/name # to connect to a specific port
398```
399
400It will load a serialport object with debugging turned on.
401
402### Error Handling
403
404All functions in Node-Serialport follow two conventions:
405
406- Argument errors throw a `TypeError` object. You'll see these when functions are called with invalid arguments.
407- 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.
408
409You should never have to wrap a Node-Serialport object in a try/catch statement if you call the functions with the correct arguments.
410
411## Command Line Tools
412If you install `serialport` globally (e.g., `npm install -g serialport`), you'll receive two command line tools.
413
414### Serial Port List
415`serialport-list` will list all available serial ports in different formats.
416
417```bash
418$ serialport-list -h
419
420 Usage: serialport-list [options]
421
422 List available serial ports
423
424 Options:
425
426 -h, --help output usage information
427 -V, --version output the version number
428 -f, --format <type> Format the output as text, json, or jsonline. default: text
429
430
431$ serialport-list
432/dev/tty.Bluetooth-Incoming-Port
433/dev/tty.usbmodem1421 Arduino (www.arduino.cc)
434
435$ serialport-list -f json
436[{"comName":"/dev/tty.Bluetooth-Incoming-Port"},{"comName":"/dev/tty.usbmodem1421","manufacturer":"Arduino (www.arduino.cc)","serialNumber":"752303138333518011C1","locationId":"14200000","vendorId":"2341","productId":"0043"}]
437
438$ serialport-list -f jsonline
439{"comName":"/dev/tty.Bluetooth-Incoming-Port"}
440{"comName":"/dev/tty.usbmodem1421","manufacturer":"Arduino (www.arduino.cc)","serialNumber":"752303138333518011C1","locationId":"14200000","vendorId":"2341","productId":"0043"}
441```
442
443### Serial Port Terminal
444`serialport-term` provides a basic terminal interface for communicating over a serial port. `ctrl+c` will exit.
445
446```bash
447$ serialport-term -h
448
449 Usage: serialport-term -p <port> [options]
450
451 A basic terminal interface for communicating over a serial port. Pressing ctrl+c exits.
452
453 Options:
454
455 -h, --help output usage information
456 -V, --version output the version number
457 -l --list List available ports then exit
458 -p, --port, --portname <port> Path or name of serial port
459 -b, --baud <baudrate> Baud rate default: 9600
460 --databits <databits> Data bits default: 8
461 --parity <parity> Parity default: none
462 --stopbits <bits> Stop bits default: 1
463 --echo --localecho Print characters as you type them
464
465$ serialport-term -l
466/dev/tty.Bluetooth-Incoming-Port
467/dev/tty.usbmodem1421 Arduino (www.arduino.cc)
468```
469
470### Serial Port Repl
471`serialport-repl` provides a nodejs repl for working with serialport. This is valuable when debugging.
472
473You can make use of the `serialport-repl` command with;
474```bash
475$ serialport-repl # to auto detect an arduino
476$ serialport-repl /dev/tty.usbmodem1421 # to connect to a specific port
477```
478
479It will load a serialport object with debugging turned on.
480```
481 serialport:binding:auto-detect loading DarwinBinding +0ms
482port = SerialPort("/dev/tty.usbmodem1421", { autoOpen: false })
483globals { SerialPort, portName, port }
484> SerialPort.list()
485 serialport:main .list +6s
486[ { comName: '/dev/tty.usbmodem1421',
487 manufacturer: 'Arduino (www.arduino.cc)',
488 serialNumber: '752303138333518011C1',
489 pnpId: undefined,
490 locationId: '14200000',
491 vendorId: '2341',
492 productId: '0043' } ]
493> port.write('Calling all Autobots!')
494true
495> port.read()
496 serialport:main _read queueing _read for after open +1m
497null
498> port.open()
499 serialport:main opening path: /dev/tty.usbmodem1421 +30s
500 serialport:bindings open +1ms
501```
502
503## License
504SerialPort is [MIT licensed](LICENSE) and all it's dependencies are MIT or BSD licensed.