Skip to content

Commit

Permalink
feat: Add pack(), setPixel() and clear()
Browse files Browse the repository at this point in the history
  • Loading branch information
jhinrichsen committed Jan 4, 2016
1 parent d6b3bf2 commit 3f5b209
Showing 1 changed file with 60 additions and 3 deletions.
63 changes: 60 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,27 @@ const fsp = require('fs-promise'),
}),

// Decodes 16 bit RGB565 into list [R,G,B]
rgb = n => {
unpack = n => {
let r = (n & 0xF800) >> 11,
g = (n & 0x7E0) >> 5,
b = (n & 0x1F),
rc = [ r << 3, g << 2, b << 3 ];
return rc;
},

// Encodes list [R, G, B] into 16 bit RGB565
pack = rgb => {
if (rgb.length != 3) throw new Error(`length = ${rgb.lenth} violates length = 3`);
let r = (rgb[0] >> 3) & 0x1F,
g = (rgb[1] >> 2) & 0x3F,
b = (rgb[2] >> 3) & 0x1F,
bits = (r << 11) + (g << 5) + b;
return bits;
},

// Map (x, y) into absolute byte position
pos = (x, y) => 2 * (y * 8 + x),

// Returns a list of [R,G,B] representing the pixel specified by x and y
// on the LED matrix. Top left = 0,0 Bottom right = 7,7
getPixel = (fb, x, y) => {
Expand All @@ -61,8 +74,38 @@ const fsp = require('fs-promise'),
const fd = fsp.openSync(fb, 'r');
// fread() supports no sync'd version, so read in all 8 x 8 x 2 bytes in one shot
const buf = fsp.readFileSync(fd);
const n = buf.readUInt16BE(y * 8 + x);
return rgb(n);
fsp.closeSync(fd);
const n = buf.readUInt16LE(pos(x, y));
return unpack(n);
},

setPixel = (fb, x, y, rgb) => {
if (x < 0 || x > 7) throw new Error(`x=${x} violates 0 <= x <= 7`);
if (y < 0 || y > 7) throw new Error(`y=${y} violates 0 <= y <= 7`);
rgb.map(col => {
if (col < 0 || col > 255) throw new Error(`RGB color ${rgb} violates` +
` [0, 0, 0] < RGB < [255, 255, 255]`);
return col;
});
// TODO support rotation
let fd = fsp.openSync(fb, 'w'),
buf = new Buffer(2),
n = pack(rgb);
buf.writeUInt16LE(n);
fsp.writeSync(fd,
buf, 0, buf.length,
pos(x, y),
// Wait for write to return
(error, written, _) => console.log(`Wrote ${written} bytes`));
fsp.closeSync(fd);
},

clear = fb => {
for (let y = 8; --y >= 0; ) {
for (let x = 8; --x >= 0; ) {
setPixel(fb, x, y, [0, 0, 0]);
}
}
},

rc = fb.then(a => {
Expand All @@ -77,8 +120,22 @@ const fsp = require('fs-promise'),
}
}),

random = (low, high) => Math.floor(Math.random() * (high - low) + low),

rrc = rc.then(fb => {
console.log(`Pixel (0,0) = ${getPixel(fb, 0, 0)}`);
for (let n = 1; --n >= 0; ) {
for (let y = 8; --y >= 0; ) {
for (let x = 8; --x >= 0; ) {
// setPixel(fb, x, y, [random(0, 255), random(0, 255), random(0, 255)]);
// setPixel(fb, x, y, [8 * x, 8 * y, 24]);
let v = (1 + y) * 32 * 256 + (1 + x) * 32;
console.log(v);
setPixel(fb, x, y, unpack(v));
}
}
}
console.log(`Pixel (0,0) = ${getPixel(fb, 0, 0)}`);
});

// EOF

0 comments on commit 3f5b209

Please sign in to comment.