Created
July 22, 2017 19:29
-
-
Save nucleardreamer/84a5213112e762576d7cd044da0d4963 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const SerialPort = require('serialport') | |
const _ = require('lodash') | |
const async = require('async') | |
var devices = [] | |
// find all lights and connect to them (serial port opens automatically) | |
function init (config, cb = function () {}) { | |
// example device | |
// comName: '/dev/ttyACM1', | |
// manufacturer: 'OAK', | |
// serialNumber: 'OAK_LIGHT', | |
// pnpId: 'usb-OAK_LIGHT-if00', | |
// vendorId: '0x1b4f', | |
// productId: '0x8d21' | |
SerialPort.list((err, ports) => { | |
if (err) console.error(err) | |
devices = _.chain(ports) | |
.filter(d => d.serialNumber === 'OAK_LIGHT') | |
.map(function (d) { | |
return new SerialPort( | |
d.comName, | |
{ | |
autoOpen: true, | |
baudRate: 9600 | |
} | |
) | |
}) | |
.value() | |
}) | |
} | |
function list () { | |
return devices | |
} | |
// only need to call if you have fired close() previously | |
function open (cb = function () {}) { | |
async.each(function (d, _cb) { | |
if (!d.isOpen()) { | |
d.open(_cb) | |
} | |
}, cb) | |
} | |
function change ({ r = 0, g = 0, b = 0, w = 0, dur = 1000 } = {}, cb = function () {}) { | |
let toWrite = [r, g, b, w, dur].join(',') | |
async.each(devices, function (device, next) { | |
if (!device.isOpen()) return next() | |
device.write(toWrite, next) | |
}, cb) | |
} | |
function close (cb = function () {}) { | |
async.each(devices, function (device, next) { | |
device.close(next) | |
}, cb) | |
} | |
module.exports = { init, change, open, close, list } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment