Using the socket.IO library, create a simple real-time widget with Ubidots and the HTML Canvas.
Socket.IO is a JS library easy to implement that manages socket connections and messages, thus enabling a bi-directional real-time connection protocol. Ubidots has implemented this real-time protocol within its core servers to easily update devices, to retrieve and store data inside any JS variable, and without the need to implement any requests, using sockets.
The following shows how to create a HTML Canvas Widget which will display a variables' data in a real time fashion. This example relies on the previous Create an LCD screen with the HTML Canvas, so please head to said section first.
Create the HTML element in which the data will be displayed:
<pid="content"></p>
Add the logic of the widget by using the following JavaScript code:
var socket;var srv =window.location.hostname +":443"; //this allows the widget to work at the white label levelvarVAR_ID="variable-id"; // Put here your var IdvarTOKEN="YOUR-TOKEN"// Put here your token$(document).ready(function () {// Implements the connection to the server socket =io.connect("https://"+ srv, { path:'/notifications' });var subscribedVars = [];// Function to publish the variable IDvarsubscribeVariable=function (variable, callback) {// Publishes the variable ID that wishes to listensocket.emit('rt/variables/id/last_value', { variable: variable });// Listens for changessocket.on('rt/variables/'+ variable +'/last_value', callback);subscribedVars.push(variable); };// Function to unsubscribed for listeningvarunSubscribeVariable=function (variable) {socket.emit('unsub/rt/variables/id/last_value', { variable: variable });var pst =subscribedVars.indexOf(variable);if (pst !==-1) {subscribedVars.splice(pst,1); } };varconnectSocket=function () {// Implements the socket connectionsocket.on('connect',function () {socket.emit('authentication', { token:TOKEN }); });window.addEventListener('online',function () {socket.emit('authentication', { token:TOKEN }); });socket.on('authenticated',function () {subscribedVars.forEach(function (variable_id) {socket.emit('rt/variables/id/last_value', { variable: variable_id }); }); }); }/* Main Routine */connectSocket();// Should try to connect again if connection is lostsocket.on('reconnect', connectSocket);// Subscribe Variable with your own code.subscribeVariable(VAR_ID,function (value) {var parsedValue =JSON.parse(value);console.log(parsedValue);$('#content').text(value); })});