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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
* Simple Open Pixel Control client for Node.js
*
* 2013 Micah Elizabeth Scott
* This file is released into the public domain.
*/
var net = require('net');
var OPC = function(host, port)
{
this.host = host;
this.port = port;
this.pixelBuffer = null;
};
OPC.prototype._reconnect = function()
{
var _this = this;
this.socket = new net.Socket()
this.connected = false;
this.socket.onclose = function() {
console.log("Connection closed");
_this.socket = null;
_this.connected = false;
}
this.socket.connect(this.port, this.host, function() {
console.log("Connected to " + _this.socket.remoteAddress);
_this.connected = true;
_this.socket.setNoDelay();
});
}
OPC.prototype.writePixels = function()
{
if (!this.socket) {
this._reconnect();
}
if (!this.connected) {
return;
}
this.socket.write(this.pixelBuffer);
}
OPC.prototype.setPixelCount = function(num)
{
var length = 4 + num*3;
if (this.pixelBuffer == null || this.pixelBuffer.length != length) {
this.pixelBuffer = new Buffer(length);
}
// Initialize OPC header
this.pixelBuffer.writeUInt8(0, 0); // Channel
this.pixelBuffer.writeUInt8(0, 1); // Command
this.pixelBuffer.writeUInt16BE(num * 3, 2); // Length
}
OPC.prototype.setPixel = function(num, r, g, b)
{
var offset = 4 + num*3;
if (this.pixelBuffer == null || offset + 3 > this.pixelBuffer.length) {
this.setPixelCount(num + 1);
}
this.pixelBuffer.writeUInt8(Math.max(0, Math.min(255, r | 0)), offset);
this.pixelBuffer.writeUInt8(Math.max(0, Math.min(255, g | 0)), offset + 1);
this.pixelBuffer.writeUInt8(Math.max(0, Math.min(255, b | 0)), offset + 2);
}
module.exports = OPC;