-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathwled-http.js
More file actions
114 lines (100 loc) · 3.21 KB
/
wled-http.js
File metadata and controls
114 lines (100 loc) · 3.21 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
const debug = require('debug')('kcapp-colors:wled-http');
const { WLEDClient } = require('wled-client');
const SEGMENTS = [ 0 ];
const EFFECTS = {
SOLID: 0,
BLINK: 1,
TWO_DOTS: 50,
DANCING_SHADOW: 112,
PRIDE2015: 63,
LOADING: 47,
HEARTBEAT: 100,
BREATH: 2,
BPM: 68,
LIGHTHOUSE: 41, // 240 effect, 220 fade
};
const PALLETE = {
RAINBOW: 11
};
function hexToRgb(hex) {
const h = hex.replace('#', '');
return [
parseInt(h.substring(0, 2), 16),
parseInt(h.substring(2, 4), 16),
parseInt(h.substring(4, 6), 16)
];
}
module.exports = (wledUrl) => {
const host = wledUrl.replace(/^https?:\/\//, '');
debug(`Connecting to WLED at ${host}`);
const client = new WLEDClient({ host, secure: false, websocket: false, immediate: false });
let connected = false;
let pendingFn = null;
client.refreshContext().then(() => {
connected = true;
debug(`Connected to WLED at ${host}`);
if (pendingFn) {
debug("Flushing pending command");
const fn = pendingFn;
pendingFn = null;
send(fn);
}
}).catch((err) => {
debug(`Failed to connect to WLED at ${host}: ${err.message}`);
});
async function send(fn) {
if (!connected) {
debug("Not connected to WLED, queuing command");
pendingFn = fn;
return;
}
try {
await fn();
} catch (err) {
debug(`Error communicating with WLED: ${err.message}`);
}
}
return {
EFFECTS,
PALLETE,
setColor: (color) => {
debug(`Setting lights to ${color}`);
const rgb = hexToRgb(color);
return send(async () => {
for (const id of SEGMENTS) {
await client.updateSegment(id, { on: true, effectId: EFFECTS.SOLID, colors: [rgb] });
}
await client.turnOn();
});
},
turnOff: () => {
debug("Disabled lights");
return send(() => client.turnOff());
},
blink: function(color, time, callback) {
this.effect(EFFECTS.BLINK, color, null, 225, 120, time, callback);
},
effect: function(effect, color, pallete, sx = 100, ix = 100, time, callback) {
const effectName = Object.keys(EFFECTS).find(k => EFFECTS[k] === effect) || effect;
debug(`Setting effect ${effectName}`);
const rgb = color ? hexToRgb(color) : null;
send(async () => {
for (const id of SEGMENTS) {
const seg = { effectId: effect, effectSpeed: sx, effectIntensity: ix };
if (rgb) seg.colors = [rgb];
if (pallete) seg.paletteId = pallete;
await client.updateSegment(id, seg);
}
await client.turnOn();
});
if (time) {
setTimeout(() => {
debug("Stopping effect...");
send(() => client.turnOff()).then(() => {
if (callback) callback();
});
}, time);
}
}
};
};