We live in a world ruled by technology that is transparent to the data that we seek. How can we harness this invisible flow of information in the World of IoT?
A few decades ago, the internet was just a simple system for serving up basic text web pages and sending emails. It wasn't long before we saw the mark up language of the hyper text markup language (HTML) give us rich text, formatting, pictures and of course, tables. The internet grew up, and we got cascading styles sheets, web 2.0 and rounded corners but it still had one major issue – it could not match the rich desktop experience and every-time the user wanted a change or new data the page would need to be refreshed. This was because the server side controlled the data and the rendering of the information, so simple things like a drop-down box would cause whole pages to be reloaded, slowing down the user experience. An example of serverside software would be PHP or ASP.
We then got javascript, a language designed for the client side of the equation. This was also the time of the browser wars, where standards shifted, and your choice of browser would often dramatically affect the way the page and javascript were rendered and work. What did come out of this was a stable cross-browser standard for javascript, followed by the birth of AJAX. “Asynchronous javascript and XML” gave us the ability to pull data from the server without needing to reload the entire page; essentially, AJAX is a collection of technologies that are used in a particular way.
At a similar time, Node.js sprang to life. Node.js is a server-side implementation of javascript and presents a unified language for allowing fast asynchronous programming. It is an open source server framework that runs on all the major operating systems.
A common task for a web server can be to open a file on the server, and return the content to the client. Using PHP or ASP this is how they would handle a file request:
- Send the task to their (the servers) file system
- Wait until the file system opens and reads the file
- Return the content to the client
- Ready to handle the next request
However, Node.js handles this quite differently:
- Send the task to their (the servers) file system
- Get ready to handle the next request
- When the file system has opened and read the file, the server returns the content to the client
As you can see, Node.js eliminates the waiting and simply continues with the next request.
Node.js runs single-threaded, non-blocking, asynchronously programming. This in turns means you have a much more efficient system that can run a lot faster. Node.js can generate dynamic page content. It can create, open, read, write, delete, and close files on the server; it can collect form data, and it can add, delete, modify data in your database. It must be initiated on the server first however, before it can work – unlike HTML or PHP.
GETTING STARTED
Node.js is available for a large number of environments. Because of this we would recommend using the node.js installation guide from here: https://nodejs.org/en/download/
NODE.JS HELLO WORLD
What would any Secret Code article be without a “Hello World” in blinking LED? This one does not let you down! The remainder of this article assumes you have a working install in your environment, desktop or other.
To create our first node.js program, we need to start by opening up your preferred text editor – we recommend Notepad++ on Windows, Atom on Mac and Gedit on Linux.
We begin by including the required library. Compared to other languages we have discussed, Python and C++ look somewhat different. We use the “require” to load the HTTP module and return the HTTP instance into a variable called HTTP.
var http = require(‘http’);
Next, we create the server object. To do this we take our instance of HTTP, and we use the createServer() function. We then bind it to the TCP port of 8081 with the listen command. This means that our node.js service/server will be located on this port when we call it. In amongst this, we have the response that we are sending back. The first line, response.writeHead is the header information that the browser requires. In this case, we are telling it to the display the information it receives and text or HTML. The next and final line of this section of code is response.end, which delivers the content for the browser – in this case, its “Hello World”.
http.createServer(function (request, response) {
response.writeHead(200,
{‘Content-Type’: ‘text/html’});
response.end(‘Hello World!n’);
}).listen(8080);
Put all of the above code into your text editor and call it firstnode.js. Once saved we need to open the command-line on your system. Remembering that Node.js runs in a server-client configuration, we need to start the service. Now, depending on your system (OSX/Linux) you may need to run the sudo command; this will vary on system setup.
At the command line navigate to the directory that you saved the firstnode.js file. Once located run the following:
node firstnode.js
Open up your browser of choice and input: http://127.0.0.1:8080/
You will now see “Hello World” displayed in your browser.
You may think, well that's interesting, but what would be an application in the IoT world? At first glance it may seem somewhat convoluted, but in context, node.js is a very powerful tool. For Raspberry Pi and Arduino, the implementation is very different. Being that RPi reflects the general PC architecture, we will examine the use of Node.js using it first.
RASPBERRY PI
For the purpose of this article, we assume you have a current working installation of Rasbpian LITE. Run the Raspberry Pi config:
sudo raspi-config
Ensure that SSH is setup, hostname and password if required. Save changes and reboot. Log in to the system via SSH (PuTTY or similar) and log in. We need to install Node.js.
$ sudo apt-get update
$ sudo apt-get dist-upgrade
To download and install the newest version of Node.js, use the following command:
$ curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
Now install it by running:
$ sudo apt-get install -y nodejs
Check that the installation was successful, and the version number of Node.js with:
$ node -v
We now have a working installation of Node.js on our RPi. Repeat the earlier Hello World example to test that your install is working correctly. Assuming a successful test, let’s move on to the ultimate Hello World application – the blinking LED.
As you are aware the Raspberry Pi includes a bank of general purpose input and output pins, which are referred to as GPIO. These pins allow us to interact with the real world and in this case, we will switch an LED on and off. Remember to put the circuit together with your RPi switched off. You will need:
- RPi
- Breadboard
- LED
- 68 Ohm resistor
- Hookup/jumpers wires
With our circuit in place, we can focus on our code.
var Gpio = require(‘onoff’).Gpio;
var LED = new Gpio(4, ‘out’);
var blinkInterval = setInterval(blinkLED, 250);
function blinkLED() {
if (LED.readSync() === 0) {
LED.writeSync(1);
} else {
LED.writeSync(0);
}
}
function stopBlink() {
clearInterval(blinkInterval);
LED.writeSync(0);
LED.unexport();
}
setTimeout(stopBlink, 5000);
Let’s examine this for a moment. Firstly this does not include any of the HTTP code that we mentioned in the previous example. This code directly interfaces with the GPIO hardware. When we dig into the code, we see that the first three lines declare the required variables. The first of these is the library for using the GPIO port on the RPi. The next defines our LED, which will be switched on and off each interval. This will be on pin 4 and is set for “out”, which means that is the output. The final variable is set as an interval, which calls a particular function at a predetermined time. In this case, we are calling blinkLED function every 250 milliseconds.
Next, we have the blinkLED function. If you have used javascript, C++, PHP or similar languages you will see this is a simple if/else block. The second line checks the current state of the LED pin if its 0 (off) then we go to the next line and turn the LED on. The follow lines reciprocate this process if the LED is switched off.
Next, we have the stopBlink function. The purpose here is to terminate the program and clean up the use of the GPIO ports. Those new to the world of the RPi may be wondering why you would require something like this, but it is best practice to make sure that you have freed up all resources relating to the port that may be used in alternative programs.
You may have noticed that throughout this code we have not called the stopBlink. This is because of the last line, which sets a timeout event to occur at 5,000 milliseconds. In this case, after the defined period, we will execute a function and that function stopBlink. This finalises any process and frees up the aforementioned GPIO.
PYTHON VS NODE.JS ON RPI
Now Python is the traditional language of the RPi, but as you can see Node.js can run very easily on the system. Is there any advantaged to doing this? On the surface, if your background is one of traditional programming such as C++ or Java, then the learning curve with Python can be quite steep. On the surface, Python is incredibly easy to use, but once you get under the hood, there are some quirks that while well documented, may trip up the traditional programmer. Using Node.js means that you can easily switch over and a lot of things will work quite easily. Python struggles to be asynchronous whereas Node.js is designed to be like this out of the box. Node.js is one of the best platforms available if your project requires web applications development, as it is backed by Google’s V8 standard, and it supports callback as we have seen here, which makes process run much faster.
RUNNING WITH ARDUINO
This is very different, so you would not code an Arduino as a node.js server, but we can communicate with it and get it to do database calls and the like. We will be using an interesting plugin for Node.js called “johnny-five”.
We will assume at this point that you have a working Arduino environment. Any Arduino should work, but for this article, we will be using an Arduino UNO. You can hook up an LED, but for the purpose of this, we will use the built-in LED on pin 13.
However johnny-five will work with most Arduino compatible boards including Uno, Mega, Leonardo, Fio, Pro and Pro mini. This really does open some grat ideas and possibilities. Combine this with an ESP processor and you can have node based control via wifi.
On the Arduino side, we don’t have to write any code. We will be using the standard firmata. Firmata is a generic protocol for communicating with micro-controllers from software on a host computer, and it is intended to work with any host computer software package. With the Arduino IDE open, select Files > Examples > Firmata > StandardFirmata. Once it is open, upload it.
Next, we need to install the johnny-five libraries for Node.js. Go to the command line and enter:
npm install johnny-five
Below is the Node.js code required to communicate with our Arduino via Firmata. Open up your preferred text editor and place the following code.
var five = require(‘johnny-five’);
var board = new five.Board();
board.on(‘ready’, function() {
var led = new five.Led(13); // pin 13
led.blink(500); // 500ms interval
});
Here in the first two lines are our variable declarations. The first creates an instance of the johnny-five library; the second is to create the board object. Board.on is only on function here, and it relates to the board. The first line declares which pin will be our LED pin. The second calls a built-in function in the library called blink and instructs it to do so at 500ms intervals.
Once you have saved the file, open the command line and navigate to where your file is saved. If you are using Mac or Linux, you will need to enter the sudo command at the beginning to give the system access to hardware. You will be asked to input a password.
sudo node five.js
You will get confirmation in your command line window, and pin 13’s built-in LED will flash. Terminate the command, and the LED will stop flashing.
WHERE TO FROM HERE?
We have not even scratched the surface of what is achievable here. The resources available in the Node package manager is amazing. Need a database to work on your project? Download and install the MySQL library. Don’t like MySQL? Download the MongoDB package. This linked with the web interface means no building propriety apps for different phones or tablets.