Advertisement
stanleyseow

MQTT highcharts

Feb 12th, 2016
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <html>
  2. <head>
  3. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  4. <title>Example of plotting live data with websockets and highcharts</title>
  5.  
  6.  
  7. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
  8. <script src="mqttws31.js" type="text/javascript"></script>
  9. <script type="text/javascript">
  10. /*
  11. by @bordignon on twitter
  12. Feb 2014
  13. */
  14.  
  15. //settings BEGIN
  16.     var MQTTbroker = 'mqtt.espert.io';
  17.     var MQTTport = 8000;
  18.     var MQTTsubTopic = 'Monitor/#'; //works with wildcard # and + topics dynamically now
  19. //settings END
  20.  
  21.     var chart; // global variuable for chart
  22.     var dataTopics = new Array();
  23.    
  24.  
  25.            
  26.  
  27. //mqtt broker
  28.     var client = new Paho.MQTT.Client(MQTTbroker, MQTTport,
  29.                 "myclientid_" + parseInt(Math.random() * 100, 10));
  30.     client.onMessageArrived = onMessageArrived;
  31.     client.onConnectionLost = onConnectionLost;
  32.     //connect to broker is at the bottom of the init() function !!!!
  33.    
  34.  
  35.        
  36.    
  37.  
  38. //mqtt connecton options including the mqtt broker subscriptions
  39.     var options = {
  40.         timeout: 3,
  41.         onSuccess: function () {
  42.             console.log("mqtt connected");
  43.             // Connection succeeded; subscribe to our topics
  44.             client.subscribe(MQTTsubTopic, {qos: 1});
  45.         },
  46.         onFailure: function (message) {
  47.             console.log("Connection failed, ERROR: " + message.errorMessage);
  48.             //window.setTimeout(location.reload(),20000); //wait 20seconds before trying to connect again.
  49.         }
  50.     };
  51.  
  52. //can be used to reconnect on connection lost
  53.     function onConnectionLost(responseObject) {
  54.         console.log("connection lost: " + responseObject.errorMessage);
  55.         //window.setTimeout(location.reload(),20000); //wait 20seconds before trying to connect again.
  56.     };
  57.  
  58. //what is done when a message arrives from the broker
  59.     function onMessageArrived(message) {
  60.         console.log(message.destinationName, '',message.payloadString);
  61.  
  62.         var x = message.payloadString;
  63.        
  64.         // parse into JSON format
  65.         z = JSON.parse(x)
  66.         //console.log("x=" + x);
  67.         // convert them to float
  68.         console.log("t=" + parseFloat(z.temperature) );
  69.         console.log("h=" + parseFloat(z.humidity) );
  70.         console.log("v=" + parseFloat(z.volt) );
  71.  
  72.         if (dataTopics.indexOf(message.destinationName) < 0){
  73.  
  74.             dataTopics.push(message.destinationName); //add new topic to array
  75.  
  76.             var newseries = {
  77.                     id: 0,
  78.                     name: "Temp (C)", // hard-coded, need to be fixed
  79.                     data: []
  80.                     };
  81.  
  82.             chart.addSeries(newseries); //add the series
  83.            
  84.             var newseries = {
  85.                     id: 1,
  86.                     name: "Humidity (% RH)", // hard-coded, need to be fixed
  87.                     data: []
  88.                     };
  89.  
  90.             chart.addSeries(newseries); //add the series
  91.            
  92.             var newseries = {
  93.                     id: 2,
  94.                     name: "Volt (V)" , // hard-coded, need to be fixed
  95.                     data: []
  96.                     };
  97.  
  98.             chart.addSeries(newseries); //add the series
  99.            
  100.             };
  101.            
  102.  
  103.         var myEpoch = new Date().getTime(); //get current epoch time
  104.        
  105.         var thenum = parseFloat(z.temperature); //remove any text spaces from the message
  106.         var plotMqtt = [myEpoch, Number(thenum)]; //create the array
  107.         if (isNumber(thenum)) { //check if it is a real number and not text
  108.             plot(plotMqtt, 0);  //send it to the plot function
  109.         };
  110.        
  111.         var thenum2 = parseFloat(z.humidity); //remove any text spaces from the message
  112.         var plotMqtt2 = [myEpoch, Number(thenum2)]; //create the array
  113.         if (isNumber(thenum2)) { //check if it is a real number and not text
  114.             plot(plotMqtt2, 1); //send it to the plot function
  115.         };
  116.        
  117.         var thenum3 = parseFloat(z.volt); //remove any text spaces from the message
  118.         var plotMqtt3 = [myEpoch, Number(thenum3)]; //create the array
  119.         if (isNumber(thenum3)) { //check if it is a real number and not text
  120.             plot(plotMqtt3, 2); //send it to the plot function
  121.         };
  122.        
  123.        
  124.     };
  125.  
  126. //check if a real number   
  127.     function isNumber(n) {
  128.       return !isNaN(parseFloat(n)) && isFinite(n);
  129.     };
  130.  
  131. //function that is called once the document has loaded
  132.     function init() {
  133.  
  134.         //i find i have to set this to false if i have trouble with timezones.
  135.         Highcharts.setOptions({
  136.             global: {
  137.                 useUTC: false
  138.             }
  139.         });
  140.  
  141.         // Connect to MQTT broker
  142.         client.connect(options);
  143.  
  144.     };
  145.  
  146.  
  147. //this adds the plots to the chart 
  148.     function plot(point, chartno) {
  149.         console.log(point);
  150.        
  151.             var series = chart.series[0],
  152.                 shift = series.data.length > 20; // shift if the series is
  153.                                                  // longer than 20
  154.             // add the point
  155.             chart.series[chartno].addPoint(point, true, shift);  
  156.  
  157.     };
  158.  
  159. //settings for the chart
  160.     $(document).ready(function() {
  161.         chart = new Highcharts.Chart({
  162.             chart: {
  163.                 renderTo: 'container',
  164.                 defaultSeriesType: 'spline'
  165.             },
  166.             title: {
  167.                 text: 'Plotting Live websockets data from a MQTT topic'
  168.             },
  169.             subtitle: {
  170.                                 text: 'broker: ' + MQTTbroker + ' | port: ' + MQTTport + ' | topic : ' + MQTTsubTopic
  171.                         },
  172.             xAxis: {
  173.                 type: 'datetime',
  174.                 tickPixelInterval: 150,
  175.                 maxZoom: 20 * 1000
  176.             },
  177.             yAxis: {
  178.                 minPadding: 0.2,
  179.                 maxPadding: 0.2,
  180.                 title: {
  181.                     text: 'Value',
  182.                     margin: 80
  183.                 }
  184.             },
  185.             series: []
  186.         });        
  187.     });
  188.  
  189. </script>
  190.  
  191. <script src="http://code.highcharts.com/stock/highstock.js"></script>
  192. <script src="http://code.highcharts.com/stock/modules/exporting.js"></script>
  193.  
  194. </head>
  195. <body>
  196. <body onload="init();"><!--Start the javascript ball rolling and connect to the mqtt broker-->
  197.  
  198.  
  199.  
  200. <div id="container" style="height: 500px; min-width: 500px"></div><!-- this the placeholder for the chart-->
  201.  
  202.     </body>
  203. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement