How to convert the message in to a json object - json

I am using a client program called fire packets to fire some hexadecimal data on to a server program in which the server listening on a specified port. The server program works well and it receives the message from the client but need to convert the message into a json object in which results undefined when tried can any one please tell me how to do the conversion of the message into json object. Will attach the server program below,
var dgram = require('dgram');
var server = dgram.createSocket("udp4");
var fs = require('fs');
server.on("error", function(err) {
console.log("Error:" + err.stack);
server.close();
});
server.on("message", function(msg, rinfo) {
console.log("server got the message :" + msg + "from" + rinfo.address + "from the port" + rinfo.port);
fs.writeFile("packet.txt", msg.toString(), 'utf-8', function(err) {
//var jsonmess=JSON.parse(msg);
//console.log(jsonmess);
console.log("written on packet");
});
});
server.on("listening", function() {
var address = server.address();
console.log("Server listening on:" + address.address + "on the port:" + address.port);
});
server.bind(5432);
The message i send to through the client is
4500005100060000801116FB75610CFACF47D1F8501E5014003DD5C383051632426347010101020AC252F131AB52F131AB0776956F2CC65619000002CC0000000000000800005FFF970F07660001080100000032C8
When i stringify the JSON object the data has been shown as
[131,5,22,50,66,99,71,1,1,1,2,10,194,82,241,49,171,82,241,49,171,7,118,149,111,44,198,86,25,0,0,2,204,0,0,0,0,0,0,8,0,0,95,255,151,15,7,102,0,1,8,1,0,0,0,50,200]
How can i get the exact value that has been send through the client on a server json object

Related

When opening multiple clients, old client does not get updated using nodejs web socket

My goal is when I open a new browser(client), the message sent from the server in the previous client gets updated as well.
Currently,
The clients send messages to the server, the server stores them in localStorage as an array and should send it back to all the clients. All clients should get the same array of messages. It works like ajax call.
As of right now, when I open the first browser, the message is sent to the server and received in the client successfully, and then I open the second one(it works) but the message is not updated in the first browser. PS this acts like a forum, when somebody posts a messages to server, all users should be able to see it.
Here's my code for server:
<html>
<head>
<!-- This is the websocket SERVER -->
<script src="http://localhost:5000/socket.io/socket.io.js"></script>
</head>
<body>
<div id="msg"></div>
<script>
// connect to WEBSOCKET server
var socket = io.connect('http://localhost:5000',{'forceNew':true} );
// Fire an event (that the server will handle
socket.emit('myEvent', 'Hello Message from the client');
// Attach event handler for event fired by server
socket.on('server', function(data) {
var elem = document.getElementById('msg');
console.log(data);
elem.innerHTML += "<br>" + data; // append data that we got back
});
</script>
</body>
</html>
Here's for client:
//---------------------------------------------------------------
// The purpose is to introduce you to websockets
// This is a SERVER that is SEPARATE from the http server.
//
// Your webpage (in this case the index.html in this directory)
// will be SERVED by the http server. THEN, it will connect to the
// websocket server. Then - they will talk to each other!
//
// Note that in regular http - the server cannot initiate a conversation
// Here, the websocket server sends a message to the client browser.
//
// This example has THREE parts
// 1) The http server code (which is same as what we did earlier)
// 2) This code - this is the web socket server
// It prints what it got from client. It also sends a message to the
// client after every 1 second.
// 3) The html or client code. Note how it connects to the websocket
// and how it sends and receives messages
//
// To RUN THIS EXAMPLE
// First, run node httpServer.js on one terminal
// Next, run node 1_ws.js on another terminal
// Next, type localhost:4000/index.html on some browser
//
//---------------------------------------------------------------
var items=[];
var io = require('socket.io').listen(5000);
if (typeof localStorage === "undefined" || localStorage === null) {
var LocalStorage = require('node-localstorage').LocalStorage;
localStorage = new LocalStorage('./scratch');
}
io.sockets.on('connection', function(socket) {
socket.on('myEvent', function(content) {
//i need to store the content
items.push(content);
localStorage.setItem("list",JSON.stringify(items));
socket.emit('server', JSON.parse(localStorage.getItem("list")));
});
});
I'm running on the local server:( you can ignore the local server if you want, the above code can function on their own)
//---------------------------------------------------------------
// The purpose is to serve a file!
//---------------------------------------------------------------
var util = require('util');
var path = require('path');
var http = require('http');
var fs = require('fs');
var server = http.createServer();
// attach handler
server.on('request', function (req,res) {
var file = path.normalize('.' + req.url);
fs.exists(file, function(exists) {
if (exists) {
var rs = fs.createReadStream(file);
rs.on('error', function() {
res.writeHead(500); // error status
res.end('Internal Server Error');
});
res.writeHead(200); // ok status
// PIPE the read stream with the RESPONSE stream
rs.pipe(res);
}
else {
res.writeHead(404); // error status
res.end('NOT FOUND');
}
});
}); // end server on handler
server.listen(4000);
console.log("start");
You are sending response to only client who sent message to sever only,
To send to all clients which are connected you must use this,
io.emit('server', JSON.parse(localStorage.getItem("list")));
Visit this answer for all
Responses

sensor data is not uploading on artik cloud

I am trying to send sensor data to artik cloud via node.js. (using web socket and serial port). But its sending null. Anyone knows the reason? I just copied the code from tutorial so there is no syntax error.
var webSocketUrl = "wss://api.artik.cloud/v1.1/websocket?ack=true";
var device_id = "####";
var device_token = "#####";
var isWebSocketReady = false;
var ws = null;
var serialport = require("serialport");
var portName = 'COM5';
var sp= new serialport.SerialPort(portName, {
baudRate: 9600,
parser: serialport.parsers.readline("\r\n")
});
var WebSocket = require('ws');
/**
* Gets the current time in millis
*/
function getTimeMillis(){
return parseInt(Date.now().toString());
}
/**
* Create a /websocket bi-directional connection
*/
function start() {
//Create the websocket connection
isWebSocketReady = false;
ws = new WebSocket(webSocketUrl);
ws.on('open', function() {
console.log("Websocket connection is open ....");
register();
});
ws.on('message', function(data, flags) {
console.log("Received message: " + data + '\n');
});
ws.on('close', function() {
console.log("Websocket connection is closed ....");
});
}
/**
* Sends a register message to the websocket and starts the message flooder
*/
function register(){
console.log("Registering device on the websocket connection");
try{
var registerMessage = '{"type":"register", "sdid":"'+device_id+'", "Authorization":"bearer '+device_token+'", "cid":"'+getTimeMillis()+'"}';
console.log('Sending register message ' + registerMessage + '\n');
ws.send(registerMessage, {mask: true});
isWebSocketReady = true;
}
catch (e) {
console.error('Failed to register messages. Error in registering message: ' + e.toString());
}
}
/**
* Send one message to ARTIK Cloud
*/
function sendData(temperature){
try{
// ts = ', "ts": '+getTimeMillis();
var data = {
"temp": temperature
};
var payload = '{"sdid":"'+device_id+'", "data": '+JSON.stringify(data)+', "cid":"'+getTimeMillis()+'"}';
console.log('Sending payload ' + payload);
ws.send(payload, {mask: true});
} catch (e) {
console.error('Error in sending a message: ' + e.toString());
}
}
/**
* All start here
*/
start(); // create websocket connection
sp.on("open", function () {
sp.on('data', function(data) {
if (!isWebSocketReady){
console.log("WebSocket is not ready. Skip sending data to ARTIK Cloud (data:" + data +")");
return;
}
console.log("Serial port received data:" + data);
//var parsedStrs = data.split(",");
var temperature = parseInt(data);
sendData(temperature);
});
});
If you reference our First IoT Sample:
https://developer.artik.cloud/documentation/tutorials/your-first-iot-device.html
The node.js sample sends the value from the temperature sensor. As a dependency it requires a connected Arduino, Raspberry Pi, and a DHT temperature sensor located at the right pin. If you are seeing null "before" sending the data to ARTIK Cloud, you are not getting any value from the sensor.
In particular, output and print to console the "temperature" value from the following function in case of any parsing errors:
function sendData(temperature) //...
Email us at developer#artik.cloud if you need additional information.
Thanks!
In this line:
var temperature = parseInt(data);
If you're getting empty or non numeric data (you can verify this in the previous line where you're logging the variable's content), then temperature will be NaN (not a number). Then, when you build the JSON payload for Artik Cloud, you'll end up with something like:
{
"sdid": "cbd3f844967d464da3c4f4989f80f86c",
"data": {
"temp":null
},
"cid":"1495817841624"
}
Because the JSON.stringify of:
{"temp":NaN}
would be translated to:
{"temp":null}

Nodejs read JSON data from a http request chunk

I am using Jira API's to get data on single tickets. I have successfully setup a http GET request to the server and can display the data to the console however I ideally need to get certain properties from the data which is in JSON format.
When I try to read the properties I just get undefined.
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk); // This displays the JSON
console.log('endSTATUS: ' + chunk.id); // This shows up undefined
});
The data is in this format from jira API for reference.
The first console log in the res successfully displays all the data from the chunk.
The second one is:
endSTATUS: undefined
Try to get the body after the data stream finish. Like this:
var body = '';
response.on('data', function(d) {
body += d;
});
response.on('end', function() {
// Data reception is done, do whatever with it!
var parsed = JSON.parse(body);
console.log('endSTATUS: ' + parsed.id);
});
Make sure you are parsing the response data as JSON. I think you may want something like var data = JSON.parse(chunk);, and reference the chunk data as data.value.
res.on('data', function (chunk) {
var data = JSON.parse(chunk);
console.log('BODY: ' + data);
console.log('endSTATUS: ' + data.id);
});

How to send Data to the client with out client requesting the ws server in nodejs

I need to convert a csv file to json format and send it to a client requesting to ws server in nodejs ,
the file will be updated so many times so i need to send updated data to client
i am able to send data once it is loaded completely(like when app is started it sends all data in file to client) but when i update data in the file the updated data is being printed out on console but it is not being sent to client is their any thing wrong in my code
my node.js code:
var ts = require('tail-stream');
var Converter = require("csvtojson").Converter;
var converter = new Converter({constructResult:false}); //for big csv data
var WebSocketServer = require('websocket').server;
var http = require('http');
var server = http.createServer(function(request, response) {
// process HTTP request. Since we're writing just WebSockets server
// we don't have to implement anything.
response.write('hello');
console.log('in http server \n');
});
server.listen(1337, function() { });
// create the server
wsServer = new WebSocketServer({
httpServer: server
});
// WebSocket server
wsServer.on('request', function(request) {
var connection = request.accept(null, request.origin);
console.log('wsserver');
connection.send('ws server');
converter.on("record_parsed", function (jsonObj) {
console.log(jsonObj); //here is your result json object
connection.send(jsonObj);
});
var tstream = ts.createReadStream('log.csv', {
beginAt: 0,
onMove: 'follow',
detectTruncate: false,
onTruncate: 'end',
endOnError: false
});
tstream.pipe(converter);
});
Right now you are creating a new read stream and adding a listener to the converter on every new connection, that will cause trouble once you have more than one client (same event emitted multiple times, etc..). Instead of that you should keep just one reader and notify all open connections when there's a new record.
Also notice that the library you are using only accepts UTF-8 strings or binary type messages, row objects sent the way you're sending them now will be received as a "[object Object]" string after toString() is called on them. You should probably send just send the row string or use JSON.stringify / JSON.parse.
Try this:
var http = require("http");
var tailStream = require("tail-stream");
var Converter = require("csvtojson").Converter;
var WebSocketServer = require("websocket").server;
var server = http.createServer();
var wsServer = new WebSocketServer({ httpServer: server });
var converter = new Converter({constructResult:false});
var logStream = tailStream.createReadStream("log.csv", { detectTruncate : false });
var connections = [];
server.listen(1337);
logStream.pipe(converter);
//----------------------------------------------------
converter.on("record_parsed", function (jsonObj) {
connections.forEach(function(connection){
connection.send(JSON.stringify(jsonObj));
});
});
//----------------------------------------------------
wsServer.on("request", function(request) {
var connection = request.accept(null, request.origin);
connection.on("close", function() {
connections.splice(connections.indexOf(connection), 1);
});
connections.push(connection);
});
The code above works, tested like this on the client side:
var socket = new WebSocket('ws://localhost:1337/');
socket.onmessage = function (event) {
console.log(JSON.parse(event.data));
}
Note: this doesn't send the whole content of the file at the beginning, just the updates, but you can easily achieve this storing the records and sending them on new connections.

Call socket.io from dgram socket udp4

I'm having some problems with a small aplications that I'm developing.
I have an Arduino with a temperature sensor, I wanted to send the values to a nodejs service, and show it to a webpage. I wanted to use socket.io, but I'm just able to use UDP connection from arduino to server (ethernet). Just to keep the sensor value refreshed, seems that I have to call a io socket from the UDP service, but I can't.
My socket.io that works when I call it from a webpage.
var io = require('socket.io').listen(3000);
io.sockets.on('connection', function (socket) {
socket.on('message', function (message) {
console.log("Got message: " + message);
io.sockets.emit('SensorList', { 'temperature': temp });
});
});
This is the UDP service that reads the arduino packets:
var dgram = require("dgram");
var server = dgram.createSocket("udp4");
var fs = require('fs');
**var io = require('socket.io');**
var crlf = new Buffer(2);
crlf[0] = 0xD; //CR - Carriage return character
crlf[1] = 0xA; //LF - Line feed character
server.on("message", function (msg, rinfo) { //every time new data arrives do this:
console.log("server got: " + msg.readUInt16LE(0) + " from " + rinfo.address + ":" + rinfo.port); // you can comment this line out
**var socket = io.connect('http://localhost:3000');
socket.on('connect', function () {
socket.send(msg.readUInt16LE(0));
});**
});
server.on("listening", function () {
var address = server.address();
console.log("server listening " + address.address + ":" + address.port);
});
server.bind(6000); //listen to udp traffic on port 6000
The error is:
var socket = io.connect('http://localhostit.is:3000'); ^
TypeError: Object # has no method 'connect'
at Socket. (/Users/xfr/Documents/nodejs/temp1/app2.js:15:19)
at Socket.EventEmitter.emit (events.js:98:17)
at UDP.onMessage (dgram.js:437:8)
If I erase all the io part, I'm able to see the values in console.
If there is another way to mix 2 services in one.. tell me some clues and I'll do the search.
Thanks.
Made it!
2 in 1...
var http = require('http'),
dgram = require('dgram'),
socketio = require('socket.io');
var fs = require('fs');
var app = http.createServer(),
io = socketio.listen(app),
socket = dgram.createSocket('udp4');
var crlf = new Buffer(2);
crlf[0] = 0xD; //CR - Carriage return character
crlf[1] = 0xA; //LF - Line feed character
socket.on('message', function(content, rinfo) {
console.log('got message', content.readUInt16LE(0), 'from', rinfo.address, rinfo.port);
io.sockets.emit('udp message', content.readUInt16LE(0));
});
socket.bind(6000);
app.listen(8000);
On the webpage side:
src="socket.io.min.js"
src="jquery.min.js"
<script>
var socket = io.connect('http://local_host.com:8000');
socket.on('udp message', function(msg) {
console.log(msg) ;
temperature = msg/100;
$('#temperature h1').html(temperature+'°C');
});
</script>
bind/listen newbie issues.