JSFiddle - React, Tailwind, and code Playground
by leggetter
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>The Realtime Web is Shocking!!</title>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script src="http://js.pusherapp.com/1.9.5/pusher.min.js"></script>
<script src="https://raw.github.com/leggetter/pusher-js-helper/master/helper.js"></script>
<script src="https://raw.github.com/joewalnes/smoothie/master/smoothie.js">
</script>
<script src="http://people.iola.dk/olau/flot/jquery.flot.js"></script>
<script src="http://people.iola.dk/olau/flot/jquery.flot.pie.js"></script>
</head>
<body>
<section>
<div>Connection State: <span id="conn_status"></span></div>
</section>
<button id="sendTest">Test</button>
<section id="usage">
<canvas id="seriesChart" width="400" height="100"></canvas>
<div id="pie" style="width:300px;height:300px;"></div>
</section>
</body>
</html>
JavaScript
$(function() {
var pusher = new Pusher('a71b8d8b7eef0ef6d98c');
pusher.connection.bind('state_change', function() {
$("#conn_status").text(pusher.connection.state);
});
var channel = pusher.subscribe('energy-usage');
var timeSeriesLookup = {};
var smoothie = new SmoothieChart();
smoothie.streamTo(document.getElementById("seriesChart"));
var pieDataSets = [];
channel.bind('usage_updated', function(usage) {
var updateTime = new Date().getTime();
for(var i = 0, l = usage.payload.devices.length; i < l; ++i) {
var deviceInfo = usage.payload.devices[i];
var timeSeries = timeSeriesLookup[deviceInfo.name];
if( timeSeries === undefined ) {
timeSeries = new TimeSeries();
timeSeriesLookup[deviceInfo.name] = timeSeries;
var colors = rndColors();
smoothie.addTimeSeries(timeSeries, { strokeStyle: colors.rgb, fillStyle:colors.rgba, lineWidth:3 });
pieDataSets.push({label:deviceInfo.name, data: deviceInfo.usage});
timeSeries._pieDataIndex = (pieDataSets.length-1);
}
var pieData = pieDataSets[timeSeries._pieDataIndex];
pieData.data = deviceInfo.usage;
console.log(pieDataSets);
drawPie(pieDataSets);
timeSeries.append(updateTime, deviceInfo.usage);
}
});
function drawPie(pieDataSets) {
$.plot($("#pie"), pieDataSets,
{
series: {
pie: {
show: true,
radius: 1,
label: {
show: true,
radius: 3/4,
formatter: function(label, series){
return '<div...