Using Devicehub with Electric Imp

After using Pachube/Cosm/Xively for quite a while while the Electric Imp planner was still in use, I wanted to try something new and simpler with the new Agent.

With the new firmware (release 27.9) it is now possible to get a reading of the light level, so why not make a little tutorial on how to log this?

After creating a project on the devicehub.net site you will get a API key and project number. Insert the two into the agent code.

You will also need a sensor. Create that on the site too and insert it’s name into the agent too.

Agent:

device.on("updateLight", function(msg)
{
  local devicehubApiKey = "api key here";
  local devicehubProject = projectnum;
  local sensor = "sensor name";

  addDevicehub(devicehubApiKey, devicehubProject, sensor, msg);
});

function addDevicehub(key, project, sensor, value)
{
  local url = "http://devicehub.net/io/" + project + "/?apiKey=" + key + "&" + sensor + "=" + value;

  http.get(url).sendasync(function(resp)
  {
    if (resp.statuscode = 200)
    {
      server.log("Devicehub sensor '" + sensor + "' got updated with the value " + value);
    }
    else
    {
      server.log(format("%i: %s", resp.statuscode, resp.body));
    }
  })
}

Device:

On the device we collect the numbers we want to send to devicehub, then sends it over to the agent.

function devicehub()
{
  agent.send("updateLight", hardware.lightlevel());
  imp.wakeup(60, devicehub); //Do this again in 1 minute
}
devicehub();

This should now end up looking something like this: http://devicehub.net/project/221/

Leave a Reply