Skip to content

Instantly share code, notes, and snippets.

@cat-haines
Created April 20, 2013 00:02
Show Gist options
  • Select an option

  • Save cat-haines/5424076 to your computer and use it in GitHub Desktop.

Select an option

Save cat-haines/5424076 to your computer and use it in GitHub Desktop.
Electric Imp example API
local greenState = 0;
local redState = 0;
device.on("setRed", function(data) {
redState = data;
});
device.on("setGreen", function(data) {
greenState = data;
});
http.onrequest(function(request, response) {
local code = null;
local message = null;
if (request.path == "/lights")
{
if (request.method == "GET")
{
code = 200;
message = "{ 'red': " + redState + ", 'green': " + greenState + " }";
}
else if (request.method == "POST")
{
try {
local data = http.jsondecode(request.body);
if ("red" in data)
{
server.log("red: " + data.red);
device.send("setRed", data.red);
}
if("green" in data)
{
server.log("green: " + data.green);
device.send("setGreen", data.green);
}
code = 200;
message = "OK";
}
catch (e) {
code = 501;
message = "Unacceptable";
server.log(e);
}
}
}
else
{
code = 404;
message = "Not Found";
}
response.send(code, message);
});
class LEDController{
pin = null;
colour = null
state = 0;
constructor(ledPin, ledColour){
pin = ledPin;
colour = ledColour;
pin.configure(DIGITAL_OUT);
}
function TurnOn(){
Write(1);
}
function TurnOff(){
Write(0);
}
function Write(newState){
if (newState == 0 || newState == 1)
{
state = newState;
server.log(colour + ": " + newState);
agent.send("set" + colour, newState);
pin.write(newState);
}
else
{
server.log(newState + " is not a valid LED state. Please use 0 or 1.");
}
}
};
local RedLED = LEDController(hardware.pin2, "Red");
local GreenLED = LEDController(hardware.pin5, "Green");
RedLED.TurnOff();
GreenLED.TurnOff();
agent.on("setGreen", function(state) {
GreenLED.Write(state);
});
agent.on("setRed", function(state) {
RedLED.Write(state);
});
imp.configure("Red Light Green Light",[],[]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment