27.3.2015
Few weeks ago I described simple http server for Qt a and universal API to access application data – today I will show you how to use HTML5 event stream.
We use the server in a embedded applications built on BeagleBone Black. HTML pages in such device use usual structure:
Do you want to have your data stored in a small box and accessible from your tablet, phone or notebook?
Call: +420 777 566 384 or email to address info@hobrasoft.cz
See the live example. How it works?
HTML source shows only a simple table without any data (I ignored other parts of page):
<table id="tabledata"> <thead><tr><th>ID</th><th>Text</th><th>Value</th><th></th></tr></thead> <tbody></tbody> </table>
The table is empty – data are obtained using JavaScript and HTML event stream:
$(document).ready(function(){ var source = new EventSource("/example/events"); source.addEventListener("status", function(event) { var data = JSON.parse(event.data); var id = data.id; var rowdata = "" + " \n"; var rowelement = $("table#tabledata tbody tr#"+id); if (rowelement.text() == "") { $("table#tabledata tbody").append( rowdata ); } else { rowelement.replaceWith( rowdata ); } }, false); });" + data.id + " " + "" + data.text + " " + "" + data.counter + " " + "detail " + "
First line is the construction of jQuery, the second one installs the event stream and on other lines the event is processed. Code will not work in MS Explorer, this web browser do not support HTML5 event streams. Other browser are usually without problems.
Please note the line installing event stream processing:
var source = new EventSource("/example/events");
String "/example/events" is a relative URL linking event stream. Please, see prior article to understand how the address is created in HobrasoftHttp server.
There is nothing magic about HTML5 event streams. Their use is simple and effective. A lot of detailed articles can be found on Internet:
Stream Updates with Server-Sent Events
I wanted to show interesting and simple technology in this article. My experience shows that embedded application developers – single chip micro-controllers, BeagleBone, Raspberry and other – very often has only small knowledge in web technologies. And the reverse is also true - web developers have the knowledge in hardware even smaller. But both worlds can be connected so easily.