|
'use strict'; |
|
|
|
var serialport = require('serialport'), |
|
SerialPort = serialport.SerialPort, // localize object constructor |
|
events = require('events'), |
|
fs = require('fs'), |
|
util = require('util'); |
|
|
|
var startAccessPoint = new Buffer([0xFF, 0x7, 0x03]), |
|
stopAccessPoint = new Buffer([0xFF, 0x9, 0x03]), |
|
accDataRequest = new Buffer([0xFF, 0x08, 0x07, 0x00, 0x00, 0x00, 0x00]), |
|
devicePath = '/dev/ttyACM0'; // temp fix |
|
|
|
var DEBOUNCE = 50; |
|
|
|
function ez430(options) { |
|
var sp, self = this; |
|
|
|
options = options || {}; |
|
events.EventEmitter.call(this); |
|
|
|
try { |
|
fs.statSync(devicePath); |
|
} catch (e) { |
|
throw new Error('device not found'); |
|
} |
|
sp = new SerialPort(devicePath, { baudRate: 115200 }, function(){ |
|
console.log('Chronos serial port at', devicePath); |
|
}); |
|
|
|
this.close = function () { |
|
sp.write(stopAccessPoint); |
|
sp.close(); |
|
}; |
|
|
|
sp.on('open', function () { |
|
console.log('ez430: start ap..', startAccessPoint); |
|
|
|
sp.write(startAccessPoint); |
|
sp.write(accDataRequest); |
|
|
|
sp.on('data', function (data) { |
|
var timeout = DEBOUNCE, |
|
x, y, z, b = 0, on, |
|
buf = new Buffer(data); |
|
if (data.length >= 7) { |
|
b = buf.readInt8(3); |
|
x = buf.readInt8(5); |
|
y = buf.readInt8(4); |
|
z = buf.readInt8(6); |
|
on = (buf[3] === 1 || buf[3] === 18 || buf[3] === 34 || buf[3] === 50); |
|
if (on) { |
|
console.log('b:' + b + ', x:' + x + ', y:' + y + ', z:' + z); |
|
self.emit('chronosData', b, x, y, z); |
|
} |
|
} else { |
|
console.log((new Date()).getTime() + ' invalid data', buf); |
|
} |
|
setTimeout(function () {sp.write(accDataRequest);}, timeout); |
|
}); |
|
sp.on('close', function (err) { |
|
console.log('port closed'); |
|
self.emit('close'); |
|
}); |
|
sp.on('error', function (err) { |
|
console.log('error', err); |
|
sp.write(stopAccessPoint); |
|
self.emit('error', err); |
|
}); |
|
}); |
|
} |
|
|
|
util.inherits(ez430, events.EventEmitter); |
|
module.exports = ez430; |