forked from phasewalker18/ReaControl24
-
Notifications
You must be signed in to change notification settings - Fork 6
/
control24osc.py
1618 lines (1440 loc) · 56 KB
/
control24osc.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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
"""Control24 to Reaper.OSC client. Communicate between the daemon
process and an OSC Client/Listener pair, tuned for Reaper DAW.
Other, similar clients can be written to communicate with other
protocols such as MIDI HUI, Mackie etc.
"""
import binascii
import signal
import sys
import threading
import time
from ctypes import c_ubyte
from multiprocessing.connection import Client
from optparse import OptionError
import OSC
from control24common import (DEFAULTS, FADER_RANGE, NetworkHelper,
opts_common, start_logging, tick)
from control24map import MAPPING_TREE
'''
This file is part of ReaControl24. Control Surface Middleware.
Copyright (C) 2018 PhaseWalker
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, either version 3 of the License, or
(at your option) any later version.
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/>.
'''
# Timing values in seconds
TIMING_MAIN_LOOP = 10 # 0
TIMING_SERVER_POLL = 2
TIMING_MP_POLL = 1
TIMING_WAIT_OSC_LISTENER = 4
TIMING_OSC_LISTENER_RESTART = 1
TIMING_OSC_CLIENT_RESTART = 1
TIMING_OSC_CLIENT_LOOP = 4
TIMING_SCRIBBLESTRIP_RESTORE = 1
TIMING_FADER_ECHO = 0.1
SESSION = None
# Globals
LOG = None
# Control24 functions
# Split command list on repeats of the same starting byte or any instance of the F7 byte
# Housekeeping functions
def signal_handler(sig, stackframe):
"""Exit the daemon if a signal is received"""
signals_dict = dict((getattr(signal, n), n)
for n in dir(signal) if n.startswith('SIG') and '_' not in n)
LOG.info("control24osc shutting down as %s received.", signals_dict[sig])
if not SESSION is None:
SESSION.close()
sys.exit(0)
# Helper classes to apply standard functionality to C24 classes
class ModeManager(object):
"""Mode managers encapsulate stateful mode switching and toggling
functionality. Instantiate one into another class to provide
that functionality"""
def __init__(self, modesdict):
"""Build a mode manager from a dict containing the possible modes
each with a value of a child dict containing any required data items.
If the data contains a key 'default' then that will set the initial mode
otherwise one will be chosen arbitrarily
"""
# Only accept a dict as the constructor parameter
if not isinstance(modesdict, dict):
raise ValueError(
"A dict of modes, with subdict of data for each with address was expected."
)
self.modes = dict(modesdict)
self.modeslist = list(modesdict.keys())
self.numberofmodes = len(self.modeslist)
# Iterate to find the default and also
# build / init anything needed along the way:
# - Create an OSC message for any address
self.mode = None
first = None
for key, value in self.modes.iteritems():
if first is None:
first = key
# Construct an OSC message for each address
if value.has_key('address'):
value['msg'] = OSC.OSCMessage(value['address'])
if value.get('default'):
self.mode = key
if self.mode is None:
self.mode = first
def set_mode(self, mode):
"""directly set the mode to the key requested"""
if self.is_valid_mode(mode):
self.mode = mode
else:
self.modes[mode] = {'Address': mode}
raise IndexError("That mode does not exist.")
def is_valid_mode(self, mode):
"""Boolean test to ensure mode is currently in the
list of valid modes"""
return self.modes.has_key(mode)
def toggle_mode(self):
"""set the mode to the next one in order of the original
dict passed"""
thiskeyindex = self.modeslist.index(self.mode)
if thiskeyindex < self.numberofmodes - 1:
self.mode = self.modeslist[thiskeyindex + 1]
else:
self.mode = self.modeslist[0]
def get_data(self):
"""return the whole data dict for the current mode"""
return self.modes.get(self.mode)
def get(self, key):
""" pass through method to current mode data dict get"""
return self.modes.get(self.mode).get(key)
def get_msg(self):
"""return only the OSC message for the current mode"""
currmode = self.get_data()
msg = currmode.get('msg')
if msg:
msg.clearData()
return msg
else:
return None
# Classes representing Control24
class C24base(object):
"""base class to make available standard functions"""
@staticmethod
def initbytes(bytelist):
"""load the command byte array with
a list of initial values"""
cmdlength = len(bytelist)
retbytes = (c_ubyte * cmdlength)()
for ind, byt in enumerate(bytelist):
retbytes[ind] = byt
return retbytes
@staticmethod
def parsedcmd_simplebutton(parsedcmd):
"""from a parsedcmd, extract the last address and value"""
#TODO investigate if a parsed command class is the way to go instead
return parsedcmd.get('addresses')[-1], parsedcmd.get('Value')
@staticmethod
def tenbits(num):
"""Return 7 bits in one byte and 3 in the next for an integer provided"""
num = num & 0x3FF
return (num >> 3, (num & 7) << 4)
@staticmethod
def calc_faderscale():
"""Return a dict that converts tenbit 7 bit pair into gain factor 0-1"""
fader_range = 2**10
fader_step = 1 / float(fader_range)
return {C24base.tenbits(num): num * fader_step for num in range(0, fader_range)}
@staticmethod
def walk(node, path, byts, cbyt, tbyt, outp):
"""Walk the mapping tree picking off the LED
buttons, and inverting the sequence.
Basically because too lazy to hand write a second
map and keep them in step"""
mybyts = list(byts)
for key, item in node.items():
addr = item.get('Address', '')
kids = item.get('Children')
kbyt = item.get('ChildByte')
if tbyt is None:
tbyt = item.get('TrackByte')
led = item.get('LED')
tog = item.get('Toggle')
if not kids is None:
kidbyts = list(mybyts)
kidbyts[cbyt] = key
C24base.walk(kids, path + '/' + addr, kidbyts, kbyt, tbyt, outp)
else:
if addr != '' and led:
leafbyts = list(mybyts)
leafbyts[cbyt] = key
opr = {
'cmdbytes': leafbyts
}
if tog:
opr['Toggle'] = tog
if not tbyt is None:
opr['TrackByte'] = tbyt
outp[path + '/' + addr] = opr
class C24nav(C24base):
"""Class to manage the desk navigation section
and cursor keys with 3 modes going to different
OSC addresses"""
#TODO look up the addresses instead of double coding them here
#probably from the existing MAPPING_OSC
navmodes = {
'Nav': {
'address': '/button/command/Window+ZoomPresets+Navigation/Nav',
'osc_address': '/scroll/',
'default': True
},
'Zoom': {
'address': '/button/command/Window+ZoomPresets+Navigation/Zoom',
'osc_address': '/zoom/'
},
'SelAdj': {
'address': '/button/command/Window+ZoomPresets+Navigation/SelAdj',
'osc_address': '/fxcursor/'
}
}
def __init__(self, desk):
self.desk = desk
# Global / full desk level modes and modifiers
self.modemgr = ModeManager(self.navmodes)
#TODO look how we can deal with arrival of a desk
# and the need to initialise things like the NAV
# button controlled by this class
def d_c(self, parsedcmd):
"""Respond to desk buttons mapped to this class"""
button, val = self.parsedcmd_simplebutton(parsedcmd)
if self.modemgr.is_valid_mode(button):
if val == 1:
self.modemgr.set_mode(button)
self.update()
else: #remainder is the cursors mapped to class
addr = self.modemgr.get('osc_address') + button
msg = OSC.OSCMessage(addr)
self.desk.osc_client_send(msg, val)
def update(self):
"""Update button LEDs"""
for key, val in self.modemgr.modes.iteritems():
addr = val.get('address')
butval = int(key == self.modemgr.mode)
self.desk.c24buttonled.set_btn(addr, butval)
class C24modifiers(C24base):
"""Class to hold current state of press and release modifier
keys"""
def __init__(self, desk):
self.desk = desk
self.shift = False
self.option = False
self.control = False
self.command = False
def d_c(self, parsedcmd):
"""Respond to whichever button is mapped to the
class and set the attribute state accordingly"""
button, val = self.parsedcmd_simplebutton(parsedcmd)
button = button.lower()
if hasattr(self, button):
setattr(self, button, bool(val))
class C24desk(C24base):
"""Class to represent the desk, state and
instances to help conversions and behaviour"""
channels = 24
busvus = 1
deskmodes = {
'Values': {
'address': '/track/c24scribstrip/volume',
},
'Group': {
'toggle': True
},
'Names': {
'address': '/track/c24scribstrip/name',
'default': True
},
'Info': {
'address': '/track/c24scribstrip/pan'
}
}
def __init__(self, osc_client_send, c24_client_send):
# DONE original mode management to be deprecated
# phunkyg 29/09/2-18
# self.mode = DEFAULTS.get('scribble')
self.modemgr = ModeManager(self.deskmodes)
# passthrough methods
self.osc_client_send = osc_client_send
self.c24_client_send = c24_client_send
# Set up the child track objects
self.c24tracks = [C24track(self, track_number)
for track_number in range(0, 32)]
self.c24clock = C24clock(self)
self.c24buttonled = C24buttonled(self, None)
self.c24nav = C24nav(self)
self.c24modifiers = C24modifiers(self)
def set_mode(self, mode):
"""set the global desk mode"""
LOG.debug('Desk mode set: %s', mode)
self.modemgr.set_mode(mode)
for track in self.c24tracks:
track.modemgr.set_mode(mode)
if hasattr(track, 'c24scribstrip'):
track.c24scribstrip.restore_desk_display()
def get_track(self, track):
"""Safely access both the main tracks and any virtual
ones in the address space between 24 and 31"""
if track is None:
return None
try:
return self.c24tracks[track]
except IndexError:
LOG.warn("No track exists with index %d", track)
return None
def long_scribble(self, longtext96chars):
"""write a long message using ALL the scribble strips
as a long alphanumeric display"""
for track_number, track in enumerate(self.c24tracks):
if hasattr(track, 'c24scribstrip'):
psn = track_number * 4
piece = longtext96chars[psn:psn + 4]
track.c24scribstrip.c_d(['c24scribstrip', 'long'], [piece])
class C24track(C24base):
"""Track (channel strip) object to contain
one each of the bits found in each of the 24 main tracks"""
def __init__(self, desk, track_number):
self.desk = desk
self.track_number = track_number
self.modemgr = ModeManager(self.desk.modemgr.modes)
self.osctrack_number = track_number + 1
if self.track_number < self.desk.channels:
self.c24fader = C24fader(self)
self.c24vpot = C24vpot(self)
self.c24vumeter = C24vumeter(self)
self.c24buttonled = C24buttonled(self.desk, self)
self.c24automode = C24automode(self.desk, self)
# Place a VU meter on virtual tracks above 24, these are bus VUs
if self.track_number >= self.desk.channels and self.track_number <= self.desk.channels + self.desk.busvus:
self.c24vumeter = C24vumeter(self)
if self.track_number == 28:
self.c24vpot = C24jpot(self)
#Allow access from both 'virtual' track 28 AND desk object
# as it physically belongs there
self.desk.c24jpot = self.c24vpot
if self.track_number <= self.desk.channels or self.track_number in range(self.desk.channels, 32):
self.c24scribstrip = C24scribstrip(self)
class C24clock(C24base):
"""Class to hold and convert clock display value representations"""
# 8 segments
# Displays seems to all be 0xf0, 0x13, 0x01
# 0xf0, 0x13, 0x01 = Displays
# 0x30, 0x19 = Clock display
# 0xFF = DOT byte
# 0x00 x 8 = Display bytes
# 0xf7 = terminator
# seven segment display decoding, seven bits (128 not used)
# 631
# 4268421
# TTBBBT
# RR LLM
sevenseg = {
'0': 0b1111110,
'1': 0b0110000,
'2': 0b1101101,
'3': 0b1111001,
'4': 0b0110011,
'5': 0b1011011,
'6': 0b1011111,
'7': 0b1110000,
'8': 0b1111111,
'9': 0b1111011,
'-': 0b0000001,
' ': 0,
'L': 0x0E,
'h': 0x17,
'o': 0x1D,
'b': 0x1F,
'H': 0x37,
'J': 0x38,
'Y': 0x3B,
'd': 0x3D,
'U': 0x3E,
'R': 0x46,
'F': 0x47,
'C': 0x4E,
'E': 0x4F,
'S': 0b1011011,
'P': 0x67,
'Z': 0b1101101,
'A': 0x77
}
clockbytes = [0xf0, 0x13, 0x01, 0x30, 0x19, 0x00, 0x01,
0x46, 0x4f, 0x67, 0x77, 0x4f, 0x46, 0x01, 0xf7]
ledbytes = [0xF0, 0x13, 0x01, 0x20, 0x19, 0x00, 0xF7]
clockmodes = {
'time': {
'address': '/clock/time',
'dots': 0b0010101,
'LED': 0x40,
'formatter': '_fmt_time'
},
'frames': {
'address': ' /clock/frames',
'dots': 0b0101010,
'LED': 0x20,
'formatter': '_fmt_time'
},
'samples': {
'address': ' /clock/samples',
'dots': 0x00,
'LED': 0x10,
'formatter': '_fmt_default'
},
'beat': {
'address': ' /clock/beat',
'dots': 0b0010100,
'LED': 0x08,
'default': True,
'formatter': '_fmt_beat'
}
}
@staticmethod
def _xform_txt(text):
"""transform the input text to seven segment encoding"""
psn = len(text) - 1
opr = 0
while opr < 8 and psn >= 0:
this_chr = C24clock.sevenseg.get(text[psn])
psn -= 1
if not this_chr is None:
yield this_chr
opr += 1
while opr < 8:
yield 0x00
opr += 1
@staticmethod
def _fmt_beat(text):
"""formatter for beat text"""
if text[-5] == '.':
return ''.join([text[:-4], ' ', text[-4:], ' '])
else:
return ''.join([text, ' '])
@staticmethod
def _fmt_time(text):
"""formatter for time text"""
return text[-13:]
@staticmethod
def _fmt_default(text):
return ''.join([text, ' '])
def __init__(self, desk):
self.desk = desk
self.text = {}
self.op_list = None
self.byt_list = None
self.modemgr = ModeManager(self.clockmodes)
self.cmdbytes = self.initbytes(self.clockbytes)
self.ledbytes = self.initbytes(self.ledbytes)
self._set_things()
def __str__(self):
return 'Text:{}, CmdBytes:{}'.format(
self.text,
binascii.hexlify(self.cmdbytes)
)
def _set_things(self):
self.cmdbytes[5] = self.modemgr.get('dots')
self.ledbytes[5] = self.modemgr.get('LED')
self.formatter = getattr(self, self.modemgr.get('formatter'))
def _update(self):
# Apply whichever formatter function is indicated
optext = self.formatter(self.text[self.modemgr.mode])
# For now, display whatever mode we last gotfrom the daw
self.op_list = self._xform_txt(optext)
self.byt_list = list(self.op_list)
self.cmdbytes[6:14] = [byt for byt in self.byt_list]
self.desk.c24_client_send(self.cmdbytes)
def d_c(self, parsedcmd):
"""Toggle the mode"""
if parsedcmd.get('Value') == 1.0:
self.modemgr.toggle_mode()
self._set_things()
self.desk.c24_client_send(self.ledbytes)
self._update()
def c_d(self, addrlist, stuff):
"""Update from DAW text"""
mode = addrlist[2]
self.text[mode] = stuff[0]
# for speed we simply ignore any osc message that isn't
# for the current mode.
if mode == self.modemgr.mode:
self._update()
class C24vumeter(C24base):
"""Class to hold and convert VU meter value representations"""
# 0xf0, 0x13, 0x01 = display
# 0x10 - VUs
# 0-23 Left
# 32-55 Right
# 24-> bus left
# 56-> bus right
# 0x00 MSB
# 0x00 LSB
# 0xf7 terminator
meterscale = [
(0, 0),
(0, 1),
(0, 3),
(0, 7),
(0, 15),
(0, 31),
(0, 63),
(0, 127),
(1, 127),
(3, 127),
(7, 127),
(15, 127),
(31, 127),
(63, 127),
(127, 127)
]
def __init__(self, track):
self.track = track
self.vu_val = {'postfader': [(0, 0), (0, 0)], 'prefader': [
(0, 0), (0, 0)]}
self.mode = 'postfader'
self.cmdbytes = (c_ubyte * 8)()
for ind, byt in enumerate([0xf0, 0x13, 0x01, 0x10, track.track_number, 0x7f, 0x7f, 0xf7]):
self.cmdbytes[ind] = byt
def __str__(self):
return 'vu_val:{}, mode: {}, CmdBytes:{}'.format(
self.vu_val,
self.mode,
binascii.hexlify(self.cmdbytes)
)
def c_d(self, addrlist, stuff):
"""Update from DAW value"""
spkr = int(addrlist[3])
val = stuff[0]
mode = 'postfader'
self.mode = mode
this_val = self.vu_val.get(mode)
if not this_val is None:
new_val = self._xform_vu(val) # take a copy before change
if new_val != this_val[spkr]:
this_val[spkr] = new_val
# For now, display whatever mode we last gotfrom the daw
self.cmdbytes[4] = 32 * spkr + self.track.track_number
self.cmdbytes[5], self.cmdbytes[6] = this_val[0]
self.track.desk.c24_client_send(self.cmdbytes)
@staticmethod
def _xform_vu(val):
return C24vumeter.meterscale[int(val * 15)]
class C24scribstrip(C24base):
"""Class to hold and convert scribblestrip value representations"""
# 0xf0, 0x13, 0x01 = Displays
# 0x40 = Scribble strip
# 0x00 = track/strip
# 0x00 = ?
# 0x00, 0x00, 0x00, 0x00 = 4 'ascii' chars to display
# 0xf7 = terminator
def __init__(self, track):
self.track = track
self.mode = track.modemgr.get_data()
defaulttext = ' {num:02d}'.format(num=self.track.track_number + 1)
self.dtext4ch = defaulttext
self.text = {'/track/number': defaulttext}
self.cmdbytes = (c_ubyte * 12)()
self.last_update = time.time()
self.restore_timer = threading.Timer(
float(TIMING_SCRIBBLESTRIP_RESTORE), self.restore_desk_display)
for ind, byt in enumerate(
[0xf0, 0x13, 0x01, 0x40, self.track.track_number,
0x00, 0x00, 0x00, 0x00, 0x00, 0xf7]):
self.cmdbytes[ind] = byt
def __str__(self):
return 'Channel:{}, Text:{}, CmdBytes:{}'.format(
self.track,
self.text,
binascii.hexlify(self.cmdbytes)
)
def set_current_display(self):
"""send the current display state to the desk"""
self.transform_text()
self.cmdbytes[6:10] = [ord(thischar) for thischar in self.dtext4ch]
LOG.debug('c24scribstrip mode state: %s = %s',
self.mode, self.dtext4ch)
self.track.desk.c24_client_send(self.cmdbytes)
def restore_desk_display(self):
""" To be called in a delayed fashion
to restore channel bar display to desk default"""
#self.mode.set_mode(self.track.desk.mode)
self.mode = self.track.desk.modemgr.get_data().get('address')
self.set_current_display()
def transform_text(self):
"""transform the basic text string into one that
is ready for the 4 character scribble strip"""
dtext = self.text.get(self.mode)
if not dtext is None:
# The desk has neat characters with a dot and small numeral,
# Which is nice because 1 char is saved
# but only 1-9, so 0 (46) is left as a dot
dpp = dtext.find('.')
if dpp == 3:
nco = ord(dtext[dpp + 1])
if nco != 48:
little = chr(nco - 26)
dtext = dtext[:dpp] + little + dtext[dpp + 1:]
self.dtext4ch = '{txt: <4}'.format(txt=dtext[:4])
else:
self.dtext4ch = ' '
def c_d(self, addrlist, stuff):
"""Update from DAW text"""
address = '/'.join(addrlist)
textvalue = stuff[0]
self.text[address] = textvalue
if address == self.mode:
self.set_current_display()
else:
if time.time() - self.last_update > TIMING_SCRIBBLESTRIP_RESTORE:
self.mode = address
self.set_current_display()
if self.restore_timer.isAlive:
self.restore_timer.cancel()
self.restore_timer = threading.Timer(
float(TIMING_SCRIBBLESTRIP_RESTORE), self.restore_desk_display)
self.restore_timer.start()
class C24jpot(C24base):
"""Class for the Control24 Jog wheel"""
#'DirectionByte': 2,1
#'DirectionByteMask': 0x40,
#'ValueByte': 3
def __init__(self, track):
self.track = track
self.cmdbytes = (c_ubyte * 30)()
self.val = 0
self.dir = 0
self.velocity = 0
self.out = 0
self.scrubout = 0
# Make the class modeful
#TODO use the mode manager class
self.mode = None
self.modes = {
'Scrub': {'address': '/scrub', 'default': True},
'Shuttle': {'address' : '/playrate/rotary'}
}
for key, value in self.modes.iteritems():
value['msg'] = OSC.OSCMessage(value['address'])
if value.get('default'):
self.mode = key
def __str__(self):
return 'JOGWHEEL Channel:{}, dir:{} val:{} vel: {} out:{} cmdbytes:{}'.format(
self.track.track_number,
self.dir,
self.val,
self.velocity,
self.out,
binascii.hexlify(self.cmdbytes)
)
def d_c(self, parsedcmd):
"""desk to computer, switch by button or jog input"""
addrs = parsedcmd.get('addresses')
if addrs[1] == "button":
self._update_from_button(parsedcmd, addrs)
else:
self._update_from_move(parsedcmd)
def _update_from_button(self, parsedcmd, addrs):
if parsedcmd.get('Value') == 1:
button = addrs[-1]
if self.modes.has_key(button):
self.mode = button
else:
LOG.warn('C24jpot no mode for button %s', button)
def _update_from_move(self, parsedcmd):
"""Update from desk command byte list"""
cbytes = parsedcmd.get('cmdbytes')
if cbytes:
for ind, byt in enumerate(cbytes):
self.cmdbytes[ind] = ord(byt)
self.val = self.cmdbytes[2]
if self.val > 64:
self.dir = 1
self.scrubout = 1
else:
self.dir = -1
self.scrubout = 0
self.velocity = self.cmdbytes[3]
self.out = 0.5 + (float(self.val - 64) * float(0.05))
#self.out += float(self.val - 64) * 0.00001
currmode = self.modes.get(self.mode)
msg = currmode.get('msg')
msg.clearData()
if self.mode == 'Scrub':
msg.append(self.scrubout)
else:
msg.append(self.out)
LOG.debug('%s', self)
self.track.desk.osc_client_send(msg)
class C24vpot(C24base):
"""Class for the Control24 Virtual Pots"""
#'DirectionByte': 2,
#'DirectionByteMask': 0x40,
#'ValueByte': 3
scale_dot = [
(0x40, 0x00, 0x00), # 1 L
(0x00, 0x40, 0x00), # 2
(0x00, 0x20, 0x00), # 3
(0x00, 0x10, 0x00), # 4
(0x00, 0x08, 0x00), # 5
(0x00, 0x04, 0x00), # 6
(0x00, 0x02, 0x00), # 7
(0x00, 0x01, 0x00), # 8 C
(0x00, 0x00, 0x40), # 9
(0x00, 0x00, 0x20), # 10
(0x00, 0x00, 0x10), # 11
(0x00, 0x00, 0x08), # 12
(0x00, 0x00, 0x04), # 13
(0x00, 0x00, 0x02), # 14
(0x00, 0x00, 0x01), # 15 R
]
scale_fill = [
(0x40, 0x7F, 0x00), # 1 L
(0x00, 0x7F, 0x00), # 2
(0x00, 0x3F, 0x00), # 3
(0x00, 0x1F, 0x00), # 4
(0x00, 0x0F, 0x00), # 5
(0x00, 0x07, 0x00), # 6
(0x00, 0x03, 0x00), # 7
(0x00, 0x01, 0x00), # 8 C
(0x00, 0x01, 0x40), # 9
(0x00, 0x01, 0x60), # 10
(0x00, 0x01, 0x70), # 11
(0x00, 0x01, 0x78), # 12
(0x00, 0x01, 0x7C), # 13
(0x00, 0x01, 0x7E), # 14
(0x00, 0x01, 0x7F), # 15 R
]
coarse = float(0.03125)
fine = float(0.005)
def __init__(self, track):
self.track = track
self.pang = 0
self.panv = 0,
self.pan = float(0.5)
self.cmdbytes_d_c = (c_ubyte * 30)()
self.cmdbytes = (c_ubyte * 8)()
for ind, byt in enumerate(
[0xF0, 0x13, 0x01, 0x00, self.track.track_number & 0x3f,
0x00, 0x00, 0xF7]):
self.cmdbytes[ind] = byt
self.cmdbytes_d_c[ind] = byt
self.osc_address = '/track/c24vpot/{}'.format(
self.track.track_number + 1)
self.osc_message = OSC.OSCMessage(self.osc_address)
def __str__(self):
return 'Channel:{}, Pan:{}, Pang:{}, Panv:{}, b:{} {} CmdBytes:{}'.format(
self.track.track_number,
self.pan,
self.pang,
self.panv,
self.cmdbytes[5],
self.cmdbytes[6],
binascii.hexlify(self.cmdbytes)
)
def d_c(self, parsedcmd):
"""Desk to Computer. Update from desk command byte list"""
cbytes = parsedcmd.get('cmdbytes')
for ind, byt in enumerate(cbytes):
self.cmdbytes_d_c[ind] = ord(byt)
self.adj_pan(self)
self.osc_message.clearData()
self.osc_message.append(self.pan)
self.update_led()
self.track.desk.osc_client_send(self.osc_message)
def c_d(self, addrlist, stuff):
"""Computer to Desk. Update from DAW pan value (0-1)"""
pan = stuff[0]
self.pan = pan
self.update_led()
def update_led(self):
"""Update the LED display aroudn the vpot"""
if self.pan > 0 and self.pan < 1:
self.panv = self.pan - 0.5
self.pang = int(self.panv * 16) + 7
elif self.pan == 0:
self.panv = -0.5
self.pang = 0
elif self.pan == 1:
self.panv = 0.5
self.pang = 15
try:
led = self.led_value(self.pang)
self.cmdbytes[4], self.cmdbytes[5], self.cmdbytes[6] = led
self.cmdbytes[4] = self.cmdbytes[4] | (self.track.track_number & 0x3f)
except IndexError:
LOG.debug('VPOT LED lookup failure: %s', self)
self.track.desk.c24_client_send(self.cmdbytes)
LOG.debug('VPOT LED: %s', self)
@staticmethod
def led_value(pang):
"""Look up the value to send to the pot LEDs"""
return C24vpot.scale_fill[pang]
@staticmethod
def adj_pan(vpot):
"""Increment/decrement the pan factor from command bytes"""
potdir = vpot.cmdbytes_d_c[2] - 64
potvel = vpot.cmdbytes_d_c[3]
if vpot.track.desk.c24modifiers.command:
amt = vpot.fine
else:
amt = vpot.coarse
adj = potdir * amt
vpot.pan += adj
if vpot.pan > 1:
vpot.pan = 1
if vpot.pan < 0:
vpot.pan = 0
LOG.debug('vpot dir:%d vel:%d adj:%1.6f pan:%1.6f',
potdir, potvel, adj, vpot.pan)
return adj
class C24fader(C24base):
"""Class to hold and convert fader value representations"""
faderscale = C24base.calc_faderscale()
def __init__(self, track):
self.track = track
self.gain = None
self.cmdbytes = (c_ubyte * 5)()
for ind, byt in enumerate(
[0xB0, self.track.track_number & 0x1F,
0x00, self.track.track_number + 0x20, 0x00]):
self.cmdbytes[ind] = byt
self.osc_address = '/track/c24fader/{}'.format(
self.track.track_number + 1)
self.osc_message = OSC.OSCMessage(self.osc_address)
self.last_tick = 0.0
self.touch_status = False
def __str__(self):
return 'Channel:{}, Gain:{}, CmdBytes:{}'.format(
self.track.track_number,
self.gain,
binascii.hexlify(self.cmdbytes)
)
def d_c(self, parsedcmd):
"""Desk to Computer. Update from desk command byte list"""
addr = parsedcmd.get('addresses')
if addr[1] == 'track':
self._update_from_fadermove(parsedcmd)
elif addr[1] == 'button':
self._update_from_touch(parsedcmd)
else:
LOG.warn('Unknown command sent to fader class: %s', parsedcmd)
def c_d(self, addrlist, stuff):
"""Computer to Desk. Update from DAW gain factor (0-1)"""
gai = stuff[0]
self.gain = gai
self.cmdbytes[3] = 0x20 + self.track.track_number
self.cmdbytes[2], self.cmdbytes[4] = self.calc_cmdbytes(self)
self.track.desk.c24_client_send(self.cmdbytes)
def _update_from_fadermove(self, parsedcmd):
cbytes = parsedcmd.get('cmdbytes')
t_in = ord(cbytes[1])
if t_in != self.track.track_number:
LOG.error('Track from Command Bytes does not match Track object Index: %s %s',
binascii.hexlify(cbytes), self)
return None
#TODO tidy up here
if len(cbytes) < 2:
LOG.warn('c24fader bad signature %s',
parsedcmd)
return None
if cbytes[3] == '\x00':
LOG.warn('c24fader bad signature %s',
parsedcmd)
return None
self.cmdbytes[2] = ord(cbytes[2])
self.cmdbytes[4] = ord(cbytes[4])
self.gain = self.calc_gain(self)
self.osc_message.clearData()
self.osc_message.append(self.gain)
self.track.desk.osc_client_send(self.osc_message)
if tick() - self.last_tick > TIMING_FADER_ECHO:
self.track.desk.c24_client_send(self.cmdbytes)
self.last_tick = tick()
def _update_from_touch(self, parsedcmd):
val = parsedcmd.get('Value')
valb = bool(val)
if self.touch_status and not valb:
self.track.desk.c24_client_send(self.cmdbytes)
self.touch_status = valb
@staticmethod
def calc_cmdbytes(fdr):
"""Calculate the command bytes from gain factor"""
gain_from_daw = fdr.gain
if gain_from_daw > 1:
gain_from_daw = 1
gain_tenbits = int(gain_from_daw * FADER_RANGE) - 1
if gain_tenbits < 0:
gain_tenbits = 0
tenb = C24base.tenbits(gain_tenbits)
return c_ubyte(tenb[0]), c_ubyte(tenb[1])
@staticmethod
def calc_gain(fdr):
"""Calculate the gain factor from command bytes"""
volume_from_desk = (fdr.cmdbytes[2], fdr.cmdbytes[4])