I am using neo 6m gps module with raspberry pi 3 , i have attached it on serial port ttyAMA0 , but it reads data for only small time and then port closes automatically , and sometime the data is also corrupt which causes gps.js module to throw an error.
Execution Demo screenshot.
Below is my node js script:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var file = '/dev/ttyAMA0';
const SerialPort = require('serialport');
const parsers = SerialPort.parsers;
const parser = new parsers.Readline({
delimiter: '\r\n'
});
const port = new SerialPort(file, {
baudRate: 9600
});
port.pipe(parser);
var GPS = require('../../gps.js');
var gps = new GPS;
gps.on('GGA', function(data) {
io.emit('position', data);
console.log("Latitiude :", data.lat);
console.log("Longitude :", data.lon);
});
app.get('/', function(req, res) {
res.sendFile(__dirname + '/maps.html');
});
http.listen(3000, function() {
console.log('listening on *:3000');
});
port.on('data', function(data) {
gps.updatePartial(data);
});
process.on('unhandledRejection', function (reason, p) {
//I just caught an unhandled promise rejection, since we already have fallback handler for unhandled errors (see below), let throw and let him handle that
console.log("=============");
console.log(reason);
console.log("=============");
return;
});
process.on('rejectionHandled', () => {});
process.on('uncaughtException', function (error) {
console.log(error);
});
port.on('close', function(data) {
console.log("Port closed");
console.log(port.binding);
});
Output screenshot
I solved the problem by reinstalling the raspbian, OS was closing the port for some reason
Related
Solution
Change
var server = app.listen(3000);
To
var server = app.listen(process.env.PORT || 5000);
I want to deploy an game made with JavaScript on Heroku.
Here's my server:
var express = require('express');
var app = express();
var server = app.listen(3000);
var socket = require('socket.io');
var io = socket(server);
app.use(express.static('public'));
var connectedPlayers = {};
console.log("Server is running!");
io.on('connection',
function (socket) {
socket.on('newPlayer',
function (data) {
console.log("New player connected - ID: " + data.id);
connectedPlayers[socket.id] = {
idOnline: socket.id,
idOffline: data.id,
x: data.w,
y: data.h
};
socket.emit('allPlayers', connectedPlayers);
socket.broadcast.emit('newPlayer', connectedPlayers[socket.id]);
});
socket.on('move',
function (data) {
connectedPlayers[socket.id].x = data.x;
connectedPlayers[socket.id].y = data.y;
socket.broadcast.emit('move', connectedPlayers[socket.id]);
});
socket.on('message',
function (data) {
message = {
name: data.name,
message: data.message,
messageId: generateId()
};
socket.broadcast.emit('message', message);
});
socket.on('emote',
function (data) {
message = {
emote: data.emote,
id: socket.id
}
socket.broadcast.emit('emote', message);
});
socket.on('disconnect', function () {
delete connectedPlayers[socket.id];
io.emit('remove', socket.id);
});
});
This work's fine locally, but when I deploy to heroku I get this error message:
2018-11-23T21:04:18.009491+00:00 app[web.1]: /app/server.js:33
2018-11-23T21:04:18.009512+00:00 app[web.1]: connectedPlayers[socket.id].x = data.x;
2018-11-23T21:04:18.009514+00:00 app[web.1]: ^
2018-11-23T21:04:18.009516+00:00 app[web.1]:
2018-11-23T21:04:18.009518+00:00 app[web.1]: TypeError: Cannot set property 'x' of undefined
I understand that heroku is not recognizing the "connectedPlayers" array at that index, but how this can work properly locally?
What's wrong with the socket.id property?
PS.: the socket.id it's sended by the client, but I think that's generated after a client establish an connection with the server right?
After looking for a lot of solutions, I was trying crazy things to insert the:
process.env.PORT || 5000
on the server.listen.
As you can see in the code of the question, I've posted an out of date code, with the following line (my first try):
var server = app.listen(3000);
The solution was simplier than I thought, just changing the above line of code to:
var server = app.listen(process.env.PORT || 5000);
I tried to build a chat box server by node.js. When the browser requestes the page, it workes well at first. But when I refresh the page, the Server crashes.
Below is the error message:
events.js:183
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at _errnoException (util.js:1022:11)
at TCP.onread (net.js:615:25)
I used the node --inspect index.js, but could not find the point.
Below is the code of index.js:
const http = require('http');
const fs = require('fs');
const extract = require('./extract');
const wss = require('./websockets-server');
var handleError = function (err,res) {
res.writeHead(404);
res.end();
}
var server = http.createServer(function (req, res) {
console.log("Responding to a request.");
var filePath = extract(req.url);
console.log("filePath:"+filePath);
fs.readFile(filePath,function (err,data) {
if(err){
handleError(err,res);
return;
}else {
res.end(data);
}
})
})
server.listen(3000);
When I comment the 4th line, the import of websockets-server. Server works well when I refresh the page. Maybe it's about the websocket while it works without websocket.
Below is code of websockets-server.js:
const WebSocket = require('ws');
var WebSocketServer = WebSocket.Server;
var port = 3001;
var ws = new WebSocketServer({
port:port
});
var message = [];
console.log('websockets server started');
ws.on('connection', function (socket) {
console.log('client connection established');
message.forEach(function (msg) {
socket.send(msg);
})
socket.on('message', function (data) {
console.log('message received: ' + data);
message.push(data);
ws.clients.forEach(function (clientSocket) {
clientSocket.send(data);
});
});
});
Does the problem is about the websocket? Whether should I do process when the client shutdown the connection with the server while refreshing the page.
extract.js below:
const path = require('path');
var extractFilePath = function (url) {
var filePath;
var fileName = 'index.html';
if(url.length > 1){
fileName = url.substring(1);
}
console.log('The fileName is: ' + fileName);
filePath = path.resolve(__dirname, 'app', fileName);
return filePath;
}
module.exports = extractFilePath;
I guess that you maybe execute var ws = new WebSocket("ws://localhost:3001"); in html file. I haven't figured out exact reason about your error as I'm not proficient in WebSocket. But there is a solution:
window.onbeforeunload = function () {
ws.close();
}
close connection before reload, then the error will not reappear.
You need to add an error listener on the socket. Error listener only on the websocket instance does not help in this case.
socket.on('error', function(e){
console.log(e);
});
The ECONNRESET error means that the other side (browser) closed the connection abruptly. On browser refresh, browser simple killed the connection with the websocket server.
To solve this, you have to listen for the error event on the websocket server instance.
// listen for "error" event so that the whole app doesn't crash
wss.on("error", function(error){
console.log(error);
}
I was having the same problem, but it resolved after this command:
npm install #ionic/app-scripts#nightly --save-dev
Using node js I'm calling external script in MATLAB and Python
That is working well using terminal commands to run the scripts using those application ('start')
But when I'm trying to close them using kill() ('stop') I get an error:
TypeError: exec.kill is not a function
I'm using MAC OS and this is my code:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
var path = require('path');
const exec = require('child_process').exec;
var cmd1 =
'/Applications/MATLAB_R2016b.app/bin/matlab -nojvm < /Users/dorsimon/Desktop/liftrack/Testing_Classifier.m';
var cmd2 = 'python /Users/dorsimon/Desktop/liftrack/arduino_sampling_for_workout.py';
app.get('/', function(req, res) {
res.sendfile('index.html');
});
//Whenever someone connects this gets executed
io.on('connection', function(socket) {
console.log('A user connected');
fs.watch('/Users/dorsimon/Desktop/liftrack/result/', function(event, test) {
console.log('event is: ' + event);
fs.readFile('/Users/dorsimon/Desktop/liftrack/result/results.csv', 'utf-8', function read(
err,
data
) {
if (err) {
console.log('err');
throw err;
}
console.log(data);
socket.send(data);
});
});
fs.watch('/Users/dorsimon/Desktop/liftrack/go', function(event, test) {
console.log('event is: ' + event);
fs.readFile('/Users/dorsimon/Desktop/liftrack/go/go.csv', 'utf-8', function read(err, data) {
if (err) {
console.log('err');
throw err;
}
console.log(data);
socket.send(data);
});
});
//Whenever someone disconnects this piece of code executed
socket.on('disconnect', function() {
console.log('A user disconnected');
});
socket.on('start', function() {
exec(cmd1, function(error, stdout, stderr) {
// command output is in stdout
});
exec(cmd2, function(error, stdout, stderr) {
// command output is in stdout
});
});
socket.on('stop', function() {
exec.kill();
});
});
http.listen(3000, function() {
console.log('listening on *:3000');
});
How can I kill those child_process that I started?
Thanks
Dor
You need to store the return value of exec and call kill on that. You can store those values as properties on socket for convenience:
socket.on('start', function() {
socket.child1 = exec(cmd1, function(error, stdout, stderr) {
// command output is in stdout
});
socket.child2 = exec(cmd2, function(error, stdout, stderr) {
// command output is in stdout
});
});
socket.on('stop', function() {
socket.child1.kill();
socket.child2.kill();
});
FWIW, you probably have to do the same with the return values of fs.watch(), and call close() on them when the socket gets closed, otherwise you'll probably run into issues after your server has been running for a while (it creates two watchers for each socket.io connection, but doesn't remove them, so they'll linger).
I have the simple node.js server that receives udp packages and prints them in the console:
var PORT = 19777;
var MULTICAST_GROUP = "224.0.0.251";
var dgram = require("dgram");
var payload = new Buffer('A wild message appears');
var client = dgram.createSocket("udp4");
client.on("message", function(message, rinfo) {
console.log("received: ",message);
});
client.on("listening", function() {
console.log("listening on ",client.address());
client.setBroadcast(true);
client.setTTL(64);
client.setMulticastTTL(64);
client.setMulticastLoopback(true);
client.addMembership(MULTICAST_GROUP);
client.send(payload, 0, payload.length, PORT, MULTICAST_GROUP, function(err,bytes) {
console.log("err: "+err+" bytes: "+bytes);
// client.close();
});
});
client.on("close", function() {
console.log("closed");
});
client.on("error", function(err) {
console.log("error: ",err);
});
client.bind(19777);
it works remotely on my server. I want to present the received data to each client that will turn on his browser and enter the address of my server. How could I do that?
I am trying to close a http server associated with a socket.io instance, using mySocketIoInstance.close(), but I am getting the following error:
Uncaught TypeError: Object #<Server> has no method 'close'
at Socket.<anonymous> (/home/jackson/projects/tcg/test/server/ServerLobbySpec.js:35:20)
at Socket.Emitter.emit (/home/jackson/projects/tcg/node_modules/socket.io-client/node_modules/component-emitter/index.js:134:20)
at Socket.emit (/home/jackson/projects/tcg/node_modules/socket.io-client/lib/socket.js:128:10)
at Socket.onconnect (/home/jackson/projects/tcg/node_modules/socket.io-client/lib/socket.js:306:8)
at Socket.onpacket (/home/jackson/projects/tcg/node_modules/socket.io-client/lib/socket.js:206:12)
at Manager.<anonymous> (/home/jackson/projects/tcg/node_modules/socket.io-client/node_modules/component-bind/index.js:21:15)
at Manager.Emitter.emit (/home/jackson/projects/tcg/node_modules/socket.io-client/node_modules/component-emitter/index.js:134:20)
at Manager.ondecoded (/home/jackson/projects/tcg/node_modules/socket.io-client/lib/manager.js:270:8)
at Decoder.<anonymous> (/home/jackson/projects/tcg/node_modules/socket.io-client/node_modules/component-bind/index.js:21:15)
at Decoder.Emitter.emit (/home/jackson/projects/tcg/node_modules/socket.io-client/node_modules/socket.io-parser/node_modules/emitter/index.js:132:20)
Here's where I'm trying to close it:
'use strict';
var http = require('http'),
expect = require('chai').expect,
socketIo = require('socket.io'),
socketIoClient = require('socket.io-client'),
ServerLobby = require('../../source/server/ServerLobby');
describe('ServerLobby', function () {
var port = 2468,
uri = 'http://localhost:' + port;
describe('is connectable', function () {
it('should connect', function (done) {
var httpServer = http.Server().listen(port),
io = socketIo(httpServer),
lobby = new ServerLobby(io),
socket = socketIoClient(uri + lobby.namespace);
socket.on('connect', function () {
// HERE
io.close();
// HERE
done();
});
});
});
});
I tried commenting-out the lobby and socket code and just console.log'd io.close and got undefined.
My version is 1.0.6. According to socket.io/test/socket.io.js (also 1.0.6), I should be able to close the server in the following way:
var http = require('http').Server;
var io = require('..');
var expect = require('expect.js');
// ...
it('should be able to close sio sending a srv', function() {
var PORT = 54016;
var srv = http().listen(PORT);
var sio = io(srv);
var clientSocket = client(srv, {
reconnection: false
});
clientSocket.on('connect', function init() {
expect(sio.nsps['/'].sockets.length).to.equal(1);
// HERE
sio.close();
// HERE
});
});
My setup looks almost exactly like that. Please advise.
In the examples and in the test you have included, it shows a socket.io object being constructed with a server object that has been initialized in a different manner.
Try this:
var http = require('http').Server,
// ...
var httpServer = http().listen(port);
Full example taken from link at time of posting:
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});