Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
- <title>Example of plotting live data with websockets and highcharts</title>
- <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
- <script src="mqttws31.js" type="text/javascript"></script>
- <script type="text/javascript">
- /*
- by @bordignon on twitter
- Feb 2014
- */
- //settings BEGIN
- var MQTTbroker = 'mqtt.espert.io';
- var MQTTport = 8000;
- var MQTTsubTopic = 'Monitor/#'; //works with wildcard # and + topics dynamically now
- //settings END
- var chart; // global variuable for chart
- var dataTopics = new Array();
- //mqtt broker
- var client = new Paho.MQTT.Client(MQTTbroker, MQTTport,
- "myclientid_" + parseInt(Math.random() * 100, 10));
- client.onMessageArrived = onMessageArrived;
- client.onConnectionLost = onConnectionLost;
- //connect to broker is at the bottom of the init() function !!!!
- //mqtt connecton options including the mqtt broker subscriptions
- var options = {
- timeout: 3,
- onSuccess: function () {
- console.log("mqtt connected");
- // Connection succeeded; subscribe to our topics
- client.subscribe(MQTTsubTopic, {qos: 1});
- },
- onFailure: function (message) {
- console.log("Connection failed, ERROR: " + message.errorMessage);
- //window.setTimeout(location.reload(),20000); //wait 20seconds before trying to connect again.
- }
- };
- //can be used to reconnect on connection lost
- function onConnectionLost(responseObject) {
- console.log("connection lost: " + responseObject.errorMessage);
- //window.setTimeout(location.reload(),20000); //wait 20seconds before trying to connect again.
- };
- //what is done when a message arrives from the broker
- function onMessageArrived(message) {
- console.log(message.destinationName, '',message.payloadString);
- var x = message.payloadString;
- // parse into JSON format
- z = JSON.parse(x)
- //console.log("x=" + x);
- // convert them to float
- console.log("t=" + parseFloat(z.temperature) );
- console.log("h=" + parseFloat(z.humidity) );
- console.log("v=" + parseFloat(z.volt) );
- if (dataTopics.indexOf(message.destinationName) < 0){
- dataTopics.push(message.destinationName); //add new topic to array
- var newseries = {
- id: 0,
- name: "Temp (C)", // hard-coded, need to be fixed
- data: []
- };
- chart.addSeries(newseries); //add the series
- var newseries = {
- id: 1,
- name: "Humidity (% RH)", // hard-coded, need to be fixed
- data: []
- };
- chart.addSeries(newseries); //add the series
- var newseries = {
- id: 2,
- name: "Volt (V)" , // hard-coded, need to be fixed
- data: []
- };
- chart.addSeries(newseries); //add the series
- };
- var myEpoch = new Date().getTime(); //get current epoch time
- var thenum = parseFloat(z.temperature); //remove any text spaces from the message
- var plotMqtt = [myEpoch, Number(thenum)]; //create the array
- if (isNumber(thenum)) { //check if it is a real number and not text
- plot(plotMqtt, 0); //send it to the plot function
- };
- var thenum2 = parseFloat(z.humidity); //remove any text spaces from the message
- var plotMqtt2 = [myEpoch, Number(thenum2)]; //create the array
- if (isNumber(thenum2)) { //check if it is a real number and not text
- plot(plotMqtt2, 1); //send it to the plot function
- };
- var thenum3 = parseFloat(z.volt); //remove any text spaces from the message
- var plotMqtt3 = [myEpoch, Number(thenum3)]; //create the array
- if (isNumber(thenum3)) { //check if it is a real number and not text
- plot(plotMqtt3, 2); //send it to the plot function
- };
- };
- //check if a real number
- function isNumber(n) {
- return !isNaN(parseFloat(n)) && isFinite(n);
- };
- //function that is called once the document has loaded
- function init() {
- //i find i have to set this to false if i have trouble with timezones.
- Highcharts.setOptions({
- global: {
- useUTC: false
- }
- });
- // Connect to MQTT broker
- client.connect(options);
- };
- //this adds the plots to the chart
- function plot(point, chartno) {
- console.log(point);
- var series = chart.series[0],
- shift = series.data.length > 20; // shift if the series is
- // longer than 20
- // add the point
- chart.series[chartno].addPoint(point, true, shift);
- };
- //settings for the chart
- $(document).ready(function() {
- chart = new Highcharts.Chart({
- chart: {
- renderTo: 'container',
- defaultSeriesType: 'spline'
- },
- title: {
- text: 'Plotting Live websockets data from a MQTT topic'
- },
- subtitle: {
- text: 'broker: ' + MQTTbroker + ' | port: ' + MQTTport + ' | topic : ' + MQTTsubTopic
- },
- xAxis: {
- type: 'datetime',
- tickPixelInterval: 150,
- maxZoom: 20 * 1000
- },
- yAxis: {
- minPadding: 0.2,
- maxPadding: 0.2,
- title: {
- text: 'Value',
- margin: 80
- }
- },
- series: []
- });
- });
- </script>
- <script src="http://code.highcharts.com/stock/highstock.js"></script>
- <script src="http://code.highcharts.com/stock/modules/exporting.js"></script>
- </head>
- <body>
- <body onload="init();"><!--Start the javascript ball rolling and connect to the mqtt broker-->
- <div id="container" style="height: 500px; min-width: 500px"></div><!-- this the placeholder for the chart-->
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement