Like Magic Imp Light Level with Firebase, HightChart

This is a live graph of the Light sensor light in the Imp.

My setup: Imp001, April Board and release 27.9

Copy agent and device code, Build and Run, then go to your agent URL and Voila!!!
Agent Code
`
local dID = “”;

device.on(“setdID”, function(data) {
dID = data;
server.log(“device ID:” + dID);
});

{const html1 = @"





var ReadCount = 0 ;
var reDrawChart = false;
var messageListRef = new Firebase('https://implight.firebaseio.com/";

const html2 = @"');
        messageListRef.on('child_added', function(dataSnapshot) {
            var data = dataSnapshot.val();
            var yPoint = Math.round(data.lightlevel/655.35)
            chart.series[0].addPoint([(data.time*1000),yPoint],reDrawChart );
            $('#readc').html ('Total Number of readings = ' + ++ReadCount);
           //console.log('Redraw = ' + reDrawChart)
        });

        messageListRef.once('value', function(dataSnapshot) { 
            ReadCount = dataSnapshot.numChildren();
            $('#readc').html ('Total Number of readings = ' + ReadCount);
            chart.hideLoading();
            chart.redraw();
            reDrawChart = true;
           //console.log('Done');
        });
    </script>
</head>
<body>
<div id='container' style='width:100%; height:480px;'></div>
<div id='readc' style='width: 100% ;margin-left: auto ;margin-right: auto ;'></div>
<script type='text/javascript'src='https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js'></script>
<script src='https://code.highcharts.com/stock/highstock.js'></script>
<script src='https://code.highcharts.com/stock/modules/exporting.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/highcharts/3.0.2/themes/gray.js'></script>
<script>
    $(function () {

        Highcharts.setOptions({
            global: {
                useUTC: false
            }
        });
        chart = new Highcharts.StockChart({
            chart: {
                renderTo: 'container',
                zoomType: 'x',
                spacingRight: 20
            },
            rangeSelector : {
                buttons: [
                    { type: 'minute',
                        count: 60,
                        text: '1h'},
                    { type: 'day',
                        count: 1,
                        text: '1d'},
                    {
                    type: 'month',
                    count: 1,
                    text: '1m'
                }, {
                    type: 'month',
                    count: 3,
                    text: '3m'
                }, {
                    type: 'month',
                    count: 6,
                    text: '6m'
                }, {
                    type: 'ytd',
                    text: 'YTD'
                }, {
                    type: 'year',
                    count: 1,
                    text: '1y'
                }, {
                    type: 'all',
                    text: 'All'
                }],
                inputEnabled : false
            },

            title: {
                text: 'Imp Light Sensor '
            },
            subtitle: {
                text: document.ontouchstart === undefined ?
                        'Click and drag in the plot area to zoom in' :
                        'Pinch the chart to zoom in'
            },
            xAxis: {
                type: 'datetime',
                title: {
                    text: 'Date'
                }
            },
            yAxis: {
                max:100,
                title: {
                    text: 'Light Level %'
                }
            },

            legend: {
                enabled: false
            } ,
            series: [{
                type: 'areaspline',
                name: 'Light Level',
                fillColor : {
                    linearGradient : {
                        x1: 0,
                        y1: 0,
                        x2: 0,
                        y2: 1
                    },
                    stops : [[0, Highcharts.getOptions().colors[0]], [1, 'rgba(0,0,0,0)']]
                },

                pointInterval: 24 * 3600 * 1000,
                data: []
            }]
        });
        chart.showLoading();
    });
</script>
</body>
</html>";

}

http.onrequest(function(request,res){
server.log(“Request”);
res.send(200, html1 + dID + html2);
});

device.onconnect(function() {
server.log(“device connected to agent”);
});

device.ondisconnect(function() {
server.log(“device disconnected from agent”);
});

device.on(“firebaseLog”, function(data) {
//server.log("in the agent -> " + data.llevel + " | Time -> " + time() + “Imp ID=” + data.ImpID);

//server.log(“IMP ID = " + impID);
local x = {
lightlevel = data.llevel ,
time =time()
};
local request = http.post(“https://implight.firebaseio.com/” + data.ImpID +”/.json",
{},
http.jsonencode(x)
);
local response = request.sendsync();
// server.log(response.body + " ImpID :" + data.ImpID);
});
`

Device Code
`
imp.configure(“Imp Light Levl”, [], []);
server.log(“light Level=”+hardware.lightlevel());
function loop(){
local x = {
llevel = hardware.lightlevel(),
ImpID = hardware.getdeviceid()
};

// server.log(“light Level=”+ x.llevel);
agent.send(“firebaseLog”, x);
imp.wakeup(1, loop)
}
agent.send(“setdID”, hardware.getdeviceid());
loop();
`

Cool!
This isn’t an HTTPS URL, are you sure its being pulled? I didn’t think you could pull both secure and non secure sources.
`

`

Hi Joel!
Thats only a theme file. Chrome block that file but safary loads it. You can see looks different in safary that chrome and also the charts are touch enable

See attahed screenshot

Ahh… good to know(about Safari). Is there no HTTPS URL for the theme file? I’m about to test your code. That is really good stuff. I know that several people, including myself are interested in charting data with the agent.

Nice work! I have it running. I tried using HTTPS for the theme, but no go in Chrome. Strange that they wouldn’t have a secure source for that.

I am glad that you like it. I will try to optimize load times with large set of data

Have your tried using //cdnjs.com/libraries/highcharts/ they support both http/s where as highcharts only supports http

Thanks!! controlCloud that works…

:)>-

What about hosting the html file on some simple static webspace and including the agent file as a script…

<script src="https://agent.electricimp.com/xxxxxxxxx"></script>

And then just has the agent return the required data as json. I think there’s something to be said for keeping device and agent code as “thin” as possible, whilst still being sensible.

True, but I have to say, for a simple page, I love that the agent can be its own webserver and need almost nothing else.