Display MQTT webchannel data in a html page - html

I have to display data of mqtt channel to the html page. I have prepared a node js code for the same as following :
var mqtt = require('mqtt');
client = mqtt.createClient(1883, 'mqtt.beebotte.com',
//Authenticate with your channel token,
{username: 'token:TOKEN_KEY', password: ''});
client.on('message', function (topic, message) {
console.log('topic: ' + topic + ' payload: ' + message);
});
client.subscribe('AppTeamDemo/GpsDataUpload');
client.subscribe('AppTeamDemo/EventDataUpload');
client.subscribe('AppTeamDemo/CommToZiggi');
client.subscribe('AppTeamDemo/CommFromZiggi');
And i am able to get data which i need to parse using JSON formatter and have to display it in html page.
I am confused as I am little new to all of this, how would I be able to use nodejs variable to the html page as it is a server side javascript.
How would I be able to connect with mqtt channel because every time it is saying mqtt is not defined.
I preferred not to use node and subscribe this channel in html page by using mqtt and by parsing the JSON data, I want to display latitude and longitude in google map. How would I be able to connect and get JSON response at front-end side ?
Please guide me. Thanks in advance.

Rather than write your own MQTT to Web bridge have you considered using a MQTT broker that supports WebSockets?
If you use the Paho library you can subscribe to the topics you are interested directly from javascript in the page.

Related

Parse JSON data which is a response to http get request

Using NODE.js I am trying to develop a website which sends request to some third-party server, and the response being in JSON format, what is the best way rather the fastest way to filter the data directly ? Suppose i want to query certain books of a specific author, what is the best practice ?
Should i handle this in callback ? and then parse the entire response object ?
OR Should i filter the response while receiving itself in the stream using pipe ?
NOTE that i am intending to develop a website which will have to answer users in real-time, so time is precious here.
I think you can use callback to retrieve JSON data and them use websocket to pass the filtered data to the client in real time.
http://nodejs.org/api/http.html#http_http_get_options_callback
http.get("http://www.google.com/index.html", function(res) {
console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
You can use socket.io for node.js
http://socket.io/

Express.js & Node.js | Rendering template

1) Can I render a view with Express without using any template file like jade?
I'm building a real-time chat system for Mobile Devs (cross-platform, so it's a web app) with Node, Express & Socket.io, and the server code core will be build for dispatch messages, user's requests & so on, I don't need to have a view but the result of the functions, because the view is already running on the device.
That's not really rendering, just serving.
You can send a file as answer using res.sendfile :
res.sendfile("pathToYourFile.html");
If you just want to send the results of functions, you can simply send the response without using a template by calling the .end() method (documentation) of the response object that Node passes. An example:
function onRequest( request, response ) {
functionResult = someFunctionYouWantToCall();
response.end( functionResult );
}

RestSharp usage for sending and receiving data

I have successfully created my app and now want to connect it to a localhost to check the working of my app. I have been suggested to use restsharp for connecting to the server using php and json to receive data from server.
I have looked at codes for both but do not completely understand how the process works. I have looked into all forums but found could snippets with no explanation as how it works. I have even tried restsharp.org and google search results. Please explain me as to how this works.
RestSharp is a library that helps you invoking REST web services.
You use RestSharp on your client to invoke Rest style Web Services (send and receive data)
Here is an example on the usage of your service:
var client = new RestClient(baseUrl);
var request = new RestRequest("/*rest_resource*/", Method.POST);
// see Rest services
// set the request format - HTTP Content-Type text/xml
request.RequestFormat = DataFormat.Xml;
// add data to the request
request.AddBody("<books><book>RestSharp Book</book></books>");
/* send the request and if your service returns text put the as expected return type; otherwise you will get raw byte array*/
IRestResponse response = client.Execute(request);
//HTTP status code 200-success
Assert.IsTrue(response.StatusCode == HttpStatusCode.OK);
Assert.IsTrue(!string.IsNullOrEmpty(response.Data)); // the response is not empty

How to send data back to node from casperjs?

How can I send data back to node, from a process launched via execfile in nodeJS? preferably in a JSON format.
This is how my code looks like right now:
//index.js NodeJS
var execFile = require('child_process').execFile;
var express = require('express');
app.get('/', function(req, res) {
var lchecker = execFile('/usr/local/bin/casperjs', [myprogram, myargs]);
lchecker.stdout.on('data', function(data) {
var dataObject = JSON.parse(data); //This throws an error.
});
});
The casperjs script that I'm calling returns JSON-like strings, like this:
console.log("[{href: targetLink.href, anchor: targetLink.anchor, isLive: 0, isFollowed: null}]");
This is the error that I get
When I'm trying to parse the JSON-like string, I get an error that says:
19 Jun 16:46:43 - [nodemon] starting node index.js
undefined:1
[{href: targetLink.href, anchor: targetLink.anchor, isLive: 1, isFollow: 1}]
^
Unexpected token h
So my JSON is invalid, and sincerely, I'm sure that there's a better way to send data back to node from casperjs, but I don't know how.
I've been thinking about creating a new route in express, and then make casperjs visit that route and pass the information via GET, and then manipulate that information in node. Is this a good way to achieve this?
Even though I received good and viable answers, I ultimately ended up outputting everything to stdout in casperjs, to send it back to PHP through a JSON array.
so in casperjs I wrote something like:
console.log(JSON.stringify(targetLink))
And then in node, I could just access that through JSON.parse and manipulate the data in any way I want.
EDIT:
I've run into this situation more often than not, so alternatively you can make CasperJS POST the information to a web endpoint, it's sometimes cleaner, but it adds overhead if you are worried about security and you need to make sure that only authorized scrapers can post data to your endpoint.
I have used CasperJS on NodeJS by running CasperJs as a service.
Basically NodeJS through http.get() makes a request to CasperJS script which return a JSON object as response.
Here an example and more details about how a CasperJS script can start a web server:
CasperJS passing data back to PHP
You may probably prefer to use something like SpookyJS (https://github.com/WaterfallEngineering/SpookyJS) which offer the ability to use CasperJs inside a Node.js program.
I don't know if you will find the feature you want but it's probably cleaner anyway.

Generate PDF document with data on Titanium DB

I am creating a mobile app using Titanium. I am using the titanium db which is sqlite. This pdf needs to have boxes to structure the data and images that I am taking with the app as well.
I am assuming what I need to do is convert the data into json on titanium, upload it to a web server and insert into a mysql/phpmysql db and then use some sort of script that is out there will read the web db and create a pdf and send it back to the phone
is that right?
and if so...i need help with that whole process haha...any good tutorials on db upload to web db process?
Check the docs, HTTPClient is what you need to use, its a standard.
First steps would be to create a web service on your server that parses your JSON formatting. The bulk of the work you would have to do has nothing to do with Titanium, but here is the code for sending a JSON object to some web service with a POST from a Titanium App.
var xhr_getstep = Titanium.Network.createHTTPClient();
xhr_getstep.onload = function(e) {
// Do something with the response from the server
var responseBlob = this.responseText;
};
xhr_getstep.onerror = function() {
Ti.API.info('[ERROR] WebService failed.');
};
xhr_getstep.open("POST", 'http://yourwebsite.com/yourwebserviceentry.php');
xhr_getstep.setRequestHeader("Content-Type", "application/json");
// Create your object with info on how to create the PDF
var objSend = {title : 'Amazing Title'};
xhr_getstep.send(obj); // Send it all off