forked from matbor/mqtt2highcharts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
livemqttchart.html
160 lines (144 loc) · 5.39 KB
/
livemqttchart.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
<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
Simple example of plotting live mqtt/websockets data using highcharts.
public broker and topic you can use for testing.
var MQTTbroker = 'broker.mqttdashboard.com';
var MQTTport = 8000;
var MQTTsubTopic = 'dcsquare/cubes/#'; //works with wildcard # and + topics dynamically now
*/
//settings BEGIN
var MQTTbroker = 'test.mosca.io';
var MQTTport = 80;
var MQTTsubTopic = 'HouseMalan/+/temperature'; //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: 0});
},
onFailure: function (message) {
console.log("Connection failed, ERROR: " + message.errorMessage);
//window.setTimeout(location.reload(),20000); //wait 20seconds before trying to connect again.
}
};
// eclipse error work-around: keep another set of options to reuse
function clone(obj) {
if (null == obj || "object" != typeof obj) return obj;
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
}
return copy;
}
var options2 = clone(options);
//can be used to reconnect on connection lost
function onConnectionLost(responseObject) {
console.log("connection lost: " + responseObject.errorMessage);
window.setTimeout(function() {init(); },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);
//check if it is a new topic, if not add it to the array
if (dataTopics.indexOf(message.destinationName) < 0){
dataTopics.push(message.destinationName); //add new topic to array
var y = dataTopics.indexOf(message.destinationName); //get the index no
//create new data series for the chart
var newseries = {
id: y,
name: message.destinationName,
data: []
};
chart.addSeries(newseries); //add the series
};
var y = dataTopics.indexOf(message.destinationName); //get the index no of the topic from the array
var myEpoch = new Date().getTime(); //get current epoch time
var thenum = message.payloadString.replace( /^\D+/g, ''); //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
console.log('is a propper number, will send to chart.')
plot(plotMqtt, y); //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 (eclipse error workaround.)
options = clone(options2);
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>