Tag Archive for IoT

Recording sensor data with MongoDB Stitch & Electric Imp

Old school IoT

My early experiments with IoT involved standalone sensors, breakout boards, Arduinos, Raspberry Pis, and a soldering iron. It was a lot of fun, but it took ages to build even the simplest of projects.

Therefore, I was super excited when I discovered that Electric Imp had a self-contained IoT hardware developer kit and a library to access MongoDB Stitch directly.

Electric Imp impExplorer IoT development kit

My first experiment with Electric Imp took sensor data (temperature, humidity, air pressure, light level, and orientation) from the device, and stored it in MongoDB.

The Electric Imp code (written in Squirrel) is split into 2 parts:
– On-device code – sends sensor data to the agent
– Agent code, running in Electric Imp’s cloud – forwards the data to Stitch

This post focuses on the integration between the Electric Imp agent code and Stitch, but those interested can view the device code.

The agent code receives the readings from the device, and then it uses the Electric Imp MongoDB Stitch library to forward them to Stitch:

#require "MongoDBStitch.agent.lib.nut:1.0.0"

//Create the connection to Stitch
stitch <- MongoDBStitch("imptemp-sobpa");

//Add an API key to link this device to a specific Stitch User
const API_KEY = "hNErDmBw1zYGOfpaSv4Pf5kaNQrIaxOHLZgj0vExzDcxWf9GAEX055l1mXXX";

//Ensure you are authenticated to Stitch
stitch.loginWithApiKey(API_KEY);

function log(data) {
    stitch.executeFunction("Imp_Write", [data], function (error, response) {
        if (error) {
            server.log("error: " + error.details);
        } else {
            server.log("temperature sent");
        }
    });
}

// Register a function to receive sensor data from the device
device.on("reading.sent", log);

Note that you will need to create the API_KEY through the Stitch UI.

impExplorer sends readings to Electric Imp agent which sends them to MongoDB Stitch to store in MongoDB Atlas

The Imp_Write function receives the readings from the agent, retrieves outside weather data from DarkSky.net, and stores the data in the TempData MongoDB Atlas collection:

exports = function(data){

  //Get the current time
  var now = new Date();

  var darksky = context.services.get("darksky");
  var mongodb = context.services.get("mongodb-atlas");
  var TempData = mongodb.db("Imp").collection("TempData");

  // Fetch the current weather from darksky.net

  darksky.get({"url": "https://api.darksky.net/forecast/" + 
    context.values.get("DarkSkyKey") + '/' + 
    context.values.get("DeviceLocation") +
    "?exclude=minutely,hourly,daily,alerts,flags&units=auto"
  }).then(response => {
    var darkskyJSON = EJSON.parse(response.body.text()).currently;

    var status =
      {
        "Timestamp": now.getTime(),
        "Date": now,
        "Readings": data,
        "External": darkskyJSON,
      };
    status.Readings.light = (100*(data.light/65536));
    context.functions.execute("controlHumidity", data.temp, data.humid);
    TempData.insertOne(status).then(
      results => {
        console.log("Successfully wrote document to TempData");
      },
      error => {
        console.log("Error writing to TempData collection: " + error);
      });
  });
};

ImpWrite also calls the controlHumidity method – find more on that in this post.

You can recreate the Stitch app for yourself by downloading the app from GitHub and importing it into Stitch. You’ll need to set some of your own keys first (including the details of your IFTTT webhook address) – details are in the README. The repo also includes the Electric Imp code for the agent and device.

Creating your first Stitch app? Start with one of the Stitch tutorials.

Want to learn more about MongoDB Stitch? Read the MongoDB Stitch white paper.





Controlling humidity with a MongoDB Stitch HTTP service and IFTTT

I’ve long been a fan of using IFTTT as a quick and easy way to automate my home/life by connecting cloud and IoT services. My IFTTT Applets are what make my study lights flash when my Amazon Alexa timer expires in the kitchen; they’re what add my FourSquare check-ins to my Google calendar and MongoDB database.

I have a dumb dehumidifier in my study, and I wanted to make it a bit smarter using MongoDB Stitch. I use an ElectricImp IoT device to send periodic temperature and humidity sensor readings to my Stitch app. The Stitch app then fetches weather data from DarkSky.net and stores the combined data in a MongoDB collection. I have a dashboard that lets me view that data over time.

Based on the latest humidity and temperature, a Stitch function decides whether to turn the humidifier on or off. The function then uses a Stitch HTTP service I created to send a request an IFTTT Maker service webhook with the desired state (on|off).

exports = function(temp, humidity){

  var IFTTT = context.services.get("IFTTT");

  // The humidifier is very inefficient if room is too cold, so only turn
  // it on if the humidity is too high and temperature is high enough

  var state = "dry";

  if (temp > context.values.get("minTemp")) {
    if (humidity > context.values.get("maxHumidity")) {
        state = "damp";
    }
  }

  IFTTT.get({"url": "https://maker.ifttt.com/trigger/" + 
    state + "/with/key/" + 
    context.values.get("MakerIFTTKey")})
  .then(() => {
    console.log("Sent IFTTT request");
  });
};

The webhook uses the TP-Link Kasa IFTTT service to send an on|off request to my smart plug:

IFTTT Webhook to turn plug onn

You can recreate this Stitch app for your self by downloading the app from GitHub and importing into Stitch. You’ll need to set some of your own keys first (including the details of your IFTTT webhook address) – details are in the README. The repo also includes the ElectricImp device and agent code.

Creating your first Stitch app? Start with one of the Stitch tutorials.

Want to learn more about MongoDB Stitch? Read the white paper.