-
Notifications
You must be signed in to change notification settings - Fork 2
/
controller.js
87 lines (77 loc) · 2.11 KB
/
controller.js
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
const COLOR_CODES = {
OFF: 12,
RED: 15,
AMBER: 63,
YELLOW: 62,
GREEN: 60
};
const mappings = require('./mappings');
const midi = require('web-midi');
let midiController = null;
const setController = (err, names) => {
console.log('all controllers', names);
if (!names || names.length === 0 || err) return;
const filteredControllers = names.filter((controller) => {
return controller.toLowerCase().match('launchpad');
});
console.log('allowed controllers', filteredControllers);
midiController = global.midiController = midi(filteredControllers[0]);
observeController();
};
const observeController = () => {
midiController.on('data', touchClip);
};
const touchClip = (data) => {
const key = data[1];
const down = data[2] > 0;
const clip = mappings[key];
if (down && clip) {
clip.touch();
setKeyColor(key, clipToKeyColor(clip));
}
};
const clipToKeyColor = (clip) => {
if (clip.isIdle()) {
return COLOR_CODES.OFF;
} else if (clip.isScheduled()) {
return COLOR_CODES.YELLOW;
} else if (clip.isPlaying()) {
return COLOR_CODES.GREEN;
} else if (clip.isStopped()) {
return COLOR_CODES.RED;
}
};
const mappingKeys = Object.keys(mappings);
const update = (tick, beat) => {
// don't update if no midi controller present
if (!midiController) { return; }
updateProgress(tick, beat);
mappingKeys.forEach((key) => {
const clip = mappings[key];
const color = clipToKeyColor(clip);
setKeyColor(key, color);
});
};
const setKeyColor = (key, color) => {
midiController.write([144, key, color]);
};
const updateProgress = (tick, beat) => {
const priorTicks = (beat - 1) * 96;
const currentTicks = tick;
const tickProgress = currentTicks + priorTicks;
const totalTicks = 4 * 96;
const ratio = tickProgress / totalTicks;
const position = Math.floor(ratio * 8);
for (let i = 1; i <= 8; i++) {
setKeyColor((i * 16) - 8, i-1 === position ? COLOR_CODES.AMBER : COLOR_CODES.OFF);
}
};
module.exports = {
init () {
midi.getPortNames(setController);
midi.watchPortNames(setController);
},
update (tick, beat) {
update(tick, beat);
}
};