Skip to content

Instantly share code, notes, and snippets.

@cat-haines
Last active December 20, 2015 19:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cat-haines/6187679 to your computer and use it in GitHub Desktop.
Save cat-haines/6187679 to your computer and use it in GitHub Desktop.
This GIST has four files and demonstrates how data can be passed from one imp to another using HTTP requests, and HTTP request handlers.
const otherAgentUrl = "http://agent.electricimp.com/YourOtherAgentID";
// create a handler for the "button" message from the device
device.on("button", function(state) {
local url = otherAgentUrl + "?led=" + state;
server.log("sending request to " + url);
// create the request
local request = http.get(url);
// send the request
request.sendsync();
});
server.log("Copy this URL to your other agent (otherAgentURL): " + http.agenturl());
server.log("Turn LED on by calling: " + http.agenturl() + "?led=1");
server.log("Turn LED off by calling: " + http.agenturl() + "?led=0");
// setup an HTTP handler to process incoming http requests
http.onrequest(function(request, response) {
try {
// check an 'led' query parameter was passed into the request
if (request.query != null && "led" in request.query) {
// if it was, pass it on the device
device.send("setLed", request.query.led.tointeger());
}
// send an http 200 to say everything was OK
response.send(200, "OK");
} catch (ex) {
// if there was an error, send back an http 500 and the error
response.send(500, "Internal Server Error: " + ex);
}
});
/* Hardware setup:
* connect a button or switch between pin9 and GND
*/
// it's considered best practice for every model to have an imp.configure
imp.configure("Button", [], []);
// assign hardware.pin9 to a variable to make things more clear
button <- hardware.pin9;
// function to be called when button state changes
function buttonStateChanged() {
// read the current state
local state = button.read();
// send it to the agent
agent.send("button", state);
}
// configure the button
button.configure(DIGITAL_IN_PULLUP, buttonStateChanged);
/* Hardware setup:
* connect an LED from Pin9 to GND (through a 339Ω resistor - orange, white, brown)
*/
// it's considered best practice for every model to have an imp.configure
imp.configure("LED", [], []);
// assign hardware.pin9 to a variable to make things more clear
led <- hardware.pin9;
led.configure(DIGITAL_OUT);
// turn LED off
led.write(0);
// value - 1 or 0
function setLed(value) {
led.write(value);
}
// setup a handler for setLed message from the agent
agent.on("setLed", setLed);
@ozzieg
Copy link

ozzieg commented Aug 20, 2013

This just beats XBee out of the water. What can I say?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment