NordicPlayground/node-serialport

Name: node-serialport

Owner: Nordic Semiconductor Playground

Description: Node.js package to access serial ports. Linux, OSX and Windows. Welcome your robotic JavaScript overlords. Better yet, program them!

Created: 2018-02-01 11:04:34.0

Updated: 2018-03-09 23:25:42.0

Pushed: 2018-03-05 12:18:42.0

Homepage:

Size: 2234

Language: JavaScript

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

Node Serialport

npm Gitter chat Known Vulnerabilities codecov Build Status Build status Greenkeeper badge

Intro to Node-Serialport

Imagine a world where 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.

Node-Serialport provides a stream interface for the low-level serial port code necessary to controll Arduino chipsets, X10 interfaces, Zigbee 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 you have a hardware device with a UART we can speak to it. The physical world is your oyster with this goodie.

For a full breakdown of why we made Node-Serialport, please read NodeBots - The Rise of JS Robotics. It explains why one would want to program robots in JS in the first place.

We're not against firmware but we're better than it.

Quick Answers to Important Questions

API Documentation

Can be found at https://node-serialport.github.io/node-serialport/

See our changelog for what's new, and our upgrade guide for a walk-through on differences between major versions.

Older versions are no longer supported but their docs can be found by looking through release tags.

You can generate the docs by running

run docs

And browsing to ./docs/index.html.


Helpful Resources for Getting Started with Node-Serialport

In addition to reading the article mentioned above, these others might help you:


Table of Contents

Platform Support

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;

| Platform / Arch | Node v4.x | Node v6.x | Node v8.x | Node v9.x | | — | — | — | — | — | | Linux / ia32 | ? | ? | ? | ? | | Linux / x64 | ? | ? | ? | ? | | Linux / ARM v6¹ | ? | ? | ? | ? | | Linux / ARM v7¹ | ? | ? | ? | ? | | Linux / ARM v8¹ | ? | ? | ? | ? | | Linux / MIPSel¹ | ? | ? | ? | ? | | Linux / PPC64¹ | ? | ? | ? | ? | | Windows² / x86 | ? | ? | ? | ? | | Windows² / x64 | ? | ? | ? | ? | | OSX³ / x64 | ? | ? | ? | ? |

¹ ARM, MIPSel and PPC64¹ platforms are not currently part of our testing or build matrix, but are known to work.

² Windows 7, 8, 10, and 10 IoT are supported, but our CI tests only Windows Server 2012 R2.

³ OSX 10.4 Tiger and above are supported, but our CI tests only 10.9.5 Mavericks with Xcode 6.1.

? Node 9 is not supported but we're providing builds for it.

Installation Instructions

For 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:

install serialport
Installation Special Cases

We use 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.

This 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.

Alpine Linux

Alpine is a (very) small distro, but it uses the musl standard library instead of glibc (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.

 you don't have node/npm already, add that first
 apk add --no-cache nodejs

d the necessary build and runtime dependencies
 apk add --no-cache make gcc g++ python linux-headers udev

en we can install serialport, forcing it to compile
install serialport --build-from-source

 you're installing as root, you'll also need to use the --unsafe-perm flag
Electron

Electron is a framework for creating cross-platform desktop applications. It comes with its own version of the Node.js runtime.

If you require serialport as a dependency for an Electron project, you must compile it for the version of Electron your project's using.

When 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.

To recompile serialport (or any native Node.js module) for Electron, you can use electron-rebuild; more info at Electron's README.

  1. npm install --save-dev electron-rebuild
  2. Add electron-rebuild to your project's package.json's install hook
  3. Run npm install

For an example project, check out electron-serialport.

NW.js

NW.js is an app runtime based on Chromium and node.js.

Like Electron, NW.js also requires compilation against its own specific headers.

To instruct prebuild to build against the correct headers, place a file named .prebuildrc on your package root with the following content:

d_from_source=true
ime=node-webkit
et=<target_version>

Where <target_version> is the NW.js version you are building against (for example, 0.26.6).

OBS: NW.js support requires prebuild >= 7.3.0.

Illegal Instruction

The pre-compiled binaries assume a fully capable chip. Intel's Galileo 2, 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.

ll ask npm to build serialport during install time
install serialport --build-from-source

 you have a package that depends on serialport, you can ask npm to rebuild it specifically...
rebuild serialport --build-from-source
Mac OS X

Ensure 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.

Raspberry Pi Linux

Follow the instructions for setting up a Raspberry pi for use with Johnny-Five and Raspi IO. These projects use Node Serialport under the hood.

| Revision | CPU | Arm Version | | —- | — | — | | A, A+, B, B+ | 32-bit ARM1176JZF-S | ARMv6 | | Compute Module | 32-bit ARM1176JZF-S | ARMv6 | | Zero | 32-bit ARM1176JZF-S | ARMv6 | | B2 | 32-bit ARM Cortex-A7 | ARMv7 | | B3 | 32-bit ARM Cortex-A53 | ARMv8 |

sudo / root

If you're going to use sudo or root to install Node-Serialport, npm will require you to use the unsafe parameters flag.

 npm install serialport --unsafe-perm --build-from-source

Failure to use the flag results in an error like this:

@rpi3:~# npm install -g serialport
/bin/serialport-list -> /usr/lib/node_modules/serialport/bin/serialport-list.js
/bin/serialport-term -> /usr/lib/node_modules/serialport/bin/serialport-terminal.js


rialport@6.0.0-beta1 install /Users/wizard/src/node-serialport
ebuild-install || node-gyp rebuild

uild-install info begin Prebuild-install version 2.2.1
uild-install info install installing standalone, skipping download.

WARN EACCES user "root" does not have permission to access the dev dir "/root/.node-gyp/6.9.1"
WARN EACCES attempting to reinstall using temporary dev dir "/usr/lib/node_modules/serialport/.node-gyp"
: Entering directory '/usr/lib/node_modules/serialport/build'
: *** No rule to make target '../.node-gyp/6.9.1/include/node/common.gypi', needed by 'Makefile'.  Stop.
: Leaving directory '/usr/lib/node_modules/serialport/build'
ERR! build error
ERR! stack Error: `make` failed with exit code: 2
Ubuntu/Debian Linux

The best way to install any version of Node.js is to use the NodeSource Node.js binary distributions. 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, then you should follow these instructions.

You'll need the package build-essential to compile serialport. If there's a binary for your platform, you won't need it. Keep rocking!

ing Ubuntu and Node 6
 -sL https://deb.nodesource.com/setup_7.x | sudo -E bash -
 apt-get install -y nodejs

ing Debian and Node 6 as root
 -sL https://deb.nodesource.com/setup_7.x | bash -
get install -y nodejs
Windows

Node-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 instructions. Once you've got things working, you can install Node-Serialport from source with:

install serialport --build-from-source

Node-gyp's documentation doesn't mention it, but it sometimes helps to create a C++ project in Visual Studio 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".

An 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).

Usage
Opening a Port
SerialPort = require('serialport');
port = new SerialPort('/dev/tty-usbserial1', {
udRate: 57600

When opening a serial port, specify (in this order)

  1. Path to Serial Port - required.
  2. Options - optional and described below.

Constructing 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.

SerialPort = require('serialport');
port = new SerialPort('/dev/tty-usbserial1');

.write('main screen turn on', function(err) {
 (err) {
return console.log('Error on write: ', err.message);

nsole.log('message written');


pen errors will be emitted as an error event
.on('error', function(err) {
nsole.log('Error: ', err.message);

Detecting open errors can be moved to the constructor's callback.

SerialPort = require('serialport');
port = new SerialPort('/dev/tty-usbserial1', function (err) {
 (err) {
return console.log('Error: ', err.message);



.write('main screen turn on', function(err) {
 (err) {
return console.log('Error on write: ', err.message);

nsole.log('message written');

When disabling the autoOpen option you'll need to open the port on your own.

SerialPort = require('serialport');
port = new SerialPort('/dev/tty-usbserial1', { autoOpen: false });

.open(function (err) {
 (err) {
return console.log('Error opening port: ', err.message);


 Because there's no callback to write, write errors will be emitted on the port:
rt.write('main screen turn on');


he open event is always emitted
.on('open', function() {
 open logic

Get updates of new data from the serial port as follows:

witches the port into "flowing mode"
.on('data', function (data) {
nsole.log('Data:', data);


ead data that is available but keep the stream from entering "flowing mode"
.on('readable', function () {
nsole.log('Data:', port.read());

You can write to the serial port by sending a string or buffer to the write method:

.write('Hi Mom!');
.write(Buffer.from('Hi Mom!'));

Enjoy and do cool things with this code.

Testing

Testing 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.

t SerialPort = require('serialport/test');
t MockBinding = SerialPort.Binding;

reate a port and enable the echo and recording.
Binding.createPort('/dev/ROBOT', { echo: true, record: true })
t port = new SerialPort('/dev/ROBOT')
Debugging

We use the debug package and log under the serialport namespace:

You can enable logging through environment variables. Check the debug docs for info.

G=serialport:main node myapp.js
G=serialport:* node myapp.js
G=* node myapp.js

You can enable core dumps on osx with;

it -c unlimited for core dumps

You can “console.log” from c++ with;

ntf(stdout, "Hellow World num=%d str=%s\n", 4, "hi");

You can make use of the serialport-repl command with;

alport-repl # to auto detect an arduino
alport-repl /path/name # to connect to a specific port

It will load a serialport object with debugging turned on.

Error Handling

All functions in Node-Serialport follow two conventions:

You should never have to wrap a Node-Serialport object in a try/catch statement if you call the functions with the correct arguments.

Command Line Tools

If you install serialport globally (e.g., npm install -g serialport), you'll receive two command line tools.

Serial Port List

serialport-list will list all available serial ports in different formats.

rialport-list -h

age: serialport-list [options]

st available serial ports

tions:

-h, --help           output usage information
-V, --version        output the version number
-f, --format <type>  Format the output as text, json, or jsonline. default: text


rialport-list
/tty.Bluetooth-Incoming-Port
/tty.usbmodem1421    Arduino (www.arduino.cc)

rialport-list -f json
omName":"/dev/tty.Bluetooth-Incoming-Port"},{"comName":"/dev/tty.usbmodem1421","manufacturer":"Arduino (www.arduino.cc)","serialNumber":"752303138333518011C1","locationId":"14200000","vendorId":"2341","productId":"0043"}]

rialport-list -f jsonline
mName":"/dev/tty.Bluetooth-Incoming-Port"}
mName":"/dev/tty.usbmodem1421","manufacturer":"Arduino (www.arduino.cc)","serialNumber":"752303138333518011C1","locationId":"14200000","vendorId":"2341","productId":"0043"}
Serial Port Terminal

serialport-term provides a basic terminal interface for communicating over a serial port. ctrl+c will exit.

rialport-term -h

age: serialport-term -p <port> [options]

basic terminal interface for communicating over a serial port. Pressing ctrl+c exits.

tions:

-h, --help                     output usage information
-V, --version                  output the version number
-l --list                      List available ports then exit
-p, --port, --portname <port>  Path or name of serial port
-b, --baud <baudrate>          Baud rate default: 9600
--databits <databits>          Data bits default: 8
--parity <parity>              Parity default: none
--stopbits <bits>              Stop bits default: 1
--echo --localecho             Print characters as you type them

rialport-term -l
/tty.Bluetooth-Incoming-Port
/tty.usbmodem1421    Arduino (www.arduino.cc)
Serial Port Repl

serialport-repl provides a nodejs repl for working with serialport. This is valuable when debugging.

You can make use of the serialport-repl command with;

rialport-repl # to auto detect an arduino
rialport-repl /dev/tty.usbmodem1421 # to connect to a specific port

It will load a serialport object with debugging turned on.

rialport:binding:auto-detect loading DarwinBinding +0ms
 = SerialPort("/dev/tty.usbmodem1421", { autoOpen: false })
als { SerialPort, portName, port }
rialPort.list()
rialport:main .list +6s
comName: '/dev/tty.usbmodem1421',
manufacturer: 'Arduino (www.arduino.cc)',
serialNumber: '752303138333518011C1',
pnpId: undefined,
locationId: '14200000',
vendorId: '2341',
productId: '0043' } ]
rt.write('Calling all Autobots!')

rt.read()
rialport:main _read queueing _read for after open +1m

rt.open()
rialport:main opening path: /dev/tty.usbmodem1421 +30s
rialport:bindings open +1ms
License

SerialPort is MIT licensed and all it's dependencies are MIT or BSD licensed.


This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.