Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<style type="text/css">
body {
background: #222;
color: #ddd;
font: 15px verdana;
}
#connectionStatus {
font-weight: bold;
font-size: 20px;
}
</style>
<script type="text/javascript">
/*
* Experiment with random Color Queue
*/
$(function() {
function hexToRgb(hex) {
// http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
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;
}
var DEFAULT_COLOR = {r:0,b:0,g:0};
// Set timeout between color changes, in milliseconds
var TIMEOUT = 3000;
// Set number of LEDs
var NUM_LEDS = 60;
function writeFrame() {
var packet = new Uint8Array(4 + NUM_LEDS * 3);
// console.log(packet);
if (socket.readyState != 1 /* OPEN */) {
// The server connection isn't open. Nothing to do.
return;
}
if (socket.bufferedAmount > packet.length) {
// The network is lagging, and we still haven't sent the previous frame.
// Don't flood the network, it will just make us laggy.
// If fcserver is running on the same computer, it should always be able
// to keep up with the frames we send, so we shouldn't reach this point.
return;
}
// Dest position in our packet. Start right after the header.
var dest = 4;
//http://www.paulirish.com/2009/random-hex-color-code-snippets/
var myRandColor = '#'+Math.floor(Math.random()*16777215).toString(16);
var myHtmlText = "<div style='color:" + myRandColor + "'>"+ myRandColor + "</div>";
var rgb = hexToRgb(myRandColor);
$("#colorQueue").append(myHtmlText);
// Sample the center pixel of each LED
for (var led = 0; led < NUM_LEDS; led++) {
//protection against null from hexToRgb().
if (rgb === null)
rgb = DEFAULT_COLOR;
packet[dest++] = rgb.r;
packet[dest++] = rgb.g;
packet[dest++] = rgb.b;
// send the command to the FadeCandy Server
socket.send(packet.buffer);
};
// Animation loop
var animate = function() {
setTimeout(animate, TIMEOUT);
};
// Connect to a Fadecandy server running on the same computer, on the default port
var socket = new WebSocket('ws://localhost:7890');
// Put some connection status text in the corner of the screen
$('#connectionStatus').text('Connecting to fcserver...');
socket.onclose = function(event) {
$('#connectionStatus').text('Not connected to fcserver');
socket.onopen = function(event) {
$('#connectionStatus').text('Connected');
animate();