Unhandled ''error'' event in Node.JS - javascript

I'm trying to active an RFID reader through node.js and then send the tag back.
It works great. It reads the tag, responds with an ID, then send the ID to the pinging node client.
However, every time the node.JS program picks up a set of data from an RFID tag, after it sends, it closes down with the following error:
events.js:72
throw er; // Unhandled 'error' event
^
Error: EBADF, read
This causes the node process to quit all the time. What could be the problem here?
My code is the following;
// Socket.io server details
var io = require('socket.io').listen(3000);
// Serialport plugin declared and made a serialport variable
var serialport = require("serialport");
var SerialPort = serialport.SerialPort;
// Variable containing technical USB port details
var serialPort = new SerialPort("/dev/ttyUSB0",
{baudrate: 2400, parser: serialport.parsers.readline("\n")},
false); // this is the openImmediately flag [default is true]
io.sockets.on('connection', function (socket) {
console.log('user connected');
socket.on('ping', function (data) {
serialPort.open(function () {
// Open notification
console.log('open');
//Start listening
serialPort.on('data', function(data) {
// If content is empty, filter out
if (data.trim() !== '') {
line = data;
//Execute function again, get tag, handle tag and end process
serialPort.close(function () {
console.log('De uiteindelijke tag is ' + data);
console.log('Ping received with data: ' + data);
socket.emit('pong', data);
console.log('closing');
});
console.log('hallo');
}
});
});
});
});

Add a listener to handle the error in the serial port, like the code below:
serialPort.on('error', function(error) {
console.log('The error: '+error);
//...
});

Related

Process Spawns With "stdio: 'inherit' " But Not "stdio: 'pipe' "

I'm trying to pipe the console output of a child Python process to a parent Node.js process. I'm able to spawn a Python process successfully, and the output from the Node parent process successfully is outputted live to the webpage.
However, I can't send the output from the child process (Python script). The Python script successfully launches if I use the parameter "stdio: 'inherit'", but I require "stdio: 'pipe'", to output the terminal, and for some reason it doesn't work.
Server Code
app.post('/clientwebpageoutput', function(req,res)
{
var io = require('socket.io')(http);
var child = require('child_process');
var events = require('events');
var eventEmitter = new events.EventEmitter();
eventEmitter.on('logging', function(message) {
io.emit('log_message', message);
});
io.on('connection', function(socket){
console.log('Before process begins');
var python_process = child.spawn( 'python3', ['snowboymultiplemodels.py'], {stdio: 'pipe'});
var chunk = '';
python_process.stdout.on('data', function(data){
chunk += data
socket.emit('newdata', chunk);
} );
python_process.stderr.on('data', function (data) {
console.log('Failed to start child process.');
})
});
// Override console.log
var originConsoleLog = console.log;
console.log = function(data) {
eventEmitter.emit('logging', data);
originConsoleLog(data);
};
res.render('clientwebpageoutput'); //,output);
});
Client (successfully outputs stderr):
<script src="/socket.io/socket.io.js"></script>
<script>
$(function () {
var socket = io();
socket.on('log_message', function(msg){
$('#messages').append($('<li>').text(msg));
});
});
</script>
Why does the process not spawn? The terminal always shows the error message created above in stderr ("Failed to start child process").

Cannot write from websocket server to browser app

I believe this is a simple question: I have a websocket server (index.js) that opens a serial port when the browser (index.html) is loaded. I have a scale connected via USB (COM3). From the browser I want to send commands to the scale and receive data back to the browser. My node version is v7.7.4 and npm version is 4.1.2. I have also NPM installed serialport and ws.
index.js
var SerialPort = require('serialport');// include the library
//var SerialPort = serialport.SerialPort; // make a local instance of it
var WebSocketServer = require('ws').Server;
var SERVER_PORT = 8080; // port number for the webSocket server
var wss = new WebSocketServer({port: SERVER_PORT}); // the webSocket server
var connections = new Array; // list of connections to the server
wss.on('connection', handleConnection);
// get port name from the command line:
portName = process.argv[2];
var myPort = new SerialPort(portName, {
baudRate: 9600,
// look for return and newline at the end of each data packet:
parser: SerialPort.parsers.readline("\n")
});
myPort.on('open', showPortOpen);
myPort.on('data', sendSerialData);
myPort.on('close', showPortClose);
myPort.on('error', showError);
// This function broadcasts messages to all webSocket clients
function broadcast(data) {
for (myConnection in connections) { // iterate over the array of connections
connections[myConnection].send(data); // send the data to each connection
}
}
function sendToSerial(data) {
myPort.write(" From: index.js:sendToSerial "+data);
console.log("sendToSerial (index.js): " + data);
// if there are webSocket connections, send the serial data
// to all of them:
if (connections.length > 0) {
broadcast(data);
}}
function handleConnection(client) {
console.log("New Connection"); // you have a new client
connections.push(client); // add this client to the connections array
client.on('message', sendToSerial); // when a client sends a message,
client.on('close', function() { // when a client closes its connection
console.log("connection closed"); // print it out
var position = connections.indexOf(client); // get the client's position in the array
connections.splice(position, 1); // and delete it from the array
});
}
function showPortOpen() {
console.log(portName+' port open. Data rate: ' + myPort.options.baudRate);
}
function sendSerialData(data) {
myPort.write(" From: index.js:sendSerialData "+data);
myPort.write("sendSerialData "+data);
console.log("sendSerialData "+data);
}
function showPortClose() {
console.log('port closed.');
}
function showError(error) {
console.log('Serial port error: ' + error);
}
and index.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.8/p5.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.8/addons/p5.dom.js"></script>
<script type="text/javascript">
var text; // variable for the text div you'll create
var socket = new WebSocket("ws://localhost:8080");
function setup() {
// The socket connection needs two event listeners:
socket.onopen = openSocket;
socket.onmessage = showData;
// make a new div and position it at 10, 10:
text = createDiv("xxSensor reading:");
text.position(10,10);
}
function openSocket() {
text.html("Socket open");
socket.send("Hello websocket server - from index.html");
}
function showData(result) {
// when the server returns, show the result in the div:
text.html("Sensor reading: " + result.data);
xPos = int(result.data); // convert result to an integer
text.position(xPos, 10); // position the text
}
I have tried SERVER_PORT = 8081 with the same results.
I am able to see info from index.html in the cmd "node index.js COM3" but the command myPort.write does not get to the index.html browser.
I get:
C:\Users\pmfoo\nodeSerialExample>node index.js COM3
COM3 port open. Data rate: 9600
New Connection
sendToSerial (index.js): Hello websocket server - from index.html
sendSerialData 277.5 g
sendSerialData
where 277.5 g is the output from the scale on COM3.
and in the browser:
Sensor reading: Hello websocket server - from index.html
I followed Tom Igoe's tutorial https://itp.nyu.edu/physcomp/labs/labs-serial-communication/lab-serial-communication-with-node-js/ with only partial results. I cannot write from index.js to index.html nor can I send a command via index.js to the scale. This scale command ("ON" or "OFF" or "PSN") is seen by index.js. Can anyone help me solve these 2 communication problems?

Yii2 send event from php to clients using yii2-nod-socket

I am using yii2-node-socket to send event to clients in a concrete room. I followed all steps to install the extension in my project, the server was started successfully and the client was connected to socket but when I tried to send event from php code the client did not receive any data.
Javascript code:
var socket = new YiiNodeSocket();
socket.onConnect(function () {
socket.room('testRoom').join(function (success, numberOfRoomSubscribers) {
// success - boolean, numberOfRoomSubscribers - number of room members
// if error occurred then success = false, and numberOfRoomSubscribers - contains error message
if (success) {
console.log(numberOfRoomSubscribers + ' clients in room: testRoom');
// do something
// bind events
this.on('join', function (newMembersCount) {
// fire on client join
});
this.on('data', function (data) {
// fire when server send frame into this room with 'data' event
console.log('in data : ', data);
});
} else {
// numberOfRoomSubscribers - error message
alert(numberOfRoomSubscribers);
}
});
});
PHP code:
// create frame
$frame = Yii::$app->nodeSocket->getFrameFactory()->createEventFrame();
// set event name
$frame->setEventName('data');
// set room name
$frame->setRoom('testRoom');
// set data
$frame['key'] = 'hello';
// send
$frame->send();

SocketIO, can't send emit data from client

I'm having the most odd problem trying to send data from a client browser to my node server using SocketIO. Sending from server to client works just fine, but the other way around I get an undefined error. Here's a quick bit of what it looks like, super simple.
Node Server (app.js)
io.on("connection", function(socket) {
socket.on("pageReady", function(data) {
console.log('pageReady called');
console.log(data);
return socket.emit('newline', '###SOCKET STARTED###');
});
socket.on("disconnect", function() {
return console.log('disconnected');
});
});
Browser (client.js)
var socket;
socket = io.connect("http://localhost:5678");
socket.on("newline", function(data) {
return $('#socketData').append('<li>' + data + '</li>');
});
socket.emit("pageReady", "test");
Super simple, right? Nothing special. When I emit from server, works fine, however when the client calls "pageReady". node responds with this.
/Volumes/HOME/Users/user/git/sockettest/app.js:89
console.log(data);
^
ReferenceError: data is not defined
Data should be returning "test", but isn't. What am I doing wrong?
Your client should listen for the socket connection before attempting to emit to it:
var socket = io.connect("http://localhost:5678");
socket.on("newline", function(data) {
return $('#socketData').append('<li>' + data + '</li>');
});
socket.on("connect", function() {
socket.emit("pageReady", "test");
});

Node.js calling a function from script to update UI

Here is my webserver:
var net = require('net');
var server = net.createServer(function(socket) {
socket.write('hello\n');
socket.write('world\n');
//RECEIVE PACKET ON SOCKET
socket.on('data', function(data) {
//socket.write(data);
//console.log(data);
testSocketData(data)
});
});
server.listen(8000);
And the method testSocketData(data) is located in file update_ui.js and does the following:
function testSocketData(test) {
$('#p1').text(test)
}
Where #p1 refers to the id of a paragraph element in my main.html. I know that my socket is working, however I get:
ReferenceError: testSocketData is not defined.
How can I simply pass off the data received from my node.js server to the rest of my web application?
You must move that method(with socket.on('data') as well) from the server to the client side. When you receive a message via socket, the p1 element will update its text too.
On the server you will still need to have a socket.on('data') to receive the messages from the client.
Edit:
Here is some code, a little bit changed from my comment below.
On server:
function computeSomeResults(data) {
// your logic here
}
socket.on('servermsg', function(data) {
var result = computeSomeResults(data);
socket.emit('clientmsg', result);
});
On client:
function testSocketData(test) {
$('#p1').text(test);
}
socket.on('clientmsg', function(data) {
testSocketData(data);
// emit something maybe?
}
Eventually, you may want to send something to the server:
$('#p1').on('click', function(){
socket.emit('servermsg', $(this).text());
});

Categories

Resources