Skip to main content

A Simple Remote Monitoring Application

An Introduction To Squirrel Applications Example 3

In this example we will create a simple remote monitoring application that takes synchronous readings from multiple sensors and sends them to the cloud using the Initial State service. We will use a Hardware Abstraction Layer (HAL) to reference all hardware objects, and to organize our application code we will use a class. This code can be easily configured for use with an imp006 Breakout Kit, impExplorer Kit, impAccelerator Battery Powered Sensor Node or impC001 Breakout Board.

Skill level

Beginner

This example will focus on writing Squirrel code. Please visit the Getting Started Guide on the Electric Imp Dev Center to learn how to configure your device with BlinkUp™ and how to use the Electric Imp IDE, impCentral™.

What You Learn

  • How to use Electric Imp libraries.
  • How to configure a sensor and take synchronous readings.
  • How to send data between device and agent.
  • How to send data to a cloud service such as Initial State.
  • How to use a Hardware Abstraction Layer (HAL).
  • How to write a class in Squirrel.

What You Need

Instructions

// HARDWARE ABSTRACTION LAYER
// ---------------------------------------------------
// HAL's are tables that map human readable names to
// the hardware objects used in the application.

// Copy and Paste Your HAL here
ExplorerKit_001 <- {
    "LED_SPI" : hardware.spi257,
    "SENSOR_AND_GROVE_I2C" : hardware.i2c89,
    "TEMP_HUMID_I2C_ADDR" : 0xBE,
    "ACCEL_I2C_ADDR" : 0x32,
    "PRESSURE_I2C_ADDR" : 0xB8,
    "POWER_GATE_AND_WAKE_PIN" : hardware.pin1,
    "AD_GROVE1_DATA1" : hardware.pin2,
    "AD_GROVE2_DATA1" : hardware.pin5
}
  • Assign your hardware class variables. In the Application class before the constructor you will find a number of class variables. You will need to re-assign the hardware variables so they look something like the example below. Do not copy and paste from this example, as these values may differ from the ones in your HAL.
// REMOTE MONITORING APPLICATION CODE
// ---------------------------------------------------
// Application code, take readings from our sensors
// and send the data to the agent

class Application {

    // Time in seconds to wait between readings
    static READING_INTERVAL_SEC = 30;
    // Accelerometer data rate in Hz
    static ACCEL_DATARATE = 1;

    // Hardware variables
    i2c             = ExplorerKit_001.SENSOR_AND_GROVE_I2C;
    tempHumidAddr   = ExplorerKit_001.TEMP_HUMID_I2C_ADDR;
    accelAddr       = ExplorerKit_001.ACCEL_I2C_ADDR;

    // Sensor variables
    tempHumid = null;
    accel = null;

    constructor() {...}
  • Copy and paste the Agent Code into the Agent Code pane in the impCentral code editor.
  • Sign into Initial State.
  • Find your Streaming Access Key on the My Account page.
  • Navigate back to impCentral.
  • In the Agent code enter your Streaming Access Key into the Application class static variable STREAMING_ACCESS_KEY on line 23.
  • Hit the Build and Force Restart button to start the code.
  • Note the agent ID in the logs.
  • Navigate back to Initial State, find the Bucket that matches your agent ID.
  • Watch your data update in the Source, Lines, Waves and Tile views on the Initial State website.

Code

Device Code

// Simple Remote Monitoring Application Device Code
// ---------------------------------------------------
// SENSOR LIBRARIES
// ---------------------------------------------------
// Libraries must be required before all other code
// Accelerometer Library
#require "LIS3DH.device.lib.nut:2.0.2"
// Temperature Humidity sensor Library
#require "HTS221.device.lib.nut:2.0.1"
// HARDWARE ABSTRACTION LAYER
// ---------------------------------------------------
// HAL's are tables that map human readable names to
// the hardware objects used in the application.
// Copy and Paste Your HAL here
// YOUR_HAL <- {...}
// REMOTE MONITORING APPLICATION CODE
// ---------------------------------------------------
// Application code, take readings from our sensors
// and send the data to the agent
class Application {
// Time in seconds to wait between readings
static READING_INTERVAL_SEC = 30;
// Accelerometer data rate in Hz
static ACCEL_DATARATE = 1;
// Hardware variables
i2c = null; // Replace with your sensori2c
tempHumidAddr = null; // Replace with your tempHumid i2c addr
accelAddr = null; // Replace with your accel i2c addr
// Sensor variables
tempHumid = null;
accel = null;
constructor() {
// Power save mode will reduce power consumption when the radio
// is idle, a good first step for saving power for battery
// powered devices.
// NOTE: Power save mode will add latency when sending data.
// Power save mode is not supported on impC001 and is not
// recommended for imp004m, so don't set for those types of imps.
local type = imp.info().type;
if (type != "imp004m" && type != "impC001") {
imp.setpowersave(true);
}
initializeSensors();
}
function run() {
// Set up the reading table with a timestamp
local reading = { "time" : time() };
// Add temperature and humidity readings
local result = tempHumid.read();
if ("temperature" in result) reading.temperature <- result.temperature;
if ("humidity" in result) reading.humidity <- result.humidity;
// Add accelerometer readings
result = accel.getAccel();
if ("x" in result) reading.accel_x <- result.x;
if ("y" in result) reading.accel_y <- result.y;
if ("z" in result) reading.accel_z <- result.z;
// Send readings to the agent
agent.send("reading", reading);
// Schedule the next reading
imp.wakeup(READING_INTERVAL_SEC, run.bindenv(this))
}
function initializeSensors() {
// Configure i2c
i2c.configure(CLOCK_SPEED_400_KHZ);
// Initialize sensors
tempHumid = HTS221(i2c, tempHumidAddr);
accel = LIS3DH(i2c, accelAddr);
// Configure sensors to take readings
tempHumid.setMode(HTS221_MODE.ONE_SHOT);
accel.reset();
accel.setMode(LIS3DH_MODE_LOW_POWER);
accel.setDataRate(ACCEL_DATARATE);
accel.enable(true);
}
}
// RUNTIME
// ---------------------------------------------------
server.log("Device running...");
// Initialize application
app <- Application();
// Start reading loop
app.run();

Agent Code

// Simple Remote Monitoring Application Agent Code
// ---------------------------------------------------
// CLOUD SERVICE LIBRARY
// ---------------------------------------------------
// Libraries must be required before all other code
// Initial State Library
#require "InitialState.class.nut:1.0.0"
// REMOTE MONITORING APPLICATION CODE
// ---------------------------------------------------
// Application code, listen for readings from device,
// when a reading is received send the data to Initial
// State
class Application {
// On Intial State website navigate to "my account"
// page find/create a "Streaming Access Key"
// Paste it into the variable below
static STREAMING_ACCESS_KEY = "";
// Class variables
iState = null;
agentID = null;
constructor() {
// Initialize Initial State
iState = InitialState(STREAMING_ACCESS_KEY);
// The Initial State library will create a bucket
// using the agent ID
agentID = split(http.agenturl(), "/").top();
// Let's log the agent ID here
server.log("Agent ID: " + agentID);
device.on("reading", readingHandler.bindenv(this));
}
function readingHandler(reading) {
// Log the reading from the device. The reading is a
// table, so use JSON encodeing method convert to a string
server.log(http.jsonencode(reading));
// Initial State requires the data in a specific structre
// Build an array with the data from our reading.
local events = [];
events.push({"key" : "temperature", "value" : reading.temperature, "epoch" : reading.time});
events.push({"key" : "humidity", "value" : reading.humidity, "epoch" : reading.time});
events.push({"key" : "accel_x", "value" : reading.accel_x, "epoch" : reading.time});
events.push({"key" : "accel_y", "value" : reading.accel_y, "epoch" : reading.time});
events.push({"key" : "accel_z", "value" : reading.accel_z, "epoch" : reading.time});
// Send reading to Initial State
iState.sendEvents(events, function(err, resp) {
if (err != null) {
// We had trouble sending to Initial State, log the error
server.error("Error sending to Initial State: " + err);
} else {
// A successful send. The response is an empty string, so
// just log a generic send message
server.log("Reading sent to Initial State.");
}
})
}
}
// RUNTIME
// ---------------------------------------------------
server.log("Agent running...");
// Run the Application
Application();