6cz53w
Last Updated: February 25, 2016
·
1.594K
· thure

Getting Electric Imps to phone home, improving availability

If you haven't heard, Electric Imp is where it's at when it comes to making a low-level electronic device (like a servo or a relay) able to respond to input on the Internet.

I recently hooked up an Electric Imp to open my building door, which is a pretty elementary setup – the imp has a single digital out pin that drives a relay that "pushes" the buzz-in button on the intercom (this is what that imp looks like). The problem is I don't want just anyone with the imp's endpoint provided by the Electric Imp cloud service to be able to open my building door, so I created a node app that implements authorization to manage that endpoint.

But, there's a problem. Although the setup was very reliable in the beginning, it eventually became somewhat unreliable.

Hugo of Electric Imp suggested that imps that need to stay awake and connected to the cloud service should do a server.log “every few minutes.”

Hopefully upgrades to the cloud service can ameliorate this in the future, but for now here's what you've got to do if you want to keep your imp connected.

Imp code:

function phoneHome(){

    //Ping the cloud service.
    server.log("I'm still awake.");

    //Phone home again every 4 minutes.
    imp.wakeup(240, phoneHome);

}

Since I've got a web app already going, I decided to take that a step further and have the web app notify me in case the imp didn't phone home in 10 minutes.

Imp code:

//Create an OutputPort for your imp to send messages with.
local phone = OutputPort("Phone", "string");

function phoneHome(){

    //Send a request to the web app that contains the impee's id.
    phone.set("{\"awake\": true, \"id\": "+hardware.getimpeeid()+"}");

    //Ping the cloud service.
    server.log("I'm still awake.");

    //Phone home again every 4 minutes.
    imp.wakeup(240, phoneHome);

}

Connect the Output port “Phone” to an HTTP Out node in the Electric Imp planner. Give that node an endpoint that you can use to listen to the imp's calls. When your app receives a call, have it wait for an amount of time that's a little greater than the interval you gave the imp (I thought 10 minutes was reasonable given a 4 minute interval, but it's up to you).

You can then give your app a failed-to-phone-home feature that does whatever you like – mine sends me an email, and I use IFTTT to check for mail from the web app and send me a text if I get one.

Happy hacking!