Skip to content

Instantly share code, notes, and snippets.

@bebraw

bebraw/send.js

Last active Aug 29, 2015
Embed
What would you like to do?
#!/usr/bin/env node
'use strict';
var PORT = 9909;
var HOST = '172.18.12.2';
var LIGHTS = 36;
var dgram = require('dgram');
var Animation = require('animation').Animation;
var flatten = require('annofp').flatten;
var range = require('annomath').range;
main();
function main() {
animate({
nick: 'bebraw',
sequence: wave({
rgb: [255, 0, 0]
}),
/*fadeIn({
min: 0,
max: 255,
step: 5
}).concat(fadeOut({
min: 0,
max: 255,
step: 5
})),*/
interval: '100ms',
times: 5
});
}
function wave(o) {
return range(LIGHTS).map(function(v) {
return [{
id: v,
rgb: o.rgb
}];
});
}
function wave2(o) {
return range(LIGHTS).map(function(v) {
var ret = setAll({rgb: [0, 0, 0]});
ret[v].rgb = o.rgb;
return ret;
});
}
function fadeIn(o) {
var min = o.min || 0;
var max = o.max || 255;
var step = o.step || 1;
return range(min, max + 1, step).map(function(v) {
return setAll({rgb: [v, v, v]});
});
}
function fadeOut(o) {
var min = o.min || 0;
var max = o.max || 255;
var step = o.step || 1;
return range(min, max + 1, step).reverse().map(function(v) {
return setAll({rgb: [v, v, v]});
});
}
/*
demos
[
setAll({rgb: [128, 128, 128]}),
setAll({rgb: [128, 128, 128]})
]
[
[{
id: 10,
rgb: [0, 0, 255]
},
{
id: 13,
rgb: [0, 0, 255]
}],
[{
id: 10,
rgb: [255, 0, 0]
},
{
id: 13,
rgb: [255, 0, 0]
}]
]
*/
function setAll(o) {
return range(LIGHTS).map(function(v) {
return {
id: v,
rgb: o.rgb
};
});
}
function animate(o) {
var animation = new Animation({
frame: o.interval
});
var frames = o.sequence.map(function(frame) {
return flatten(frame.map(function(v) {
return [1, v.id, 0].concat(v.rgb);
}));
});
var times = o.times || 1;
var i = 0;
var j = 0;
animation.on('tick', function() {
var frame;
if(!frames[i]) {
j++;
if(j === times) {
animation.stop();
}
i = 0;
}
frame = frames[i];
sendMessage(o.nick, frame);
i++;
});
animation.start();
}
function sendMessage(nick, light) {
var message = [1, 0].concat(toOrdinals(nick)).concat([0]).concat(light);
var client = dgram.createSocket('udp4');
client.send(new Buffer(message), 0, message.length, PORT, HOST, function(err) {
if(err) {
return console.error(err);
}
client.close();
});
}
function toOrdinals(str) {
return str.split('').map(function(v) {
return v.charCodeAt(0);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment