Nodejs Serialport not open after 1012 writes - node.js

I'm using nodejs "v0.10.28" and npm "1.4.9", downloaded from http://nodejs.org.
I've installed serialport through npm
npm install serialport
My program is running on a Raspberry-pi and needs to keep sending updated values quickly through serialport, so I've created this test program.
var serialPort = require("serialport");
var SerialPort = require("serialport").SerialPort;
var sp = new SerialPort("/dev/ttyAMA0", {
baudrate: 9600
}, false);
console.log("Starting up serial host...");
var message = "Num: ";
var counter = 1000000;
function write()
{
message= counter.toString();
counter+=1;
sp.open(function(err)
{
console.log("Writing serial data: " + message);
sp.write(message, function(err, res)
{
if (err)
{
console.log(err);
}
sp.close();
});
});
}
setTimeout(write, 10); //wait 10 ms for everything to initialize correctly
setInterval(write, 50); //write data every 50 ms
The program runs ok for exactly 1012 writes, then crashes.
Program output towards the end:
...
Writing serial data: 1001011
Writing serial data: 1001012
Writing serial data: 1001013
[Error: Serialport not open.]
events.js:72
throw er; // Unhandled 'error' event
^
Error: Serialport not open.
at SerialPortFactory.SerialPort.close (/home/pi/node_modules/serialport/serialport.js:476:17)
at /home/pi/serialTest.js:25:7
at SerialPortFactory.SerialPort.write (/home/pi/node_modules/serialport/serialport.js:290:9)
at /home/pi/serialTest.js:19:13
at /home/pi/node_modules/serialport/serialport.js:224:11
Why is it crashing?
Is there any buffer overflow in memory somewhere?
And why exactly 1012 writes? Very close to 1024, is it a coincidence?

A friend just helped with answering this privately so I'll share findings here.
Code:
var SerialPort = require("serialport").SerialPort;
var sp = new SerialPort("/dev/ttyAMA0", {
baudrate: 9600
}, false);
console.log("Starting up serial host...");
var message = "Num: ";
var counter = 1000000;
sp.open(function(err) {
if (err) {
console.log("Port open error: ", err);
}
else {
console.log("Port opened!");
}
});
function write()
{
if (sp.isOpen()) {
message= counter.toString();
counter+=1;
console.log("Writing serial data: " + message);
sp.write(message, function(err, res)
{
if (err)
{
console.log(err);
}
setTimeout(write, 50);
});
}
else {
setTimeout(write, 50);
}
}
setTimeout(write, 10); //wait 10 ms for everything to initialize correctly
If you look closely you'll notice that now sp.open() is used once and in the beginning of write function sp.isOpen() is used to check if port is open.
Also setInterval(write, 50); is gone and now only use setTimeout(write, 10);
Code now works, but that still doesn't answer the question why did it use to crash when opening and closing the port in the previous code.

Related

RabbitMq program is hanging while handling 100k messages. is this the right way to do it?

The code is attached below. my system hangs. is this the right way to create those many channels?
i wanted to compare the cpu usage of rabbitMQ and redis pub/sub for 100k messages and i am running the rabbitMQ server on windows.
var amqp = require("amqplib/callback_api");
var time = 0;
var limit = 100000;
amqp.connect("amqp://localhost",function(err,conn){
if(err){
console.log('Connection closed-----------error connect');
return;
}
var timer = setInterval(() => {
time+=1;
if(time>=limit){
clearInterval(timer);
}
conn.createChannel(function(err,ch){
if(err){
console.log('Connection closed-----------error createChannel');
return;
}
var q = "queue_name"+time.toString();
// console.log(q);
var msg = "this is the message string!!!";
ch.assertQueue(q,{durable: false});
ch.sendToQueue(q,new Buffer(msg),{persistent: false});
// console.log("time = "+time);
});
}, 10);
});

Cannot read property 'socket's of undefined when exporting socket.io

I'm trying to modularize my application and would like to emit different event to client on different js file. Sample code below shows that an event 'onlinestatus' will be fired from led.js. However I keep on getting the message 'Type Error: Cannot read property 'sockets' of undefined' whenever I try to emit the event from led.js. I suspect something could be wrong when I"m trying to export the io from /bin/www.
/bin/www
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var connectedClientsNum = 0;
io.sockets.on('connection', function(socket) {
console.log("client connected!");
socket.on('disconnect', function() {
console.log("Client disconnected...");
console.log("Total Clients Connected: " + --connectedClientsNum);
})
});
...
module.exports = server;
module.exports.io = io;
led.js
var io = require('../bin/www').io;
...
function toggleLed(leds, err, callback) {
/* toggle the led value */
if (leds[0].value == 0) {
leds[0].value = 1;
leds[0].save(function(err) {
if (err) {
err("update led error");
}
else {
var person= {"status": "online"};
io.sockets.emit('onlinestatus', person);
callback("update led from 0 to 1 success");
}
});
}
else {
leds[0].value = 0;
leds[0].save(function(err) {
if (err) {
err("update led error");
}
else {
var person= {"status": "offline"};
io.sockets.emit('onlinestatus', person);
callback("update led from 1 to 0 success");
}
});
}
}
You should check the Docs at socket.io and check to see if there is actually still a socket.sockets.on() function still in the socket.io framework. I'm not sure if it is still there. If you must have it working, you could try changing versions of socket.io to 0.9, which would be where I think that would work.

node.js websocket crashes when client disconnect

I am very new to NodeJS and Websockets, but i am trying to play with it.
What i do is read incoming datas from Serial port, then send these datas to a web page using websocket.
From here everything works fine.
I use node-static to serve my web page
I use ws for websocket
The problem is when a client close his browser, then my NodeJS websocket server crashes with the following error :
root#WS-SERVER-2:~/app# node socketserver.js
open serial communication
Client disconnected.
/root/node-v0.10.29/lib/node_modules/ws/lib/WebSocket.js:187
else throw new Error('not opened');
^
Error: not opened
at WebSocket.send (/root/node-v0.10.29/lib/node_modules/ws/lib/WebSocket.js:187:16)
at sendAll (/root/app/socketserver.js:30:16)
at SerialPort.<anonymous> (/root/app/socketserver.js:58:8)
at SerialPort.emit (events.js:95:17)
at Object.module.exports.raw [as parser] (/root/node-v0.10.29/bin/node_modules/serialport/parsers.js:8:13)
at Object.SerialPort.options.dataCallback (/root/node-v0.10.29/bin/node_modules/serialport/serialport.js:143:15)
at SerialPortFactory.SerialPort._emitData (/root/node-v0.10.29/bin/node_modules/serialport/serialport.js:312:20)
at afterRead (/root/node-v0.10.29/bin/node_modules/serialport/serialport.js:290:18)
at /root/node-v0.10.29/bin/node_modules/serialport/serialport.js:304:9
at Object.wrapper [as oncomplete] (fs.js:459:17)
Here is my websocket/serialport code :
var WebSocketServer = require('../node-v0.10.29/lib/node_modules/ws').Server;
var SerialPort = require('../node-v0.10.29/bin/node_modules/serialport').SerialPort;
var serialPort;
var portName = '/dev/ttyACM0';
var sendData = "";
var wss = new WebSocketServer({port: 8080});
var CLIENTS=[];
wss.on('connection', function(ws) {
CLIENTS.push(ws);
ws.on('message', function(message) {
console.log('received: %s', message);
sendAll(message);
});
ws.on('close', function() {
console.log('Client disconnected.');
});
ws.on('error', function() {
console.log('ERROR');
});
ws.send("");
});
function sendAll(message)
{
for(var i=0;i<CLIENTS.length;i++)
{
CLIENTS[i].send(message);
}
}
serialListener();
function serialListener(debug)
{
var receivedData = "";
serialPort = new SerialPort(portName, {
baudrate: 9600,
dataBits: 8,
parity: 'none',
stopBits: 1,
flowControl: false
});
serialPort.on("open", function () {
console.log('open serial communication');
// Listens to incoming data
serialPort.on('data', function(data) {
receivedData += data.toString();
if (receivedData .indexOf('E') >= 0 && receivedData .indexOf('B') >= 0) {
sendData = receivedData .substring(receivedData .indexOf('B') + 1, receivedData .indexOf('E'));
receivedData = '';
}
// send the incoming data to browser with websockets.
sendAll(sendData);
});
});
}
Can someone help me to figure out what's wrong here ?
I think, you should remove the socket from your CLIENTS array on both close and error event. Otherwise it tries to send a message to a socket that is closed.
I was having this same issue. Turned out I was attempting to send events to sockets that were in the "closing" state. Checking that each socket was specifically open before broadcasting a message fixed it for me:
function sendAll(data){
for(var i = 0; i < clients.length; i++){
if(this.clients[i].readyState != this.clients[0].OPEN){
console.error('Client state is ' + this.clients[i].readyState);
}
else{
this.clients[i].send(data);
}
}
}
Try this while sending data to client:
- socket is my current web socket object.It overwrites the default >WebSocket.js class condition that throws "not-opened error".
if (socket.readyState != socket.OPEN) {
console.error('Client state is ' + socket.readyState);
//or any message you want
} else {
socket.send(JSON.stringify(object)); //send data to client
}

NodeJs net.Socket() events not firing

Trying to write a TCP client in Node v0.10.15 and I am having a little trouble getting data back from the server. I know that the server is working properly because I have 3-4 different clients written in different languages communicating with it.
Below is a snippet of a larger piece of code but this should get the point across.
The problem is: I'm expecting 2 packets coming back after writing to the socket (this part is not included in this example). I'm only seeing the "data" event being fired once. Is there something that I need to do to get node to resume reading from the Tcp stream? I can confirm that the server is sending 2 packets(The length and then the actual data) Any help would be appreciated.
var dc = require('./DataContracts.js');
var net = require('net');
require('buffertools').extend();
var client = net.Socket();
var isConnected = false;
var serverHost = '10.2.2.21';
var dataCallback;
var receivedBuffer = new Array();
function InitComm(buffer) {
if (!isConnected) {
client.connect(4987, serverHost, function() {
client.on('data', function(data) {
console.log('Received server packet...');
var buf = new Buffer(data);
receivedBuffer.push(buf);
client.resume();
});
client.on('end', function() {
if (receivedBuffer.length > 1) {
if (dataCallback !== undefined)
dataCallback(receivedBuffer);
}
});
client.on('close', function() {
//clean up
});
client.on('error', function(err) {
console.log('Error!: ' + err);
});
Communicate(buffer);
});
} else {
Communicate(buffer);
}
}
Turns out that node was combining both of the packets together. I must be missing a Carriage return on the first packet

nodejs serialport write issues?

I am using the nodejs serialport module (https://npmjs.org/package/serialport) and I am having issues when I write to the serial port.
If I simply write to the port as shown below, the serial device never gets the command.
var serialport = require("serialport");
var sp = new serialport.SerialPort(serialPortPath);
sp.write("SYST:ADDR?\n");
However, if I use a setTimeout as shown below, then it seems to work?
var serialport = require("serialport");
var sp = new serialport.SerialPort(serialPortPath);
setTimeout(function(){sp.write("SYST:ADDR?\n")},1000);
FYI, the "serialPortPath" is set elsewhere in the code.
I am not sure what is going on... any ideas?
I think I got it figured out from the github (https://github.com/voodootikigod/node-serialport page... basically it looks like I was missing the "open" event as shown below:
serialPort.on("open", function () {
console.log("open");
serialPort.on("data", function(data) {
console.log("data received: " + data);
});
serialPort.write("SYST:ADDR?\n", function(err, results) {
console.log("err: " + err);
console.log("results: " + results);
});
});
Here is another approach which works very well and allows for dynamic addressing of a specific serial device. In my case I am only interested in connecting to the Numato device connected to our integrated system which is why I have the conditional logic in the list callback.
exports.testSerial = function(data) {
serialPort.list(function(err, ports) {
var port = {};
for(var i = 0; i < ports.length; i++) {
try {
if(typeof ports[i].manufacturer != 'undefined' && ports[i].manufacturer.includes("Numato")) {
port = ports[i];
}
} catch(err) {
console.dir(err);
}
}
// the port will be opened via the constructor of this call
var numato = new serial(port.comName, {baudrate : 19200}, function(err) {
if(err) {
return console.dir(err);
}
// by having the write call within the callback you can access it directly w/o using .on()
numato.write('relay ' + data.state + ' ' + data.channel + '\r', function(err) {
if(err) {
console.dir('error writing');
console.dir(err);
}
console.dir('serial message written');
numato.close();
});
});
return true;
});
}
Hope this helps someone in the future! For reference this is with library version 4.0.7.

Resources