Saturday 31 August 2013

node.js serialport events stop working after reconnecting to port

node.js serialport events stop working after reconnecting to port

I'm using the serialport2 library for node.js to receive serial data from
an arduino. This works like a charm but every now and then the pc running
node, decides to deactivate the usb ports due to EMI. Allthough the ports
get activated again right away, Serialport drops the connection. Node.js
remains running but never recovers the serial connection to the arduino.
Using the 'closed' event of Serialport I want node to reconnect to the
serial port, after a short delay. This works fine, so far:
var SerialPort = require('serialport2').SerialPort;
var arduinoPort = '/dev/arduino';
// setting up the serial connection
var arduinoSerial = new SerialPort();
var connectArd = function() {
arduinoSerial.open(arduinoPort, {
baudRate: 9600,
dataBits: 8,
parity: 'none',
stopBits: 1,
flowControl: false
});
}
connectArd();
// do something with incoming data
arduinoSerial.on('data', function (data) {
.
.
.
});
// check for connection errors or drops and reconnect
var reconnectArd = function () {
console.log('INITIATING RECONNECT');
setTimeout(function(){
console.log('RECONNECTING TO ARDUINO');
connectArd();
}, 2000);
};
arduinoSerial.on('close', function(){
console.log('ARDUINO PORT CLOSED');
reconnectArd();
});
arduinoSerial.on('error', function (err) {
console.error("error", err);
reconnectArd();
});
As soon as there is an EMI or the USB cable gets disconnected the 'close'
listener of 'arduinoSerial' kicks in, waits for about 2 seconds and
reconnects to the arduino. The connection is recovered and node receives
data from the arduino again.
But... this only works once!? When there is a second disconnect, node
stops receiving data but for some reason, this time the 'close' event
doesn't get triggered. I have to restart the node application in order to
reconnect to the arduino again.
I'm fairly new to javascript, so this could very well be a rookie mistake.
What am I doing wrong? Could someone please point me in the right
direction?
(I know I should rather start looking for the source of the interference
but this kind of an auto-reconnect-function will come in handy for
usability/handling reasons of the device, as well.)
thanks

No comments:

Post a Comment