2.2. Blinky from Node

2.2.1. Introduction

The previous tutorial shows how to use a Bash script to set the Gateway’s status LED color and pattern. This tutorial will demonstrate creating a Node application to change the status LED based on certain conditions.

Specifically, we’ll be querying an API for the temperature, and setting the LED according to that.

The complete code for this tutorial is available on GitLab.

In code samples in this document, each command will be preceded by the command prompt, in this case root@080030717-00055:~/node-blinky-weather#.

2.2.2. Login and Setup

  1. First, log in to the Vesta gateway. This will put you in the home directory.

  2. Create a directory for this project.

    root@080030717-00055:~# mkdir node-blinky-weather
    root@080030717-00055:~# cd node-blinky-weather/
    
  3. Initialize an empty Node project.

    root@080030717-00055:~/node-blinky-weather# npm init -y
    Wrote to /home/root/node-blinky-weather/package.json:
    
    {
      "name": "node-blinky-weather",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "",
      "license": "ISC"
    }
    

2.2.4. Blinking Based on the Weather

We can now modify the application to set the status LED color based upon an external condition – in this case, the local temperature.

  1. Begin by installing a third-party weather tool:

    root@080030717-00055:~/node-blinky-weather# npm install --save weather-js
    
  2. Update the index.js file with new code that uses weather-js:

    'use strict';
    
    const execFile = require('child_process').execFile;
    const weather = require('weather-js');
    
    weather.find({ search: 'Portland, OR', degreeType: 'F' }, (err, result) => {
      if (err) {
        console.log(`err: ${err}`);
      } else {
        const temp = result[0].current.temperature;
        if (temp >= 85) {
          console.log('Over 85 degrees! Red-hot!');
          execFile('/usr/rigado/scripts/led_control.sh', ['red', 'flash']);
        } else if (temp >= 60) {
          console.log('60-84 degrees. Perfect.');
          execFile('/usr/rigado/scripts/led_control.sh', ['green', 'solid']);
        } else {
          console.log('<60 degrees. A bit mild.');
          execFile('/usr/rigado/scripts/led_control.sh', ['yellow', 'solid']);
        }
      }
    });
    

The first part of the weather.find call, { search: 'Portland, OR', degreeType: 'F' }, tells weather-js to search for weather reports for Portland, Oregon. The subsequent result[0].current.temperature picks out the current temperature from the first weather report in the list.

  1. Executing the script should now make the status LED change based on the current temperature:

    root@080030717-00055:~/node-blinky-weather# node index.js
    Over 85 degrees! Red-hot!
    

The complete code for this tutorial is available on GitLab.