I m trying to Send serial data to Arduino using Node.js and Socket.io and my code.
and the html page have only one button. its work node and html side .but this is not send serial data.
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;
server.listen(port, function () {
// console.log('Server listening at port %d', port);
});
// Routing
app.use(express.static(__dirname + '/public'));
var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort("/dev/ttyACM3", {
baudrate:9600
}, false); // this is the openImmediately flag [default is true]
io.on('connection', function (socket) {
socket.on('my other event', function (data) {
console.log(data);
serialPort.open(function () {
console.log('open');
serialPort.on('data', function (data) {
console.log('data received: ' + data);
});
serialPort.write(data, function (err, results) {
console.log('err ' + err);
console.log('results ' + results);
});
});
});
});
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
Sending serial messages to the Arduino is not as easy as simply passing in a String. Unfortunately you have to send the String character by character which the Arduino will receive and concatenate back to a String. After you sent the last character you need to send one final new line character (/n) which is a signal for the Arduino to stop concatenating and evaluate the message.
This is what you need to do in your Node.js server:
// Socket.IO message from the browser
socket.on('serialEvent', function (data) {
// The message received as a String
console.log(data);
// Sending String character by character
for(var i=0; i<data.length; i++){
myPort.write(new Buffer(data[i], 'ascii'), function(err, results) {
// console.log('Error: ' + err);
// console.log('Results ' + results);
});
}
// Sending the terminate character
myPort.write(new Buffer('\n', 'ascii'), function(err, results) {
// console.log('err ' + err);
// console.log('results ' + results);
});
});
And this is the Arduino code that receives this:
String inData = "";
void loop(){
while (Serial.available() > 0) {
char received = Serial.read();
inData.concat(received);
// Process message when new line character is received
if (received == '\n') {
// Message is ready in inDate
}
}
}
Related
Hello I'm trying to create a chat application, I googled around and I got some issues on this step. Would appreciate some help...
Server.js
var express = require("express");
var app = express();
var http = require("http").createServer(app);
var io = require("socket.io")(http);
var users = [];
io.on("connection", function (socket) {
console.log("User connected", socket.id);
socket.on("user_connected", function (username) {
users[username] = socket.id;
io.emit("user_connected", username);
});
socket.on("send_message", function (data) {
var socketId = users[data];
io.to(socketId).emit("new_message", data);
console.log(data);
});
});
http.listen(3000, function () {
console.log("Server Started");
});
chat.php
function sendMessage(){
var message = document.getElementById("message").value;
io.emit("send_message", {
sender: sender,
message: message
});
return false;
}
io.on("new_message", function (data) {
console.log(data);
//var html = "";
//html += "<li>" + data.sender + " says: " + data.message + "</li>";
//document.getElementById("messages").innerHTML += html;
});
So my problem is happening in chat.php where my console.log(data) isn't shown, however the data is shown in server.js. Why is this currently not working?
From what you said earlier it's possible that you make it more complicated than it actually is. No need to change anything in chat.php, however instead of creating the variable socketId you could just emit the data immediately like this:
io.on("connection", function (socket) {
console.log("User connected", socket.id);
socket.on("user_connected", function (username) {
users[username] = socket.id;
io.emit("user_connected", username);
});
socket.on("send_message", function (data) {
io.emit("new_message", data);
});
});
I'm new to node, and trying to write the most minimal tcp client that sends raw hexadecimal data. if I should use a buffer then how? if I can send hex as string then how? would really appreciate guidance!
heres the current, not working code:
var hexVal = `504f5354202f6c696e653320485454502f312e310d0a557365722d4167656e743a206e6f64652d6170700d0a4163636570743a202a2f2a0d0a686f73743a203139322e3136382e31342e39343a333030300d0a636f6e74656e742d747970653a206170706c69636174696f6e2f6a736f6e0d0a636f6e74656e742d6c656e6774683a2031390d0a436f6e6e656374696f6e3a20636c6f73650d0a0d0a227b757365726e616d653a202776616c277d22` // my raw hex, unwantendly sent as string
var net = require('net');
var HOST = '192.168.14.94';
var PORT = 3000;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write(hexVal);
});
client.on('data', function(data) { // 'data' is an event handler for the client socket, what the server sent
console.log('DATA: ' + data);
client.destroy(); // Close the client socket completely
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});
server:
nc -lvp 3000
This solved it:
var bytesToSend = [0x50, 0x4f, ...],
hexVal = new Uint8Array(bytesToSend);
There is a more convenient way to do what you want, given a hex string send it as raw bytes.
Currently you're using a Uint8Array for which each byte needs to be encoded as 0x41 or something.
However, given a hex string, you can prepare a raw hex buffer as such:
const hexString = "41424344";
const rawHex = Buffer.from(hexString, 'hex');
And then you can write the buffer to the socket:
let client = new net.Socket();
client.connect(PORT, IP, () => {
console.log("Connected");
client.write(rawHex); //This will send the byte buffer over TCP
})
Hope this helps
you need to set server first !!!
then and only then client can connect to it ...
var net = require('net');
var config = {
host: 'localhost',
port: 3000
};
// var hexVal = `POST /line3 HTTP/1.1
// User-Agent: node-app
// Accept: */*
// host: 192.168.14.94:3000
// content-type: application/json
// content-length: 19
// Connection: close
// "{username: 'val'}"`
var hexVal = `504f5354202f6c696e653320485454502f312e310d0a557365722d4167656e743a206e6f64652d6170700d0a4163636570743a202a2f2a0d0a686f73743a203139322e3136382e31342e39343a333030300d0a636f6e74656e742d747970653a206170706c69636174696f6e2f6a736f6e0d0a636f6e74656e742d6c656e6774683a2031390d0a436f6e6e656374696f6e3a20636c6f73650d0a0d0a
227b757365726e616d653a202776616c277d22` // my raw hex, unwantendly sent as string
var move = {
forward: hexVal,
backward: 'READER_BWD'
};
///////////////////////////////////////////////////////////////////////////////////
/* server code */
let server = net.createServer((client) => {
console.log('client connected');
client.on('data', data => {
console.log(data.toString());
client.write('ACK')
})
client.on('end', () => console.log('ended session'))
})
server.listen(3000)
//////////////////////////////////////////////////////////////////////////////
/* client code */
var client = new net.Socket();
client.connect(3000, 'localhost', function () {
console.log('connected to ' + config.host + ':' + config.port);
client.write(move.forward, function () {
console.log('move forward command sent');
});
});
client.on('data', function (data) {
var str = data.toString();
if (str === 'ACK') {
console.log('ACK received');
client.write(move.backward, function () {
console.log('move backward sent');
client.end();
});
}
});
client.on('end', () => {
console.log('disconnected from server');
});
client.on('error', function (err) {
console.log('Error : ', err);
});
client.on('close', function () {
console.log('socket closed');
});
you can even split code of server and client in two separate files too...
then first start server and then start client
I was using net module to build a simple server/client example. The client side just send a simple message after connection is built, and server side didn't do anything but just print some log, but after that I found the data event in client side got triggered, and the data received is the data it send to the server (but server didn't write anything to client).
Client.js:
var net = require('net');
var port = 3540;
var hostName = "127.0.0.1";
var client = new net.Socket();
client.connect(port, hostName, function() {
console.log("Connected to the remote host: " + hostName + ":" + port);
client.write("hello,world");
client.end();
});
var bytesReceived = 0;
client.on('data', function(data) {
bytesReceived += data.length;
console.log('Received bytes: ' + data.length + ', total bytes received: ' + bytesReceived);
console.log(data.toString())
})
client.on('error', function(error) {
console.log(error);
client.destroy();
});
client.on('close', function() {
console.log('Closed connection');
})
server.js:
var net = require('net');
port = 3540;
var log = function(who, what) {
return function() {
var args = Array.prototype.slice.call(arguments);
console.log('[%s on %s]', who, what, args);
};
};
var count = 0
var echo = function (socket) {
socket.on('end', function() {
console.log('recevied a FIN packet');
socket.end();
});
socket.on('data', function(data) {
console.log(count + ': received bytes: ' + data.length);
count++;
});
socket.on('error', function(error) {
console.log(error);
socket.destroy();
});
socket.on('close', function() {
console.log('connection has been closed!');
});
socket.pipe(socket);
}
var server = net.createServer(echo);
server.listen(port); // port or unix socket, cannot listen on both with one server
server.on('listening', function() {
var ad = server.address();
if (typeof ad === 'string') {
console.log('[server on listening] %s', ad);
} else {
console.log('[server on listening] %s:%s using %s', ad.address, ad.port, ad.family);
}
});
server.on('connection', function(socket) {
server.getConnections(function(err, count) {
console.log('%d open connections!', count);
});
});
server.on('close', function() { console.log('[server on close]'); });
server.on('err', function(err) {
console.log(err);
server.close(function() { console.log("shutting down the server!"); });
});
After that the client print out:
Connected to the remote host: 127.0.0.1:3540
Received bytes: 11, total bytes received: 11
hello,world
Closed connection
but server didn't write anything to client
It does:
socket.pipe(socket)
This will echo the data received from the client (represented by socket) back to the client.
I want to be able to load these 4 functions: returnAvailable, processMessage, removeUser and joinRoom from an external file, but i get reference errors where it says that socket and nicknames are undefined. How do I modularize my app with respect to dependencies I use?
Here's my code:
server.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
// mongoDB init
var mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27017/chat");
var Message = require('./server/datasets/message');
//include these 4 functions
var util = require('./server/util/util');
//object which contains all users and chatrooms
var nicknames = {
'Music': [],
'Videogames': [],
'Sports': [],
'TV': [],
'Politics': []
};
// middleware
// serves static files
app.use('/client', express.static(__dirname + '/client'));
app.use('/node_modules', express.static(__dirname + '/node_modules'));
// routes
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html')
});
app.get('/api/rooms/get', function(req, res){
res.json(nicknames);
});
server.listen(2000);
// socket functionality
io.sockets.on('connection', function(socket){
socket.on('new user', util.returnAvailable);
// do when 'send message' data is received from client
socket.on('send message', function(data){
util.processMessage(data);
});
// do when 'disconnect' data is received from the client
socket.on('disconnect', function(data){
util.removeUser();
});
socket.on('leave room', function(){
util.removeUser();
});
});
util.js
module.exports.returnAvailable = function (data, callback){
console.log(data);
if(nicknames[data.room].indexOf(data.username) != -1){
callback({ bool: false });
}else {
socket.nickname = data.username;
joinRoom(socket, data.room);
nicknames[data.room].push(socket.nickname);
console.log(nicknames[data.room]);
io.sockets.to(data.room).emit('usernames', nicknames[data.room]);
callback({ bool: true, nickname: socket.nickname});
}
}
module.exports.removeUser = function(){
//console.log(socket.nickname + " disconnected. Bool value: " + socket.nickname==true);
if(socket.nickname==false) return;
// socket.room has to be defined, otherwise crashes if user reloads while not in a roomn
if(socket.room)
{
nicknames[socket.room].splice(nicknames[socket.room].indexOf(socket.nickname), 1);
socket.leave(socket.room);
}
io.sockets.to(socket.room).emit('usernames', nicknames[socket.room]);
}
module.exports.joinRoom = function (data){
socket.join(data);
socket.room = data;
console.log(socket.room);
var query = Message.find({room: socket.room});
query.sort({created:-1}).limit(5).exec(function(err, results){
if(err) { console.log(err); }
else if(results){
io.sockets.to(socket.room).emit('old messages', results);
}
});
}
module.exports.processMessage = function(data){
io.sockets.to(socket.room).emit('new message', {msg : data, nick : socket.nickname});
var message = new Message({
created: new Date,
user: socket.nickname,
message: data,
room: socket.room
});
message.save(function(err){
if(err){
console.log(err);
}else{
console.log('Successfully saved.');
}
});
}
I'm using Express 4.13.4
The socket variable is only available within io.sockets.on('connection', callback function so you can't use it in other files this easily. But you can pass the socket variable to the function where you are trying to use it like this
util.removeUser(socket);
and change the definition of removeUser to accept the socket as an argument
module.exports.removeUser = function(socket){
// your code here
}
The same goes for nicknames variable, use it like this
socket.on('new user', function(data) {
util.returnAvailable(io, socket, nicknames, data);
});
and change the function to accept those arguments
module.exports.returnAvailable = function (io, socket, nicknames, data){
// your code here
}
I have two commands to send to server, first move forward, get the acknowledgment and then send next command move backward. I have written two separate java script files do achieve this. Can it is possible to write in single function. I am trying below code but only move forward command is sent to server.
var net = require('net');
var HOST = '127.0.0.1';
var PORT = 1850;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('READER_FWD');
//client.end();
});
client.on('data', function(data) {
console.log('DATA: ' + data);
//client.destroy();
//
if (data == 'ACK')
{
console.log('DATA1: ' + data);
client.end();
console.log('DATA2: ' + data);
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
client.write('READER_BWD');
//client.end();
console.log('DATA3: ' + data);
});
}
client.end();
});
client.on('end', function() {
console.log('disconnected from server');
});
client.on('error', function(err) {
console.log(err)
});
I have updated the code, as you rightly pointed out connection is getting close while writing, i have added some delay.
var net = require('net');
var config = {
host: '127.0.0.1',
port: 1850
};
var move = {
forward: 'READER_FWD',
backward: 'READER_BWD'
};
var client = new net.Socket();
client.connect({
host: config.host,
port: config.port
}, function () {
console.log('connected to ' + config.host + ':' + config.port);
client.write(move.forward, function () {
console.log('move forward command sent');
});
});
client.on('data', function (data)
{
var str = data.toString();
if (str === 'ACK')
{
setTimeout(function()
{
console.log('ACK received');
client.write(move.backward, function ()
{
console.log('move backward sent');
client.end();
});
}, 3000);
}
});
client.on('error', function (err) {
console.log('Error : ', err);
});
client.on('close', function () {
console.log('socket closed');
});
You don't have to end your socket and re-open it again in your 'data' listener. You can keep the same socket.
Here is my client.js file which sends the commands:
var net = require('net');
var config = {
host: '127.0.0.1',
port: 1850
};
var move = {
forward: 'READER_FWD',
backward: 'READER_BWD'
};
var client = new net.Socket();
client.connect({
host: config.host,
port: config.port
}, function () {
console.log('connected to ' + config.host + ':' + config.port);
client.write(move.forward, function () {
console.log('move forward command sent');
});
});
client.on('data', function (data) {
var str = data.toString();
if (str === 'ACK') {
console.log('ACK received');
client.write(move.backward, function () {
console.log('move backward sent');
client.end();
});
}
});
client.on('error', function (err) {
console.log('Error : ', err);
});
client.on('close', function () {
console.log('socket closed');
});
The connect() method connects the socket to the server and send the forward command to it. It's exactly the same as yours.
Then, the problem comes from your 'data' listener. Your data listener must do the following things (as you mentionned in your description):
Get data from the server
If it's the ACK message: send the backward command
Then, close the connection (if needed; if not, keep it alive)
Be careful to the following point: the Socket nodejs documentation for the event 'data' says that we are receiving a Buffer. So you need to convert it to a String to compare with another String, using for this the .toString() method of the Buffer.
Thus, as is the Nodejs net.Socket is used with events, I don't think it is possible to send the forward command, listen to the 'data' event and send the backward command.
First, it is not a good idea, because you will put the on 'data' listener after the connection and it is possible that you will miss some data!
Secondly, as it is event based, you should create your architecture that follows the process :)
Below is my code for the server:
var net = require('net');
var port = 1850;
var move = {
forward: 'READER_FWD',
backward: 'READER_BWD'
};
var server = net.createServer(function (client) {
console.log('client connected');
client.on('end', function () {
console.log('client disconnected');
});
client.on('data', function (data) {
var str = data.toString();
if (str === move.forward) {
console.log('move forward command received');
client.write('ACK', function () {
console.log('ACK sent');
});
} else if (str === move.backward) {
console.log('move backward command received: do nothing...');
} else {
console.log('unknown received message: ', str);
}
});
});
server.listen(port, function () { //'listening' listener
console.log('server bound on port: ' + port);
});
Here are also the outputs if needed:
Server:
server bound on port: 1850
client connected
move forward command received
ACK sent
move backward command received: do nothing...
client disconnected
Client:
connected to 127.0.0.1:1850
move forward command sent
ACK received
move backward sent
socket closed
I hope it answers the question. Feel free to ask if there is anything.