IIoT edge development – Using WebSockets

Editor's Note: The Industrial Internet of Things (IIoT) promises to provide deep insight into industrial operations and enhance efficiency of connected machines and systems. Large-scale IIoT applications rely on layered architectures to collect data from a broad range of sensors, move data reliably and securely to the cloud, and perform analysis required to deliver that insight and efficiency. In Industrial Internet Application Development, the authors provide a detailed examination of the IIoT architecture and discuss approaches for meeting the broad requirements associated with these systems. 

Adapted from Industrial Internet Application Development, by Alena Traukina, Jayant Thomas, Prashant Tyagi, Kishore Reddipalli.


Chapter 3. IIoT Edge Development (Continued)
By Alena Traukina, Jayant Thomas, Prashant Tyagi, Kishore Reddipalli

Application-level protocols – WebSocket

In this section, we will try to build a simple IoT app for sending data from an XD-80 light sensor module to a receiver device, using a Raspberry Pi hub and the WebSocket protocol:


Data flow from an XD-80 sensor to a receiver device

WebSocket is most widely used in the case that one needs to enable fast transfer of real-time data. The protocol allows for two-way interaction between a client and a server, and for streaming multiple messages using the same TCP connection, which lowers the communications overhead.

In the following table, you can find a more detailed description of the protocol to understand whether it is suitable for your needs:

Key Value
Open source Yes
The OSI layer Application
Data types String
Limitations Not suitable for large amounts of binary data
Possible operations Send/receive data
Latency Very low
Usage Real-time communication
Security Yes
Compression Yes

Table 3: WebSocket protocol specifications

For building the application, we will need the following.

Required software:

Required hardware:

  • Raspberry Pi 3 (model B)
  • A power adapter (2A/5V)
  • A microSD card (8 GB+) and an SD adapter
  • A XD-80 light sensor module
  • A breadboard and a set of dupont cables
  • An Ethernet cable for a wired network connection


Assembling a device

Before building an application, you need to connect an XD-80 sensor to a Raspberry Pi via a breadboard.

Preparing an SD card

To prepare an SD card, follow the sequence of actions as described:

  1. Download the latest Raspbian LITE image (available at https://raspberrypi.org/downloads/raspbian/ ).
  2. Connect your SD card to a computer and use Etcher (https://io/ ) to flash the Raspbian .img file to the SD card.
  3. Enable SSH using the following command:


      cd /Volumes/boot
      touch ssh

  1. To enable Wi-Fi, create conf with the following content:


      network={
         ssid=”YOUR_SSID”
         psk=”YOUR_WIFI_PASSWORD”
      }

To create a file in a Linux console, you can use the GNU nano editor. It is pre-installed in most Linux distributives. All you need is to run the nano FILE_NAME command and follow the displayed instructions.
  1. Create the /home/pi/sensor
  2. Create the /home/pi/sensor/package.json file with the following content:


   {
      “name”: “sensor”,
      “version”: “1.0.0”,
      “description”: “”,
      “main”: “index.js”,
      “scripts”: {
         “start”: “node index.js”,
         “test”: “echo “Error: no test specified” && exit 1″
      },
      “author”: “”,
      “license”: “ISC”,
      “dependencies”: { “rpio”: “^0.9.16”,
         “ws”: “^2.3.1”
      }
   }

  1. Create the /home/pi/sensor/index.js file with the following content, replacing REMOTE-SERVER-ADDRESS.com with a real value:


      var WebSocket = require('ws');
      var rpio = require('rpio');
   
      var ws;
      var receiver = 'ws://REMOTE-SERVER-ADDRESS.com:8080';
      rpio.open(11, rpio.INPUT);
   
      var establishConnection = function () {
         ws = new WebSocket(receiver);
         ws.on('close', establishConnection);
         ws.on('error', establishConnection);
      };
      establishConnection();
   
      var sendStatus = function () {
         var status = rpio.read(11) === 0;
         console.log('light status: ' + status);
         var data = JSON.stringify({
            device: 'raspberry',
            timestamp: Date.now(),
            light: status
         });
   
         try { ws.send(data); }
         catch (e) {console.log('failed to send data to ' + receiver);}
   
         setTimeout(sendStatus, 1000);
      };
      sendStatus();

  1. Create the /home/pi/sensor/Dockerfile file with the following content:


      FROM hypriot/rpi-node:boron-onbuild

Running a sensor application on an RPi

To run a sensor application on an RPi, proceed as the following steps suggest:

  1. Insert an SD card into the RPi.
  2. Connect an Ethernet cable and open an SSH connection.
  3. Navigate to /home/pi/sensor .
  4. Build an image and run a Docker container:

      # Build an image from a Dockerfile
      docker build -t websocket-sensor .

      #
      # Run container in foreground
      docker run –privileged -it –rm –name websocket-sensor-container
      websocket-sensor

      #
      # Run container in background
      # docker run –privileged -d  –rm –name websocket-sensor-
      container websocket-sensor

      #
      # Fetch the logs of a container
      # docker logs -f websocket-sensor-container
      #
      # Stop running container
      # docker stop websocket-sensor-container    


Console output when a sensor app is running

Running a receiver application on a PC

To run a receiver app on a PC, follow this sequence:

  1. Create the receiver
  2. Create the ./receiver/package.json file with the following content:


      {
         “name”: “receiver”,
         “version”: “1.0.0”,
         “description”: “”,
         “main”: “index.js”, “scripts”: {
            “start”: “node index.js”,
            “test”: “echo “Error: no test specified” && exit 1″
         },
         “author”: “”,
         “license”: “ISC”, “dependencies”: {
            “ws”: “^2.3.1”
         }
      }

  1. Create the ./receiver/index.js file with the following content:


      const WebSocket = require('ws');
      const wss = new WebSocket.Server({port: 8080}, function () {
         console.log('Websocket server started');
      });
      wss.on('connection', function connection(ws) {
         ws.on('message', function incoming(message) {
            console.log('received: ', message);
         });
         // Send message to connected client ws.send('hello, client');
      });

  1. Create the ./receiver/Dockerfile file with the following content:


      FROM node:boron-onbuild EXPOSE 8080

  1. Navigate to ./receiver .
  1. Build an image and run a Docker container:


      # Build an image from a Dockerfile
      docker build -t websocket-receiver
      
      # Run container in foreground
      docker run -p 8080:8080 -it –rm –name websocket-receiver-
      container websocket-receiver

      
      # Run container in background
      # docker run -p 8080:8080 -d  –rm –name websocket-receiver-
      container websocket-receiver

      
      # Fetch the logs of a container
      # docker logs -f websocket-sensor-container
      
      # Stop running container
      # docker stop websocket-receiver-container
       

The console output displays that the application is running:


Console output when a receiver app is running

Reprinted with permission from Packt Publishing. Copyright © 2018 Packt Publishing


About the authors

Alena Traukina is IoT practice Lead at Altoros. She has over 12 years of experience in delivery and support of business-critical software applications and is one of the first GE's Predix Influencers.

Jayant Thomas (JT) is the director of software engineering for the IoT apps for GE Digital. He is responsible for building IoT SaaS applications using the Predix platform, and specializes in building microservices-based architecture, reactive, event-driven systems.

Prashant Tyagi is responsible for enabling the big data strategy at GE Digital for the Industrial Internet that leverages IT and Operational data for predictive analytics. He works with all the P&L verticals (such as oil and gas, power generation, aviation, healthcare, and so on) to enable their IoT use cases on the data and analytics platform.

Kishore Reddipalli is a software technical director and expert in building IIoT big data and cloud computing platform and products at ultra scale. He is passionate in building software for analytics and machine learning to make it simplified for authoring the algorithms from inception to production at scale.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.