-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
93 lines (82 loc) · 2.65 KB
/
index.js
File metadata and controls
93 lines (82 loc) · 2.65 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
const net = require("net");
const EventEmitter = require("events");
const TurnOnPacket = Buffer.from([0x71, 0x23, 0x0f, 0xa3]);
const TurnOffPacket = Buffer.from([0x71, 0x24, 0x0f, 0xa4]);
const PingPacket = Buffer.from([0x81, 0x8a, 0x8b, 0x96]);
class RGB {
constructor(red = 0, green = 0, blue = 0) {
this.red = Math.min(255, Math.max(0, red));
this.green = Math.min(255, Math.max(0, green));
this.blue = Math.min(255, Math.max(0, blue));
}
}
// noinspection JSUnusedGlobalSymbols
module.exports.LEDStrip = class LEDStrip extends EventEmitter {
#client = null;
#connected = false;
#interval = null;
constructor(address, port = 5577, pingInterval = 25000){
super();
this.#client = new net.Socket();
this.#client.connect(port, address, () => {
this.#connected = true;
this.#interval = setInterval(() => {
if(this.#connected) {
this.#client.write(PingPacket)
}
}, pingInterval);
this.emit('connect');
})
this.#client.on('close', () => {
this.#connected = false;
clearInterval(this.#interval);
this.emit('close');
})
this.#client.on('error', (error) => {
console.error('Error:', error);
this.#connected = false;
clearInterval(this.#interval);
this.#client.destroy();
this.emit('error', error);
})
}
close() {
if (this.#connected && this.#client) {
this.#client.end();
}
if(this.#interval) {
clearInterval(this.#interval);
}
this.#connected = false;
if(this.#client && !this.#client.destroy) {
this.#client.destroy();
}
}
turnOn() {
if (this.#connected) {
this.#client.write(TurnOnPacket);
} else {
throw new Error("Not connected to LED strip");
}
}
turnOff() {
if (this.#connected) {
this.#client.write(TurnOffPacket);
} else {
throw new Error("Not connected to LED strip");
}
}
setColor(RGBInput) {
if (this.#connected) {
if(RGBInput instanceof RGB) {
const colorPacket = Buffer.from([0x31, RGBInput.red, RGBInput.green, RGBInput.blue, 0x00, 0x00, 0x0f, 0x3f]);
this.#client.write(colorPacket);
} else {
throw new Error("RGB must be an instance of RGB class");
}
} else {
throw new Error("Not connected to LED strip");
}
}
}
module.exports.RGB = RGB