get data from mqtt broker -6lbr - javascript

I followed this tutorial :
Running the CC26xx Contiki Examples
but instead of using the cc26xx-demo I used the cc26xx-web-demo and successfully manged to get everything up and running and I can access the 6lbr web page, when I access the sensorTag page I see a mqtt configuration page as shown:
and if I click index in the sensorTag page (pic above) I get to see the data:
the question is , how can I write a simple nodejs js file that uses the mqtt broker information to grab all the sensorTag sensors data and save it in an local object.
I tried to do run this example but no luck
var mqtt = require('mqtt')
client = mqtt.createClient(1883, '192.168.1.109');
client.subscribe(what do I write here);
client.on('message', function(topic, message) { console.log(message); });
I don't know what I'm doing wrong
UPDATE:
mqtt configuration page :
javascript file :
and I run the js with node and listen on port 1883:
tcpdump seems to detect mqqt packets on 1883 port but I can't to seem to be able to console.log the sensor data when I run the js file with node ??
I went on the contiki wiki and came across this info
"You can also subscribe to topics and receive commands, but this will only work if you use "Org ID" != 'quickstart'. Thus, if you provide a different Org ID (do not forget the auth token!), the device will subscribe to:
iot-2/cmd/+/fmt/json"
does this mean that the topic to subscribe to is quickstart but even if that's so, I used '+/#' which subrcibes to all topics and still got nothing printing on the console ?

Hope this works for you:
var mqtt = require('mqtt');
var fs = require('fs');
var options = { port: PORT, host: HOST };/*user, password and others authentication if there.*/
var client = mqtt.connect('HOST', options);
client.on('connect', function ()
{
client.subscribe("topic, command or data");
client.publish("topic, command or data", data, function () {
});
});
client.on('error', function () { });
client.on('offline', function () { });
client.on('message', function (topic, message) {
console.log(message.toString());
});

Related

How data arrives from a gps tracker by gprs to a node.js server?

I created an application to show the location of a gps in real time using gprs. This application uses node.js. I have already created all the methods and in tests it works correctly. I set up the gps to an external gps server and send the data correctly. Now I configured it with my server and happens is I have the socket.io with open listening but the data does not arrive. Could someone help me to see why the data does not arrive or if it is arriving because I cannot read it?
This is the code to listen:
var socket = io.connect('http://34.226.95.13:5050', { 'forceNew': true });
socket.on('data', function(data) {
console.log(data);
})
socket.on('connection', function (socket) {
socket.on('data', function (data) {
console.log(data.toString());
var location = JSON.stringify(data);
socket.emit('data', item);
});
});
Thanks
I was searching the internet a lot and found a way to receive the information only with the DATA parameter, but I went a little further and found that the server returned an answer like this: ##, imei: 359xxxxxxxxxxxx, A;
Then, I kept investigating and had to respond to the device with LOAD, after doing my own development I found a repository that has everything very well organized and is the best to use.
To install you need to enter the following command in the console:
npm install gpstracker
And next, create index.js and copy this code:
var gpstracker = require("gpstracker");
var server = gpstracker.create().listen(5050, function(){
console.log('listening your gps trackers on port', 5050);
});
server.trackers.on("connected", function(tracker){
console.log("tracker connected with imei:", tracker.imei);
tracker.on("help me", function(){
console.log(tracker.imei + " pressed the help button!!".red);
});
tracker.on("position", function(position){
console.log("tracker {" + tracker.imei + "}: lat",
position.lat, "lng", position.lng);
});
tracker.trackEvery(10).seconds();
});
Thanks

Is it possible to create a "fake" socket connection to a nodejs server that is secured through SSL?

I'm using socket.io-client to create a socket connection to my locally-running server. See my code below:
// Working example of connecting to a local server that is not SSL protected
var io = require('socket.io-client')
var socket = io.connect('http://localhost:3000', {reconnect: true});
socket.on('connect', function(){ console.log("inside 'connect'") } );
socket.on('connection', function(){ console.log("inside 'connection'") } );
socket.on('event', function(data){ console.log("inside 'event'") } );
socket.on('disconnect', function(){ console.log("inside 'disconnect'") } );
var payload = {email: 'fake#gmail.com', password: 'tester'};
var tokens = {browserId: 'b965e554-b4d2-5d53-fd69-b2ca5483537a'};
socket.emit("publish", {logic:"user", method:"signIn"}, payload, tokens, function(err, creds) {
console.log("inside the socket client emit callback. err: " + err);
console.log("creds: " + creds);
});
Now for my problem. As I stated in the comment at the top of that code, I can connect to my local nodejs server and get the response I expect when I turn off SSL encryption on my server. As soon as I turn SSL on, I stop getting any response at all from the code above. I don't see any message in my server logs or from the command line, where I'm running the code above with node.
My goal is to be able to run the code above, with SSL turned on in my server, and get the same response that I get when SSL is turned off. I've tried a bunch of variations on the code I included above, such as:
connecting to "https://localhost:3000"
connecting to "//localhost:3000"
connecting to "https://localhost:3443" (this is the port I have to connect to when I have the nodejs server running with SSL)
changing {reconnect:true} to {reconnect:true,secure:true}
I'm truly stumped, and I've been doing a bunch of research on the web and on my node server. It's my company's code and I didn't originally implement the SSL components, so I've spent a few hours looking at our code and trying to understand how adding SSL changes everything. I'm also a student and have about 2 years of experience behind me, so I'm good but I'm no expert. Have I said anything above that indicates if my task is impossible to achieve, or if maybe I have just overlooked something? Any leads on things to check out would be appreciated :)

Can't send message to only one specific room through node.js and socket.io

I have a problem that i don't seems to be able to solve it. I'm doing some kind of integration with remote system and my code is in iframe but that can't be important for this one i hope :).
I'm trying to send a message from server to specific room/client to begin session. First thing I do is when user log in, I emit message from client side with username.
CLIENT.JS
conn.on('connect', function () {
conn.emit('session', { username: 'some_username' });
}, false);
And on server side i get message and join socket to the room.
SERVER.JS
socket.on('session', function(session) {
socket.join(session.username);
});
I have another module that communicates with this server.js script through redis. So i have two more events in server.js
SERVER.JS
var userCreate = redis.createClient();
userCreate.subscribe("userCreate", "userCreate");
var userDestroy = redis.createClient();
userDestroy.subscribe("userDestroy", "userDestroy");
userCreate.on("message", function(channel, data) {
socket.to(JSON.parse(data).username).emit('beginSession', data);
});
userDestroy.on("message", function(channel, data) {
socket.to(JSON.parse(data).username).emit('endSession', data);
socket.leave(JSON.parse(data).username);
});
But when ever i try to emit message from server to client i broadcast message to everyone. What am I doing wrong?
Well, from the syntax point of view you are doing everything correct.
Didn't you forget to specify the userId property in the endSession?
userDestroy.on("message", function(channel, data) {
socket.to(JSON.parse(data).userId).emit('endSession', data);
socket.leave(JSON.parse(data).userId);
});
If that doesn't work - you should provide the contents of a data object

Socket.io with Heroku

This works perfectly on my own computers server
var socket = io.connect('http://localhost:3000');
socket.of(userid).on('email', function (data) {
console.log("here")
});
however when I switch to heroku like
var socket = io.connect('http://staginggorkemnutrition.herokuapp.com');
socket.of(userid).on('email', function (data) {
console.log("here")
});
it seems like the event is never received, also I dont change anything on my server when I am changing from heroku to localhost
ps.
I have this in my server, I know I have to add this for heroku
global.io.configure(function () {
global.io.set("transports", ["xhr-polling"]);
global.io.set("polling duration", 10);
});
and my server side code when I emit the message looks like looks like:
exports.getFake = function(req, res){
global.io.of(global.id).emit('email' , email);
}
Web socket is experimental on Heroku.
Did you read this : https://devcenter.heroku.com/articles/heroku-labs-websockets ?
You may want to read this too : heroku multiple dyno socket.io

node.js server and client sideo code to connect

Im trying to set up a node.js server to send messages to the client, which will then display the messages using a jquery notification library, I'm using this notifcation library if anyone's interested: http://needim.github.com/noty/
At the minute I have a postgres database set up with a table which has a a trigger on it to write to a listener.
The trigger is as follows:
CREATE OR REPLACE FUNCTION new_noti() RETURNS trigger AS $$
DECLARE
BEGIN
PERFORM pg_notify('watchers', TG_TABLE_NAME || ',msg,' || NEW.msg );
RETURN new;
END;
$$ LANGUAGE plpgsql;
Then I have a node.js server as follows:
var pg = require ('pg');
var pgConString = "pg://aydin:password#localhost/test"
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, url = require('url')
app.listen(8080);
function handler (request, respsonse) {
var client = new pg.Client(pgConString);
client.connect();
client.query('LISTEN "watchers"');
client.on('notification', function(msg) {
console.log(msg.payload);
sendMessage(msg.payload);
});
}
function sendMessage(message) {
io.sockets.emit('notification', {'message': message});
}
Then I have some client code as follows:
<script type="text/javascript">
var socket = io.connect('http://localhost:8080');
socket.on('notification', function (data) {
console.log(data.message);
newNoty(data);
});
function newNoty(data) {
noty({
"text":data.message,
buttons: [{
type: 'button green',
text: 'Go to'
}],
"theme":"noty_theme_twitter",
"layout":"bottomRight",
"type":"information",
"animateOpen":{
"height":"toggle"
},
"animateClose":{
"height":"toggle"
},
"speed":500,
"timeout":7500,
"closeButton":true,
"closeOnSelfClick":true,
"closeOnSelfOver":false,
"modal":false,
});
}
</script>
This doesn't work, it seems the node.js never receives the postgres notifications, I think this is because I am using the function handler and I'm not actually firing any requests to it from the client code. I'm not sure how to do this and whether it is the correct way?
Is there a function on which can fire on connections and not requests?
And am I even doing it the right way round? should there be a server on the client side which node.js sends messages to? How does it know when a client is available? Any help or pointers to tutorials would be much appreciated. Thankyou.
You're not actually setting up your database connection until the client sends an HTTP request. It looks like that may never happen due to same-origin issues (your client code appears to be coming from somewhere other than the server you've shown).
In any case, you probably want to set up the connection in response to a "connection" event from io.sockets (i.e. move the stuff that's currently in the HTTP request handler there). That's how it "knows when a client is available". Or maybe you should be doing it as part of initialization. Your client-side code seems OK, but it's out of context so it's hard to tell whether it really fits your needs.

Categories

Resources