Skip to content

Instantly share code, notes, and snippets.

@ersatzavian
Last active September 9, 2015 22:30
Show Gist options
  • Save ersatzavian/62cd91df315064449834 to your computer and use it in GitHub Desktop.
Save ersatzavian/62cd91df315064449834 to your computer and use it in GitHub Desktop.
Rocky-Based HTTP API for RGB LEDs
// AGENT CODE
#require "rocky.class.nut:1.2.2"
// instantiate the Rocky framework for our API
app <- Rocky();
// say hello if someone requests our Agent URL
app.get("/", function(context) {
context.send("Try adding a color (red, green, blue) to the path!");
});
app.get("/red", function(context) {
device.send("setcolor", [50, 0, 0]);
context.send("Color set to Red!");
});
app.get("/green", function(context) {
device.send("setcolor", [0, 50, 0]);
context.send("Color set to Green!");
});
app.get("/blue", function(context) {
device.send("setcolor", [0, 0, 50]);
context.send("Color set to Blue!");
});
// Just for fun: decoding hex colors
// ascii hex digit to decimal
function hexdec(c) {
if (c <= '9') {
server.log(c - '0');
return c - '0';
} else {
server.log(0x0A + c - 'A');
return 0x0A + c - 'A';
}
}
function decodeColorString(colorString) {
colorString = colorString.toupper();
local rStr = colorString.slice(1,3);
local gStr = colorString.slice(3,5);
local bStr = colorString.slice(5,7);
local red = (hexdec(rStr[0]) * 16) + hexdec(rStr[1]);
local green = (hexdec(gStr[0]) * 16) + hexdec(gStr[1]);
local blue = (hexdec(bStr[0]) * 16) + hexdec(bStr[1]);
local rgb = [red, green, blue];
return rgb;
}
app.get("/[a-f0-9]{6}", function(context) {
local color = decodeColorString(context.matches[0]);
device.send("setcolor", color);
context.send(("Set Color to (%d, %d, %d)", color));
});
// DEVICE CODE
#require "ws2812.class.nut:2.0.1"
// create a SPI object to use to control the WS2812 LEDs
spi <- hardware.spi257;
// configure SPI to run at 7.5 MHz
spi.configure(MSB_FIRST, 7500);
// instantiate WS2812 class to create object for our 5 LEDs
leds <- WS2812(spi, 5);
// fill frame buffer with green pixels to test LEDs
// red brightness: 0/255, green: 50/255, blue: 0/255
leds.fill([0, 50, 0]);
// write out frame buffer
leds.draw();
// register agent callback for "setcolor" event
agent.on("setcolor", function(color) {
leds.fill(color);
leds.draw();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment