A new EcmaScript / JavaScript library for Yoctopuce

A new EcmaScript / JavaScript library for Yoctopuce

Some time ago, we presented the beginnings of a new Yoctopuce library designed to modernize our JavaScript support, for browsers as well as for Node.js. After three months of internal and external testing, and many improvements, it is now time to make official this EcmaScript library which is now supported at the same level as all the other languages.




Up till now, our official support for JavaScript existed in the shape of two libraries:

  • the JavaScript library, designed for use in browsers
  • the Node.js library, specifically designed for Node environments

These two libraries were initially based on "blocking" HTTP requests. The later being not in favor nowadays with JavaScript developers, we added asynchronous versions with callback results for almost all the methods. Their use were however not very practical because a whole program based on callbacks is difficult to read and to debug. Moreover, the Node.js library included a number of limitations linked to the HTTP library that was used.

The new library is called EcmaScript because it's the official name of the standardized language. It covers browsers as well as Node.js. It uses a new method, much smarter, to manage asynchronous calls, without breaking the code execution flow with callbacks: Promises. Apart from a few rare and documented exceptions, all the methods of the library now return promises for which the caller can await the result with the await operator. You can find many examples in the example_html and example_nodejs directories of the new library.

You can download the new library from our web site or directly with npm or jspm from GitHub. Detailed instructions are available in the README and in the PDF documentation.

An example: a GSM driven relay


As an example, we are going to show you how to create in Node.js a small system to drive a relay remotely with a YoctoHub-GSM-3G-EU. As SIM chips available for laymen cannot contact public servers on Internet, we are going to host our Node.js code on Heroku.com.

The application is very simple on purpose: the aim is simply to show you how you can use this new library, for example with a Node.js public host such as Heroku. We'll have other opportunities for more sophisticated tasks with this library in further posts. At this stage, we also skip all the security and scalability aspects, of which we will talk in an upcoming article.

To stay within the Node.js standards, we use Express as motor to serve the pages of our web app. This same web server accepts incoming connections from the YoctoHub-GSM, at the WebSocket standard. The interface of our web app simply offers to display the connected relays and to switch them.

Project structure


The application code is available on GitHub. You can find there:

  • under /public the static files of the web interface
  • under /views the web console pages, interpreted by Express
  • under /src the EcmaScript source code of the application
  • at the root of the project, several configuration files


The source code of the application is in a single file. The base structure to create an Express server with WebSockets is the following:

// Import http, websocket and Express libraries
var server = require('http').createServer();
var WebSocketServer = require('ws').Server;
var express = require('express');

// Setup Websocket handler
function WebSocketCallbackHandler(ws)
{ ... }
var wss = new WebSocketServer({ server: server });
wss.on('connection', WebSocketCallbackHandler);

// Setup Express app server
var app = express();
server.on('request', app);
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.get('/', function(request, response) {
    response.render('index');
});

// Start web server
server.listen(app.get('port'), function() {
    console.log('Server running on port', app.get('port'));
});



Code specific to Yoctopuce


The code necessary to handle Yoctopuce modules is put in the WebSocketCallbackHandler() function which is called when the YoctoHub-GSM-3G-EU connects itself. It starts by initializing the Yoctopuce library and enumerates the relays. It then waits for the switch instructions sent by the web interface. Note the use of async and await keywords to manage asynchronous operations.

async function WebSocketCallbackHandler(ws)
{
    let hwids = [];
    let errmsg = new YErrorMsg();
    let yctx = new YAPIContext();
    try {
        // Initialize library
        if(await yctx.RegisterHubWebSocketCallback(ws, errmsg)!=YAPI.SUCCESS){
            console.log('HTTP callback error: '+errmsg);
            yctx.FreeAPI();
            return;
        }
        // Enumerate relays
        let relay = YRelay.FirstRelayInContext(yctx);
        while(relay) {
            let hwid = await relay.get_hardwareId();
            hwids.push(hwid);
            Relays[hwid] = relay;
            relay = relay.nextRelay();
        }
        // Keep the calling hub connected for a 30 seconds
        await yctx.Sleep(30000);
    } catch(e) {
        console.log('Caught exception in WS code', e);
    }
    // Remove relays from list before disconnecting
    for(let i = 0; i < hwids.length; i++) {
        delete Relays[hwids[i]];
    }
    // Free ressources
    yctx.FreeAPI();
}


To keep it simple, relay switching from the web UI will be performed by passing arguments to the URL. We will have other opportunities to discover a more elegant method using JavaScript code directly in the UI. So here are the few lines to replace in the code skeleton above in order to driver the relays according to arguments on the URL:

app.get('/', function(request, response) {
    if(request.query.relay && Relays[request.query.relay]) {
        Relays[request.query.relay].set_state(request.query.state);
    }
    app.locals.Relays = Relays;
    response.render('index');
});



Installation prerequisites


We assume here that you have installed git, npm and Node.js on your machine.

To use the Yoctopuce EcmaScript library, we recommend that your install jspm as well, allowing you to use the new EcmaScript syntax with Node.js:

$ npm install jspm@beta -g


To test Heroku, you also need to create an account on Heroku.com. Free hosting is enough to run this example. Install the Heroku tools (Heroku Toolbelt) as decribed on this page.

Compiling the project


To start, you must download the project on your machine from GitHub:

$ git clone https://github.com/yoctopuce-examples/ecmascript-on-heroku.git
$ cd ecmascript-on-heroku


Install the project dependencies with the following commands:

$ npm install
$ jspm install


To use the project on Heroku, you must compile the project to translate the async/await syntax into code that Node.js can understand:

$ jspm build src/demo.js --node


At this stage, you already can run the project locally with the command:

$ heroku local



Deploying on Heroku


When you have compiled the project, you can upload it to Heroku:

$ heroku login
Enter your Heroku credentials.
Email: ...
$ heroku create
$ git push heroku master


You can now go to you application web page. You can do so with the following command, which opens your browser directly on the correct page:

$ heroku open



Configuring the YoctoHub


You only need to configure the YoctoHub-GSM-3G-EU so that it connects itself to our Heroku server. Use the following settings, but simply replace the URL by that of your application, as it shows in your browser when you are viewing the interface:

WebSocket callback configuration
WebSocket callback configuration



Demo


Here is a short video showing how this example code works:

  



Here we are, you now have everything to build a "smart home hub" with your own internet console, while keeping complete control of the source code and without being dependent on someone else's goodwill...

Add a comment No comment yet Back to blog












Yoctopuce, get your stuff connected.