Skip to content

Instantly share code, notes, and snippets.

Created October 5, 2014 00:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/c5bdf2e1436563f162cb to your computer and use it in GitHub Desktop.
Save anonymous/c5bdf2e1436563f162cb to your computer and use it in GitHub Desktop.
Shenanigans
var dgram = require('dgram');
var client = dgram.createSocket('udp4');
var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
app.use(express.static(__dirname + '/static'));
server.listen(8888);
var timeout = -1;
var color = {r: 0, g: 0, b: 0};
var brightness = 0;
var lastBrightness = 255;
function sendColor(r, g, b){
if(!isNaN(r) && !isNaN(g) && !isNaN(b)
&& r >= 0 && g >= 0 && b >= 0
&& r < 256 && g < 256 && b < 256){
color = {r: r, g: g, b: b};
var msg = new Buffer([0x23, r, g, b, 0x0a]);
client.send(msg, 0, msg.length, 8888, "192.168.0.20");
return true;
}return false;
}
function sendBrightness(n){
if(!isNaN(n) && n >= 0 && n < 256){
brightness = n;
msg = new Buffer([0x25, n, 0x0a]);
client.send(msg, 0, msg.length, 8888, "192.168.0.20");
return true;
}return false;
}
app.get("/hex/:hex", function(req, res){
var color = hexToRgb(req.params.hex);
if(sendColor(color.r, color.g, color.b))
res.send(".");
else
res.send("Bad color (should be HTML-like hex string without hash symbol).");
});
app.get("/rgb/:r/:g/:b", function(req, res){
if(sendColor(parseInt(req.params.r),
parseInt(req.params.g),
parseInt(req.params.b)))
res.send(".");
else
res.send("Bad color (should be 3 slash-delimited bytes).");
});
app.get("/brightness/:brightness", function(req, res){
var input = parseInt(req.params.brightness);
if(sendBrightness(input)){
lastBrightness = input;
res.send(".");
}else
res.send("Bad brightness (should be a single byte).");
});
app.get("/keepAlive", function(req, res){
if(timeout !== -1)
clearTimeout(timeout);
timeout = setTimeout(goDark, 5 * 60000);
if(brightness !== lastBrightness)
sendBrightness(lastBrightness);
res.send(".");
});
function goDark(){
if(timeout !== -1)
clearTimeout(timeout);
timeout = -1;
sendBrightness(0);
}
function hexToRgb(hex){
var result = /^([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment