In [1]:
from IPython.core.display import display, HTML
from string import Template
import pandas as pd
import json, random
In [6]:
HTML('<script src="lib/d3/d3.min.js"></script>')
# HTML('<script src="https://d3js.org/d3.v4.min.js"></script>')
Out[6]:
In [7]:
html_template = Template('''
<svg id="graph-div"></div>
<script> $js_text </script>
''')
In [8]:
js_text_template = Template('''
var data = $data;
var barHeight = 5;
var barWidth = 3;
var width = 800 * barWidth;
var x = d3.scale.linear()
.domain([0, 1000])
.range(["black", "white"]);
var chart = d3.select('#graph-div')
.attr('width', width)
.attr('height', 800);
function update() {
var row = chart.selectAll('.row')
.data(data)
.enter()
.append('g')
.attr('class', 'row')
.attr('transform', function(d, i){
return 'translate(0, ' + barHeight * i + ')';
});
var bar = row.selectAll('.bar')
.data(function(d) { return d; })
.enter()
.append('g')
.attr('class', "bar")
.attr('transform', function(d, i){
return 'translate(' + barWidth * i + ', 0)'
})
.append('rect')
.attr('width', barWidth)
.attr('height', barHeight)
.attr('fill', function(d) {
return x(d);
});
}
update();
''')
In [9]:
data = [[]];
js_text = js_text_template.substitute({'data': json.dumps(data)})
HTML(html_template.substitute({'js_text': js_text}))
Out[9]:
In [6]:
js_text_template_2 = Template('''
data = $data;
update();
''')
In [7]:
# data = [2,2,5,0,1]
tests = [[500,500,500,500,1000,1000,1000,1000], [500,500,500,500,1000,1000,1000,1000]]
def update_graph(data):
js_text = js_text_template_2.substitute({'data': json.dumps(tests)})
display(HTML('<script>' + js_text + '</script>'))
update_graph(tests)
Now for the fun stuff. Using the update_graph(data) function set up above. Each group of data, separated by "start" messages, is saved in the tests array. As new data comes in, the live data graph is updated to show data from the last test. All data is neatly saved inside the tests array for replotting and further analysis later.
Using the CloudMQTT free Cat plan:
In [116]:
import paho.mqtt.client as mqtt
data = []
tests = [[]]
update_graph(tests)
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("/outTopic")
def on_message(client, userdata, msg):
global data, tests
try:
msg_json = json.loads(msg.payload)
except:
print "Error"
print(msg.topic+" "+str(msg.payload))
return
if msg_json['type'] == "BREAK" and msg_json['label'] == "LOOP": # and msg_json['value'] == "END":
tests.append(data)
data = []
update_graph(tests)
if msg_json['type'] == "BINARY" and msg_json['label'] == "A0":
data.append(int(msg_json['value']))
tests[-1] = data
update_graph(tests)
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set("zettlmtm", "VOUbRcmhjffA")
client.connect("m11.cloudmqtt.com", 19280, 60)
client.loop_start()
# Make sure to call client.loop_stop() later
In [115]:
client.loop_stop()
In [117]:
print tests
In [ ]: