-
Notifications
You must be signed in to change notification settings - Fork 0
/
apc.py
238 lines (203 loc) · 8.65 KB
/
apc.py
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# launchpy, a Python binding and plugins for the Akai APC mini launchpad
# Copyright (C) 2022 RenWal
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from __future__ import annotations
from enum import IntEnum, IntFlag
from typing import Iterable, Tuple, Union
from threading import Lock
from mido import Message
from mido.ports import IOPort
# these are the the numerical values expected by the APC,
# do not modify
class ButtonState(IntEnum):
OFF = 0
# for round buttons that have just one color
ON = 1
BLINK = 2
# for 3-color button matrix
GREEN = 1
GREEN_BLINK = 2
RED = 3
RED_BLINK = 4
YELLOW = 5
YELLOW_BLINK = 6
def toggle(self, color: ButtonState) -> ButtonState:
if self == self.OFF:
return color
return self.OFF
def blink(self, should_blink: bool) -> ButtonState:
if self == self.OFF:
return self.OFF
if self.value & 1 and should_blink:
return ButtonState(self.value+1)
if not (self.value & 1) and not should_blink:
return ButtonState(self.value-1)
return ButtonState(self)
@property
def blinking(self):
return not (self.value & 1) and not self == self.OFF
class ButtonArea(IntFlag):
MATRIX = 0b0001
HORIZONTAL = 0b0010
VERTICAL = 0b0100
SHIFT_BUTTON = 0b1000
@classmethod
def split_flags(cls, areas):
return [area for area in cls if area & areas]
class ButtonID:
def __init__(self, area: ButtonArea, ordinal: Union[int, Tuple[int, int]]):
self.area = area
if isinstance(ordinal, tuple):
assert self.area == ButtonArea.MATRIX, "Coordinate notation only allowed for matrix buttons"
# matrix coords (column, row) to matrix index
ordinal = ordinal[1]*8 + ordinal[0]
self.ordinal = ordinal
def __eq__(self, o: object) -> bool:
if not isinstance(o, self.__class__):
return False
return self.area == o.area and self.ordinal == o.ordinal
def __hash__(self) -> int:
return hash((self.area, self.ordinal))
def __repr__(self) -> str:
if self.area == ButtonArea.MATRIX:
col, row = self.matrix_coords
return f"{self.area.name}[{col},{row}]"
return f"{self.area.name}[{self.ordinal}]"
@property
def matrix_coords(self):
if self.area != ButtonArea.MATRIX:
raise ValueError("Not a matrix button")
return divmod(self.ordinal, 8)
@classmethod
def from_idx(cls, idx: int):
if idx > APCMini.SHIFT_OFFSET:
return None
if idx == APCMini.SHIFT_OFFSET:
return cls(ButtonArea.SHIFT_BUTTON, 0)
if idx >= APCMini.VERTICAL_OFFSET:
return cls(ButtonArea.VERTICAL, idx - APCMini.VERTICAL_OFFSET)
if idx >= APCMini.HORIZONTAL_OFFSET:
return cls(ButtonArea.HORIZONTAL, idx - APCMini.HORIZONTAL_OFFSET)
if idx >= APCMini.MATRIX_OFFSET:
return cls(ButtonArea.MATRIX, idx - APCMini.MATRIX_OFFSET)
raise ValueError("Index invalid")
def to_idx(self) -> int:
if self.area == ButtonArea.SHIFT_BUTTON:
if self.ordinal != 0:
raise ValueError("Ordinal out of range")
return self.ordinal + APCMini.SHIFT_OFFSET
if self.area == ButtonArea.VERTICAL:
if self.ordinal not in range(APCMini.N_VERTICAL):
raise ValueError("Ordinal out of range")
return self.ordinal + APCMini.VERTICAL_OFFSET
if self.area == ButtonArea.HORIZONTAL:
if self.ordinal not in range(APCMini.N_HORIZONTAL):
raise ValueError("Ordinal out of range")
return self.ordinal + APCMini.HORIZONTAL_OFFSET
if self.area == ButtonArea.MATRIX:
if self.ordinal not in range(APCMini.N_MATRIX):
raise ValueError("Ordinal out of range")
return self.ordinal + APCMini.MATRIX_OFFSET
raise ValueError("Area invalid")
class APCMini:
FADER_OFFSET = 48
N_FADERS = 9
MATRIX_OFFSET = 0
DIM_MATRIX = 8
N_MATRIX = DIM_MATRIX**2
HORIZONTAL_OFFSET = 64
N_HORIZONTAL = 8
VERTICAL_OFFSET = 82
N_VERTICAL = 8
SHIFT_OFFSET = 98
button_matrix_indices = list(range(MATRIX_OFFSET, MATRIX_OFFSET+N_MATRIX))
horizontal_buttons_indices = list(range(HORIZONTAL_OFFSET, HORIZONTAL_OFFSET+N_HORIZONTAL))
vertical_buttons_indices = list(range(VERTICAL_OFFSET, VERTICAL_OFFSET+N_VERTICAL))
shift_button = [SHIFT_OFFSET]
area_button_indices = {
ButtonArea.MATRIX: button_matrix_indices,
ButtonArea.HORIZONTAL: horizontal_buttons_indices,
ButtonArea.VERTICAL: vertical_buttons_indices,
ButtonArea.SHIFT_BUTTON: shift_button
}
def __init__(self, ioport: IOPort):
self._ioport = ioport
self.light_state = {x:ButtonState.OFF for x in self.all_button_indices}
self.faders = [None] * self.N_FADERS
self.cb_button_pressed = None
self.cb_button_released = None
self.cb_fader_value = None
self.send_lock = Lock()
@property
def all_button_indices(self, only_with_light: bool = False) -> Iterable[int]:
yield from self.button_matrix_indices
yield from self.horizontal_buttons_indices
yield from self.vertical_buttons_indices
if not only_with_light:
yield from self.shift_button
def reset(self, force: bool = True) -> None:
for b in self.all_button_indices:
self.set_button(b, ButtonState.OFF, force=force)
def resync(self) -> None:
# use this when the hardware was reset (this can happen when a
# system goes to standby and the USB ports are configured to
# power down during sleep) to bring the LEDs back in sync with
# what the software believes them to be showing
self.set_all_buttons(self.light_state.items(), force=True)
def set_button(self, button: Union[int, ButtonID], state: ButtonState, force: bool = False) -> None:
# there seems to be some limitation, be it in mido/rtmidi or in
# the APC mini itself, that drops MIDI messages coming at a very
# high rate
if isinstance(button, ButtonID):
button = button.to_idx()
if force or self.light_state[button] != state:
self._send(Message('note_on', note=button, velocity=state))
self.light_state[button] = state
def get_button(self, button: Union[int, ButtonID]) -> ButtonState:
if isinstance(button, ButtonID):
button = button.to_idx()
return self.light_state[button]
def enable_events(self) -> None:
self._ioport.input.callback = self._event_callback
def disable_events(self) -> None:
self._ioport.input.callback = None
@classmethod
def id_to_fader(cls, fader_id: int) -> int:
return fader_id - cls.FADER_OFFSET
def _send(self, msg: Message):
with self.send_lock:
self._ioport.send(msg)
def _event_callback(self, msg):
if msg.type == "note_on":
if callable(self.cb_button_pressed):
self.cb_button_pressed(ButtonID.from_idx(msg.note))
elif msg.type == "note_off":
if callable(self.cb_button_released):
self.cb_button_released(ButtonID.from_idx(msg.note))
elif msg.type == "control_change":
fader_id = self.id_to_fader(msg.control)
float_val = msg.value/127
self.faders[fader_id] = float_val
if callable(self.cb_fader_value):
self.cb_fader_value(fader_id, float_val)
else:
assert 0
def get_area_light_state(self, area: ButtonArea) -> dict[int, ButtonState]:
return { b:self.get_button(b) for b in self.get_area_buttons(area) }
@classmethod
def get_area_buttons(cls, area: ButtonArea) -> list[int]:
return cls.area_button_indices[area]
def set_all_buttons(self, btn_map: Iterable, force: bool = False):
for b,s in btn_map:
self.set_button(b, s, force)