addressings.py 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668
  1. #!/usr/bin/env python3
  2. # SPDX-FileCopyrightText: 2012-2023 MOD Audio UG
  3. # SPDX-License-Identifier: AGPL-3.0-or-later
  4. import json
  5. import logging
  6. import os
  7. from tornado import gen
  8. from mod import (
  9. get_hardware_descriptor,
  10. get_nearest_valid_scalepoint_value,
  11. normalize_for_hw,
  12. safe_json_load,
  13. TextFileFlusher
  14. )
  15. from mod.control_chain import (
  16. CC_MODE_TOGGLE,
  17. CC_MODE_TRIGGER,
  18. CC_MODE_OPTIONS,
  19. CC_MODE_TAP_TEMPO,
  20. CC_MODE_REAL,
  21. CC_MODE_INTEGER,
  22. CC_MODE_LOGARITHMIC,
  23. CC_MODE_COLOURED,
  24. CC_MODE_MOMENTARY,
  25. CC_MODE_REVERSE,
  26. ControlChainDeviceListener,
  27. )
  28. from mod.settings import PEDALBOARD_INSTANCE_ID
  29. from modtools.tempo import get_divider_options
  30. from modtools.utils import get_plugin_control_inputs
  31. from mod.mod_protocol import (
  32. FLAG_CONTROL_BYPASS,
  33. FLAG_CONTROL_TAP_TEMPO,
  34. FLAG_CONTROL_ENUMERATION,
  35. FLAG_CONTROL_SCALE_POINTS,
  36. FLAG_CONTROL_TRIGGER,
  37. FLAG_CONTROL_TOGGLED,
  38. FLAG_CONTROL_LOGARITHMIC,
  39. FLAG_CONTROL_INTEGER,
  40. FLAG_CONTROL_REVERSE,
  41. FLAG_CONTROL_MOMENTARY,
  42. )
  43. # use pitchbend as midi cc, with an invalid MIDI controller number
  44. MIDI_PITCHBEND_AS_CC = 131
  45. # Special URI for non-addressed controls
  46. kNullAddressURI = "null"
  47. # Special URIs for midi-learn
  48. kMidiLearnURI = "/midi-learn"
  49. kMidiUnmapURI = "/midi-unmap"
  50. kMidiCustomPrefixURI = "/midi-custom_" # to show current one
  51. # URI for BPM sync (for non-addressed control ports)
  52. kBpmURI ="/bpm"
  53. # CV related constants
  54. CV_PREFIX = 'cv_'
  55. CV_OPTION = '/cv'
  56. HW_CV_PREFIX = CV_OPTION + '/graph/' + CV_PREFIX
  57. # definitions from lv2-hmi.h
  58. # LV2_HMI_AddressingCapabilities
  59. LV2_HMI_AddressingCapability_LED = 1 << 0
  60. LV2_HMI_AddressingCapability_Label = 1 << 1
  61. LV2_HMI_AddressingCapability_Value = 1 << 2
  62. LV2_HMI_AddressingCapability_Unit = 1 << 3
  63. LV2_HMI_AddressingCapability_Indicator = 1 << 4
  64. # LV2_HMI_AddressingFlags
  65. LV2_HMI_AddressingFlag_Coloured = 1 << 0
  66. LV2_HMI_AddressingFlag_Momentary = 1 << 1
  67. LV2_HMI_AddressingFlag_Reverse = 1 << 2
  68. LV2_HMI_AddressingFlag_TapTempo = 1 << 3
  69. class Addressings(object):
  70. ADDRESSING_TYPE_NONE = 0
  71. ADDRESSING_TYPE_HMI = 1
  72. ADDRESSING_TYPE_CC = 2
  73. ADDRESSING_TYPE_MIDI = 3
  74. ADDRESSING_TYPE_BPM = 4
  75. ADDRESSING_TYPE_CV = 5
  76. def __init__(self):
  77. self.init()
  78. self._task_addressing = None
  79. self._task_unaddressing = None
  80. self._task_set_value = None
  81. self._task_get_plugin_cv_port_op_mode = None
  82. self._task_get_plugin_data = None
  83. self._task_get_plugin_presets = None
  84. self._task_get_port_value = None
  85. self._task_get_tempo_divider = None
  86. self._task_store_address_data = None
  87. self._task_hw_added = None
  88. self._task_hw_removed = None
  89. self._task_act_added = None
  90. self._task_act_removed = None
  91. self._task_set_available_pages = None
  92. self._task_host_hmi_map = None
  93. self._task_host_hmi_unmap = None
  94. self.cchain = ControlChainDeviceListener(self.cc_hardware_added,
  95. self.cc_hardware_removed,
  96. self.cc_actuator_added)
  97. # First addressings/pedalboard load flag
  98. self.first_load = True
  99. # Flag for load_current being active or aborted
  100. self.last_load_current_aborted = False
  101. self.pending_load_current = False
  102. # Flag and callbacks for Control Chain waiting
  103. self.waiting_for_cc = not self.cchain.initialized
  104. self.waiting_for_cc_cbs = []
  105. # -----------------------------------------------------------------------------------------------------------------
  106. # initialize (clear) all addressings
  107. def init(self):
  108. desc = get_hardware_descriptor()
  109. self.hw_actuators = desc.get('actuators', [])
  110. self.hw_actuators_uris = tuple(a['uri'] for a in self.hw_actuators)
  111. self.has_hmi_subpages = bool(desc.get('hmi_subpages', False))
  112. self.hmi_show_actuator_group_prefix = bool(desc.get('hmi_actuator_group_prefix', True))
  113. self.hmi_show_empty_pages = bool(desc.get('hmi_show_empty_pages', False))
  114. self.addressing_pages = int(desc.get('addressing_pages', 0))
  115. self.current_page = 0
  116. if self.addressing_pages:
  117. self.available_pages = [True if i == 0 else False for i in range(self.addressing_pages)]
  118. else:
  119. self.available_pages = []
  120. # 'hmi_addressings' uses a structure like this:
  121. # "/hmi/knob1": {'addrs': [...], 'idx': 0}
  122. # so per actuator we get:
  123. # - 'addrs': list of addressings
  124. # - 'idx' : currently selected addressing (index)
  125. self.hmi_addressings = dict((uri, {'addrs': [], 'idx': -1}) for uri in self.hw_actuators_uris)
  126. self.cc_addressings = {}
  127. self.cc_metadata = {}
  128. self.midi_addressings = {}
  129. self.virtual_addressings = {kBpmURI: []}
  130. self.cv_addressings = {}
  131. # Store all possible HMI hardcoded values
  132. self.hmi_hw2uri_map = {}
  133. self.hmi_hwsubpages = {}
  134. self.hmi_uri2hw_map = {}
  135. for actuator in self.hw_actuators:
  136. uri = actuator['uri']
  137. hw_id = actuator['id']
  138. self.hmi_hw2uri_map[hw_id] = uri
  139. self.hmi_hwsubpages[hw_id] = 0 if self.has_hmi_subpages else None
  140. self.hmi_uri2hw_map[uri] = hw_id
  141. # clear all addressings, leaving metadata intact
  142. def clear(self):
  143. self.hmi_addressings = dict((key, {'addrs': [], 'idx': -1}) for key in self.hmi_addressings.keys())
  144. self.cc_addressings = dict((key, []) for key in self.cc_addressings.keys())
  145. self.cv_addressings = dict((key, []) for key in self.cv_addressings.keys() if self.is_hw_cv_port(key))
  146. self.virtual_addressings = dict((key, []) for key in self.virtual_addressings.keys())
  147. self.midi_addressings = {}
  148. self.current_page = 0
  149. self.last_load_current_aborted = False
  150. self.pending_load_current = False
  151. if self.has_hmi_subpages:
  152. for hw_id in self.hmi_hwsubpages:
  153. self.hmi_hwsubpages[hw_id] = 0
  154. # -----------------------------------------------------------------------------------------------------------------
  155. def get_actuators(self):
  156. actuators = self.hw_actuators.copy()
  157. for uri in sorted(self.cc_metadata.keys()):
  158. data = self.cc_metadata[uri]
  159. metadata = {
  160. 'uri': uri,
  161. 'name' : data['name'],
  162. 'modes': data['modes'],
  163. 'steps': data['steps'],
  164. 'max_assigns': data['max_assigns'],
  165. 'feedback' : data['feedback'],
  166. 'widgets' : data['widgets'],
  167. }
  168. actuator_group = data.get('actuator_group', None)
  169. if actuator_group is not None:
  170. metadata['actuator_group'] = actuator_group
  171. actuators.append(metadata)
  172. return actuators
  173. # Not used (?)
  174. def get_addressings(self):
  175. addressings = {}
  176. # HMI
  177. for uri, addrs in self.hmi_addressings.items():
  178. addrs2 = []
  179. for addr in addrs['addrs']:
  180. addrs2.append({
  181. 'instance_id': addr['instance_id'],
  182. 'port' : addr['port'],
  183. 'label' : addr['label'],
  184. 'minimum' : addr['minimum'],
  185. 'maximum' : addr['maximum'],
  186. 'steps' : addr['steps'],
  187. })
  188. addressings[uri] = addrs2
  189. # Control Chain
  190. for uri, addrs in self.cc_addressings.items():
  191. addrs2 = []
  192. for addr in addrs:
  193. addrs2.append({
  194. 'instance_id': addr['instance_id'],
  195. 'port' : addr['port'],
  196. 'label' : addr['label'],
  197. 'minimum' : addr['minimum'],
  198. 'maximum' : addr['maximum'],
  199. 'steps' : addr['steps'],
  200. })
  201. addressings[uri] = addrs2
  202. return addressings
  203. def get_available_pages(self):
  204. if not self.hmi_show_empty_pages:
  205. return self.available_pages
  206. pages = self.available_pages.copy()
  207. rpages = self.available_pages.copy()
  208. rpages.reverse()
  209. for i in range(self.addressing_pages - rpages.index(True)):
  210. pages[i] = True
  211. return pages
  212. # -----------------------------------------------------------------------------------------------------------------
  213. # common function used in load() to finish waiting callbacks
  214. def _dont_wait_for_cc(self):
  215. self.waiting_for_cc = False
  216. for cb in self.waiting_for_cc_cbs:
  217. cb()
  218. self.waiting_for_cc_cbs = []
  219. def peek_for_momentary_toggles(self, bundlepath):
  220. datafile = os.path.join(bundlepath, "addressings.json")
  221. if not os.path.exists(datafile):
  222. return {}
  223. ret = {}
  224. data = safe_json_load(datafile, dict)
  225. for actuator_uri, addrs in data.items():
  226. # Special case for CV addressings
  227. if actuator_uri.startswith(CV_OPTION) and not actuator_uri.startswith(HW_CV_PREFIX):
  228. addrs = addrs['addrs']
  229. for addr in addrs:
  230. momentary = addr.get('momentary', None)
  231. if momentary is None or not isinstance(momentary, int):
  232. continue
  233. instance = addr['instance']
  234. portsymbol = addr['port']
  235. # momentary on
  236. if momentary == 1:
  237. target = addr['maximum'] if portsymbol == ":bypass" else addr['minimum']
  238. # momentary off
  239. elif momentary == 2:
  240. target = addr['minimum'] if portsymbol == ":bypass" else addr['maximum']
  241. else:
  242. continue
  243. if not instance in ret:
  244. ret[instance] = {}
  245. ret[instance][portsymbol] = target
  246. return ret
  247. @gen.coroutine
  248. def load(self, bundlepath, instances, skippedPorts, abort_catcher):
  249. # Check if this is the first time we load addressings (ie, first time mod-ui starts)
  250. first_load = self.first_load
  251. self.first_load = False
  252. # reset for load_current before fully loading addressings
  253. self.last_load_current_aborted = False
  254. self.pending_load_current = False
  255. # Check if pedalboard contains addressings first
  256. datafile = os.path.join(bundlepath, "addressings.json")
  257. if not os.path.exists(datafile):
  258. self._dont_wait_for_cc()
  259. return
  260. # Load addressings
  261. data = safe_json_load(datafile, dict)
  262. # Basic setup
  263. cc_initialized = self.cchain.initialized
  264. has_cc_addrs = False
  265. retry_cc_addrs = False
  266. used_actuators = []
  267. hmi_widgets = []
  268. # NOTE: We need to wait for Control Chain to finish initializing.
  269. # Can take some time due to waiting for several device descriptors.
  270. # We load everything that is possible first, then wait for Control Chain at the end if not ready yet.
  271. # Load all addressings possible
  272. for actuator_uri, addrs in data.items():
  273. actuator_type = self.get_actuator_type(actuator_uri)
  274. is_cc = actuator_type == self.ADDRESSING_TYPE_CC
  275. if is_cc:
  276. has_cc_addrs = True
  277. if not cc_initialized:
  278. continue
  279. is_cv = actuator_type == self.ADDRESSING_TYPE_CV
  280. # Continue if current actuator_uri is not part of the actual available actuators (hardware, virtual bpm, cc or cv)
  281. if actuator_uri not in self.hw_actuators_uris and not is_cc and actuator_uri != kBpmURI and not is_cv:
  282. continue
  283. # Add addressed plugin cv port since it's not a hardware but pedalboard setup
  284. # plugin cv ports have the following structure:
  285. # { "/cv/graph/env/out": { "name": "Env Out", "addrs": [...] }} (instead of { "hmi/...": [...] })
  286. # because we need to save the port label even if nothing addressed to it
  287. is_hw_cv = self.is_hw_cv_port(actuator_uri)
  288. if is_cv and not is_hw_cv:
  289. self.cv_addressings[actuator_uri] = { 'name': addrs['name'], 'addrs': [] }
  290. addrs = addrs['addrs']
  291. i = 0
  292. for addr in addrs:
  293. instance = addr['instance'].replace("/graph/","",1)
  294. portsymbol = addr['port']
  295. try:
  296. instance_id, plugin_uri = instances[instance]
  297. except KeyError:
  298. print("ERROR: An instance specified in addressings file is invalid")
  299. i += 1
  300. continue
  301. if len(skippedPorts) > 0 and instance+"/"+portsymbol in skippedPorts:
  302. print("NOTE: An incompatible addressing has been skipped, port:", instance, portsymbol)
  303. i += 1
  304. continue
  305. page = addr.get('page', None)
  306. subpage = addr.get('subpage', None)
  307. if actuator_type == self.ADDRESSING_TYPE_HMI:
  308. # Dealing with HMI addr from a pedalboard without subpages in a device with, or vice-versa
  309. if subpage is None and self.has_hmi_subpages:
  310. subpage = 0
  311. elif subpage is not None and not self.has_hmi_subpages:
  312. subpage = None
  313. # Dealing with HMI addr from a pedalboard not supporting pages on a device supporting them
  314. if self.addressing_pages and page is None:
  315. if i < self.addressing_pages: # automatically assign the i-th assignment to page i
  316. page = i
  317. else: # cannot address more because we've reached the max nb of pages for current actuator
  318. break
  319. coloured = addr.get('coloured', False)
  320. momentary = int(addr.get('momentary', 0))
  321. operational_mode = addr.get('operational_mode', '=')
  322. try:
  323. curvalue = self._task_get_port_value(instance_id, portsymbol)
  324. except KeyError:
  325. continue
  326. group = addr.get('group', None)
  327. addrdata = self.add(instance_id, plugin_uri, portsymbol, actuator_uri,
  328. addr['label'], addr['minimum'], addr['maximum'], addr['steps'], curvalue,
  329. addr.get('tempo'), addr.get('dividers'), page, subpage, group,
  330. coloured, momentary, operational_mode)
  331. if addrdata is not None:
  332. stored_addrdata = addrdata.copy()
  333. if group is not None: # if addressing is grouped, then store address data using group actuator uri
  334. stored_addrdata['actuator_uri'] = group
  335. self._task_store_address_data(instance_id, portsymbol, stored_addrdata)
  336. if actuator_uri not in used_actuators:
  337. used_actuators.append(actuator_uri)
  338. if actuator_type == self.ADDRESSING_TYPE_HMI and not addr.get('tempo'):
  339. hmi_widgets.append(addrdata)
  340. elif is_cc:
  341. # Control Chain is initialized but addressing failed to load (likely due to missing hardware)
  342. # Set this flag so we wait for devices later
  343. retry_cc_addrs = True
  344. i += 1
  345. # Load HMI, Control Chain and CV addressings
  346. for actuator_uri in used_actuators:
  347. if abort_catcher is not None and abort_catcher.get('abort', False):
  348. print("WARNING: Abort triggered during addressings.load actuator requests, caller:", abort_catcher['caller'])
  349. return
  350. actuator_type = self.get_actuator_type(actuator_uri)
  351. if actuator_type == self.ADDRESSING_TYPE_HMI:
  352. try:
  353. yield gen.Task(self.hmi_load_first, actuator_uri)
  354. except Exception as e:
  355. logging.exception(e)
  356. elif actuator_type == self.ADDRESSING_TYPE_CC and cc_initialized:
  357. self.cc_load_all(actuator_uri)
  358. elif actuator_type == self.ADDRESSING_TYPE_CV:
  359. self.cv_load_all(actuator_uri)
  360. # Load HMI Widgets (needs to be done *after* HMI loads its addressings)
  361. if self._task_host_hmi_map:
  362. for addrdata in hmi_widgets:
  363. hw_id = self.hmi_uri2hw_map[addrdata['actuator_uri']]
  364. self.remap_host_hmi(hw_id, addrdata)
  365. # Load MIDI addressings
  366. # NOTE: MIDI addressings are not stored in addressings.json.
  367. # They must be loaded by calling 'add_midi' before this `load` function.
  368. for actuator_uri, addressings in self.midi_addressings.items():
  369. for addressing in addressings:
  370. if abort_catcher is not None and abort_catcher.get('abort', False):
  371. print("WARNING: Abort triggered during addressings.load MIDI requests, caller:", abort_catcher['caller'])
  372. return
  373. # NOTE: label, value, steps and options missing, not needed or used for MIDI
  374. data = {
  375. 'instance_id': addressing['instance_id'],
  376. 'port' : addressing['port'],
  377. 'minimum' : addressing['minimum'],
  378. 'maximum' : addressing['maximum'],
  379. # MIDI specific
  380. 'midichannel': addressing['midichannel'],
  381. 'midicontrol': addressing['midicontrol'],
  382. }
  383. try:
  384. yield gen.Task(self._task_addressing, self.ADDRESSING_TYPE_MIDI, actuator_uri, data)
  385. except Exception as e:
  386. logging.exception(e)
  387. # Send available pages (ie with addressings) to hmi
  388. self.available_pages = []
  389. if self.addressing_pages:
  390. for i in range(self.addressing_pages):
  391. # Build default available_pages list
  392. if i == 0: # For the moment we always boot/load a pedalboard with first page
  393. self.available_pages.append(True) # so it should always be available
  394. else:
  395. self.available_pages.append(False)
  396. # Loop through HMI addressings
  397. def loop_addressings():
  398. for uri, addrs in self.hmi_addressings.items():
  399. for addr in addrs['addrs']:
  400. if addr['page'] == i:
  401. self.available_pages[i] = True
  402. return
  403. loop_addressings()
  404. try:
  405. yield gen.Task(self._task_set_available_pages, self.get_available_pages())
  406. except Exception as e:
  407. logging.exception(e)
  408. # Unset retry flag if at least 1 Control Chain device is connected
  409. if retry_cc_addrs and len(self.cc_metadata) > 0:
  410. retry_cc_addrs = False
  411. # Check if we need to wait for Control Chain
  412. if not first_load or (cc_initialized and not retry_cc_addrs):
  413. self._dont_wait_for_cc()
  414. return
  415. if retry_cc_addrs:
  416. # Wait for any Control Chain devices to appear, with 10s maximum time-out
  417. print("NOTE: Waiting for Control Chain devices to appear")
  418. for i in range(10):
  419. yield gen.sleep(1)
  420. if len(self.cc_metadata) > 0 and self.cchain.initialized:
  421. break
  422. elif not self.cchain.initialized:
  423. # Control Chain was not initialized yet by this point, wait for it
  424. # 'wait_initialized' will time-out in 10s if nothing happens
  425. print("NOTE: Waiting for Control Chain to initialize")
  426. try:
  427. yield gen.Task(self.cchain.wait_initialized)
  428. except Exception as e:
  429. logging.exception(e)
  430. self._dont_wait_for_cc()
  431. # Don't bother continuing if there are no Control Chain addressesings
  432. if not has_cc_addrs:
  433. return
  434. # Don't bother continuing if there are no Control Chain devices available
  435. if len(self.cc_metadata) == 0:
  436. print("WARNING: Pedalboard has Control Chain addressings but no devices are available")
  437. return
  438. # reset used actuators, only load for those that succeed
  439. used_actuators = []
  440. # Re-do the same as we did above
  441. for actuator_uri, addrs in data.items():
  442. if abort_catcher is not None and abort_catcher.get('abort', False):
  443. print("WARNING: Abort triggered during addressings.load CC requests, caller:", abort_catcher['caller'])
  444. return
  445. if self.get_actuator_type(actuator_uri) != self.ADDRESSING_TYPE_CC:
  446. continue
  447. for addr in addrs:
  448. instance = addr['instance'].replace("/graph/","",1)
  449. portsymbol = addr['port']
  450. try:
  451. instance_id, plugin_uri = instances[instance]
  452. except KeyError:
  453. print("ERROR: An instance specified in addressings file is invalid")
  454. continue
  455. if len(skippedPorts) > 0 and instance+"/"+portsymbol in skippedPorts:
  456. print("NOTE: An incompatible addressing has been skipped, port:", instance, portsymbol)
  457. continue
  458. try:
  459. curvalue = self._task_get_port_value(instance_id, portsymbol)
  460. except KeyError:
  461. continue
  462. addrdata = self.add(instance_id, plugin_uri, portsymbol, actuator_uri,
  463. addr['label'], addr['minimum'], addr['maximum'], addr['steps'], curvalue)
  464. if addrdata is not None:
  465. self._task_store_address_data(instance_id, portsymbol, addrdata)
  466. if actuator_uri not in used_actuators:
  467. used_actuators.append(actuator_uri)
  468. for actuator_uri in used_actuators:
  469. self.cc_load_all(actuator_uri)
  470. def save(self, bundlepath, instances):
  471. addressings = {}
  472. # HMI
  473. for uri, addrs in self.hmi_addressings.items():
  474. addrs2 = []
  475. for addr in addrs['addrs']:
  476. instance = instances.get(addr['instance_id'], None)
  477. if instance is None:
  478. continue
  479. addrs2.append({
  480. 'instance': instance,
  481. 'port' : addr['port'],
  482. 'label' : addr['label'],
  483. 'minimum' : addr['minimum'],
  484. 'maximum' : addr['maximum'],
  485. 'steps' : addr['steps'],
  486. 'tempo' : addr.get('tempo'),
  487. 'dividers': addr.get('dividers'),
  488. 'page' : addr.get('page'),
  489. 'subpage' : addr.get('subpage'),
  490. 'group' : addr.get('group'),
  491. 'coloured': addr.get('coloured', False),
  492. 'momentary': int(addr.get('momentary', 0)),
  493. })
  494. addressings[uri] = addrs2
  495. # Control Chain
  496. for uri, addrs in self.cc_addressings.items():
  497. addrs2 = []
  498. for addr in addrs:
  499. instance = instances.get(addr['instance_id'], None)
  500. if instance is None:
  501. continue
  502. addrs2.append({
  503. 'instance': instance,
  504. 'port' : addr['port'],
  505. 'label' : addr['label'],
  506. 'minimum' : addr['minimum'],
  507. 'maximum' : addr['maximum'],
  508. 'steps' : addr['steps'],
  509. 'coloured': addr.get('coloured', False),
  510. 'momentary': int(addr.get('momentary', 0)),
  511. })
  512. addressings[uri] = addrs2
  513. # Virtual actuator (only /bpm for now)
  514. for uri, addrs in self.virtual_addressings.items():
  515. addrs2 = []
  516. for addr in addrs:
  517. instance = instances.get(addr['instance_id'], None)
  518. if instance is None:
  519. continue
  520. addrs2.append({
  521. 'instance': instance,
  522. 'port' : addr['port'],
  523. 'label' : addr['label'],
  524. 'minimum' : addr['minimum'],
  525. 'maximum' : addr['maximum'],
  526. 'steps' : addr['steps'],
  527. 'tempo' : addr.get('tempo'),
  528. 'dividers': addr.get('dividers'),
  529. 'page' : addr.get('page')
  530. })
  531. addressings[uri] = addrs2
  532. # CV
  533. for uri, addrs in self.cv_addressings.items():
  534. if self.is_hw_cv_port(uri):
  535. addrs2 = []
  536. for addr in addrs:
  537. instance = instances.get(addr['instance_id'], None)
  538. if instance is None:
  539. continue
  540. addrs2.append({
  541. 'instance' : instance,
  542. 'port' : addr['port'],
  543. 'label' : addr['label'],
  544. 'minimum' : addr['minimum'],
  545. 'maximum' : addr['maximum'],
  546. 'steps' : addr['steps'],
  547. 'operational_mode': addr['operational_mode'],
  548. })
  549. else: # plugin cv ports, different structure to save name as well
  550. addrs2 = { 'name': addrs['name'], 'addrs': [] }
  551. for addr in addrs['addrs']:
  552. instance = instances.get(addr['instance_id'], None)
  553. if instance is None:
  554. continue
  555. addrs2['addrs'].append({
  556. 'instance' : instance,
  557. 'port' : addr['port'],
  558. 'label' : addr['label'],
  559. 'minimum' : addr['minimum'],
  560. 'maximum' : addr['maximum'],
  561. 'steps' : addr['steps'],
  562. 'operational_mode': addr['operational_mode'],
  563. })
  564. addressings[uri] = addrs2
  565. # Write addressings to disk
  566. with TextFileFlusher(os.path.join(bundlepath, "addressings.json")) as fh:
  567. json.dump(addressings, fh, indent=4)
  568. def registerMappings(self, msg_callback, instances):
  569. # CV plugin ports
  570. for actuator_uri, addrs in self.cv_addressings.items():
  571. # pluginData = self._task_get_plugin_data(instance_id)
  572. if not self.is_hw_cv_port(actuator_uri):
  573. try:
  574. operational_mode = self._task_get_plugin_cv_port_op_mode(actuator_uri)
  575. except KeyError:
  576. pass
  577. else:
  578. msg_callback("add_cv_port %s %s %s" % (actuator_uri, addrs['name'].replace(" ","_"), operational_mode))
  579. # HMI
  580. group_mappings = [] #{} if self.addressing_pages else []
  581. for uri, addrs in self.hmi_addressings.items():
  582. for addr in addrs['addrs']:
  583. addr_uri = uri
  584. dividers = "{0}".format(addr.get('dividers', "null")).replace(" ", "").replace("None", "null")
  585. page = "{0}".format(addr.get('page', "null")).replace("None", "null")
  586. subpage = "{0}".format(addr.get('subpage', "null")).replace("None", "null")
  587. group = "{0}".format(addr.get('group', "null")).replace("None", "null")
  588. send_hw_map = True
  589. if addr.get('group') is not None:
  590. addr_uri = group
  591. group_mapping = {'uri': group, 'page': addr.get('page')}
  592. if group_mapping not in group_mappings:
  593. group_mappings.append({'uri': group, 'page': addr.get('page')})
  594. send_hw_map = False # Register harware group mapping only once
  595. if addr.get('group') is None or send_hw_map:
  596. instance = instances.get(addr['instance_id'], None)
  597. if instance is None:
  598. continue
  599. args = (instance,
  600. addr['port'],
  601. addr_uri,
  602. addr['minimum'],
  603. addr['maximum'],
  604. addr['steps'],
  605. addr['label'].replace(" ","_"),
  606. addr.get('tempo', False),
  607. dividers,
  608. page,
  609. subpage,
  610. group,
  611. int(addr.get('coloured', False)),
  612. int(addr.get('momentary', 0)))
  613. msg_callback("hw_map %s %s %s %f %f %d %s %s %s %s %s %s 1 %d %d" % args)
  614. # Virtual addressings (/bpm)
  615. for uri, addrs in self.virtual_addressings.items():
  616. for addr in addrs:
  617. instance = instances.get(addr['instance_id'], None)
  618. if instance is None:
  619. continue
  620. dividers = "{0}".format(addr.get('dividers', "null")).replace(" ", "").replace("None", "null")
  621. page = "{0}".format(addr.get('page', "null")).replace("None", "null")
  622. args = (instance,
  623. addr['port'],
  624. uri,
  625. addr['minimum'],
  626. addr['maximum'],
  627. addr['steps'],
  628. addr['label'].replace(" ","_"),
  629. addr.get('tempo', False),
  630. dividers,
  631. page)
  632. msg_callback("hw_map %s %s %s %f %f %d %s %s %s %s null null 1 0 0" % args)
  633. # Control Chain
  634. for uri, addrs in self.cc_addressings.items():
  635. feedback = int(self.cc_metadata[uri]['feedback'])
  636. for addr in addrs:
  637. instance = instances.get(addr['instance_id'], None)
  638. if instance is None:
  639. continue
  640. args = (instance,
  641. addr['port'],
  642. uri,
  643. addr['minimum'],
  644. addr['maximum'],
  645. addr['steps'],
  646. addr['label'].replace(" ","_"),
  647. feedback,
  648. int(addr.get('coloured', False)),
  649. int(addr.get('momentary', 0)))
  650. msg_callback("hw_map %s %s %s %f %f %d %s False null null null null %d %d %d" % args)
  651. # MIDI
  652. for uri, addrs in self.midi_addressings.items():
  653. for addr in addrs:
  654. instance = instances.get(addr['instance_id'], None)
  655. if instance is None:
  656. continue
  657. msg_callback("midi_map %s %s %i %i %f %f" % (instance,
  658. addr['port'],
  659. addr['midichannel'],
  660. addr['midicontrol'],
  661. addr['minimum'],
  662. addr['maximum']))
  663. # CV
  664. for uri, addrs in self.cv_addressings.items():
  665. if not self.is_hw_cv_port(uri):
  666. addrs = addrs['addrs']
  667. for addr in addrs:
  668. instance = instances.get(addr['instance_id'], None)
  669. if instance is None:
  670. continue
  671. msg_callback("cv_map %s %s %s %f %f %s %s 0" % (instance,
  672. addr['port'],
  673. uri,
  674. addr['minimum'],
  675. addr['maximum'],
  676. addr['label'].replace(" ","_"),
  677. addr.get('operational_mode')))
  678. # -----------------------------------------------------------------------------------------------------------------
  679. def add(self, instance_id, plugin_uri, portsymbol, actuator_uri, label, minimum, maximum, steps, value,
  680. tempo=False, dividers=None, page=None, subpage=None, group=None, coloured=None, momentary=None,
  681. operational_mode=None):
  682. actuator_type = self.get_actuator_type(actuator_uri)
  683. if actuator_type not in (self.ADDRESSING_TYPE_HMI, self.ADDRESSING_TYPE_CC, self.ADDRESSING_TYPE_BPM, self.ADDRESSING_TYPE_CV):
  684. print("ERROR: Trying to address the wrong way, stop!")
  685. return None
  686. unit = "none"
  687. options = []
  688. pprops = []
  689. if portsymbol == ":presets":
  690. data = self.get_presets_as_options(instance_id)
  691. if data is None:
  692. return None
  693. value, maximum, options, spreset = data
  694. minimum = 0
  695. steps = maximum - 1
  696. elif instance_id == PEDALBOARD_INSTANCE_ID:
  697. if portsymbol == ":bpb":
  698. pprops = ["integer"]
  699. unit = "/4"
  700. elif portsymbol == ":bpm":
  701. pprops = ["integer", "tapTempo"]
  702. unit = "BPM"
  703. elif portsymbol == ":rolling":
  704. pprops = ["toggled"]
  705. else:
  706. print("ERROR: Trying to address wrong pedalboard port:", portsymbol)
  707. return None
  708. elif portsymbol != ":bypass":
  709. for port_info in get_plugin_control_inputs(plugin_uri):
  710. if port_info["symbol"] == portsymbol:
  711. break
  712. else:
  713. print("ERROR: Trying to address non-existing control port '%s'" % (portsymbol))
  714. return None
  715. # useful info about this port
  716. pprops = port_info["properties"]
  717. if "symbol" in port_info["units"].keys():
  718. unit = port_info["units"]["symbol"]
  719. if "enumeration" in pprops and len(port_info["scalePoints"]) > 0:
  720. options = [(sp["value"], sp["label"]) for sp in port_info["scalePoints"]]
  721. # Load tap tempo addressings as tempo divider (1/4)
  722. if not tempo and "tapTempo" in pprops and actuator_uri.startswith("/hmi/footswitch"):
  723. tempo = True
  724. dividers = 4
  725. if tempo:
  726. divider_options = get_divider_options(port_info, 20.0, 280.0) # XXX min and max bpm hardcoded
  727. options_list = [opt['value'] for opt in divider_options]
  728. # Set min and max to min and max value among dividers
  729. minimum = min(options_list)
  730. maximum = max(options_list)
  731. steps = len(options_list) - 1
  732. options = [(o["value"], o["label"]) for o in divider_options]
  733. # TODO do something with spreset
  734. addressing_data = {
  735. 'actuator_uri': actuator_uri,
  736. 'instance_id' : instance_id,
  737. 'port' : portsymbol,
  738. 'label' : label,
  739. 'value' : value,
  740. 'minimum' : minimum,
  741. 'maximum' : maximum,
  742. 'steps' : steps,
  743. 'unit' : unit,
  744. 'options' : options,
  745. 'tempo' : tempo,
  746. 'dividers' : dividers,
  747. 'page' : page,
  748. 'subpage' : subpage,
  749. 'group' : group,
  750. 'coloured' : coloured,
  751. 'momentary' : momentary,
  752. 'operational_mode': operational_mode,
  753. }
  754. if tempo or "enumeration" in pprops and len(port_info["scalePoints"]) > 0:
  755. if not tempo and value not in [o[0] for o in options]:
  756. print("WARNING: current value '%f' for '%s' is not a valid scalepoint" % (value, portsymbol))
  757. addressing_data['value'] = get_nearest_valid_scalepoint_value(value, options)[1]
  758. # -------------------------------------------------------------------------------------------------------------
  759. if actuator_type == self.ADDRESSING_TYPE_HMI:
  760. if portsymbol == ":bypass":
  761. hmitype = FLAG_CONTROL_BYPASS
  762. if momentary:
  763. hmitype |= FLAG_CONTROL_MOMENTARY
  764. if momentary == 2:
  765. hmitype |= FLAG_CONTROL_REVERSE
  766. elif portsymbol == ":presets":
  767. hmitype = FLAG_CONTROL_ENUMERATION|FLAG_CONTROL_SCALE_POINTS|FLAG_CONTROL_INTEGER
  768. else:
  769. if "toggled" in pprops:
  770. hmitype = FLAG_CONTROL_TOGGLED
  771. if momentary:
  772. hmitype |= FLAG_CONTROL_MOMENTARY
  773. if momentary == 2:
  774. hmitype |= FLAG_CONTROL_REVERSE
  775. elif "integer" in pprops:
  776. hmitype = FLAG_CONTROL_INTEGER
  777. else:
  778. hmitype = 0x0 # linear, fallback mode
  779. if "logarithmic" in pprops:
  780. hmitype |= FLAG_CONTROL_LOGARITHMIC
  781. if "trigger" in pprops:
  782. hmitype |= FLAG_CONTROL_TRIGGER
  783. if portsymbol == ":bpm" and "tapTempo" in pprops and actuator_uri.startswith("/hmi/footswitch"):
  784. hmitype |= FLAG_CONTROL_TAP_TEMPO
  785. if tempo or "enumeration" in pprops and len(port_info["scalePoints"]) > 0:
  786. hmitype |= FLAG_CONTROL_ENUMERATION|FLAG_CONTROL_SCALE_POINTS
  787. # first actuator in group should have reverse enum hmi type
  788. if group is not None:
  789. group_actuator = next((act for act in self.hw_actuators if act['uri'] == group), None)
  790. if group_actuator is not None:
  791. if group_actuator['actuator_group'].index(actuator_uri) == 0:
  792. hmitype |= FLAG_CONTROL_REVERSE
  793. else:
  794. hmitype &= ~FLAG_CONTROL_REVERSE
  795. # hmi specific
  796. addressing_data['hmitype'] = hmitype
  797. addressings = self.hmi_addressings[actuator_uri]
  798. # if old_hmi_index is False:
  799. addressings['idx'] = len(addressings['addrs'])
  800. addressings['addrs'].append(addressing_data)
  801. # else:
  802. # addressings['addrs'].insert(old_hmi_index, addressing_data)
  803. elif actuator_type == self.ADDRESSING_TYPE_BPM:
  804. addressings = self.virtual_addressings[actuator_uri]
  805. # make sure to not add the same addressing more than once
  806. for i, addr in enumerate(addressings):
  807. if addressing_data['actuator_uri'] != addr['actuator_uri']:
  808. continue
  809. if addressing_data['instance_id'] != addr['instance_id']:
  810. continue
  811. if addressing_data['port'] != addr['port']:
  812. continue
  813. return None
  814. addressings.append(addressing_data)
  815. elif actuator_type == self.ADDRESSING_TYPE_CC:
  816. if actuator_uri not in self.cc_addressings.keys():
  817. print("ERROR: Can't load addressing for unavailable hardware '%s'" % actuator_uri)
  818. return None
  819. if portsymbol == ":bypass":
  820. cctype = CC_MODE_TOGGLE|CC_MODE_INTEGER
  821. if momentary:
  822. cctype |= CC_MODE_MOMENTARY
  823. if momentary == 2:
  824. cctype |= CC_MODE_REVERSE
  825. elif portsymbol == ":presets":
  826. cctype = CC_MODE_OPTIONS|CC_MODE_INTEGER
  827. if coloured:
  828. cctype |= CC_MODE_COLOURED
  829. else:
  830. if "toggled" in pprops:
  831. cctype = CC_MODE_TOGGLE
  832. if momentary:
  833. cctype |= CC_MODE_MOMENTARY
  834. if momentary == 2:
  835. cctype |= CC_MODE_REVERSE
  836. elif "integer" in pprops:
  837. cctype = CC_MODE_INTEGER
  838. else:
  839. cctype = CC_MODE_REAL
  840. if "logarithmic" in pprops:
  841. cctype |= CC_MODE_LOGARITHMIC
  842. if "trigger" in pprops:
  843. cctype |= CC_MODE_TRIGGER
  844. if portsymbol == ":bpm" and "tapTempo" in pprops:
  845. cctype |= CC_MODE_TAP_TEMPO
  846. if tempo or "enumeration" in pprops and len(port_info["scalePoints"]) > 0:
  847. cctype |= CC_MODE_OPTIONS
  848. if coloured:
  849. cctype |= CC_MODE_COLOURED
  850. # CC specific
  851. addressing_data['cctype'] = cctype
  852. addressings = self.cc_addressings[actuator_uri]
  853. addressings.append(addressing_data)
  854. elif actuator_type == self.ADDRESSING_TYPE_CV:
  855. if actuator_uri not in self.cv_addressings.keys():
  856. print("ERROR: Can't load addressing for unavailable hardware '%s'" % actuator_uri)
  857. return None
  858. addressings = self.cv_addressings[actuator_uri]
  859. if self.is_hw_cv_port(actuator_uri):
  860. addressings.append(addressing_data)
  861. else:
  862. # plugin cv ports addressings have the following structure:
  863. # { "name": "Env out", "addrs": [...] }
  864. addressings['addrs'].append(addressing_data)
  865. return addressing_data
  866. def add_midi(self, instance_id, portsymbol, midichannel, midicontrol, minimum, maximum):
  867. actuator_uri = self.create_midi_cc_uri(midichannel, midicontrol)
  868. # NOTE: label, value, steps and options missing, not needed or used for MIDI
  869. addressing_data = {
  870. 'actuator_uri': actuator_uri,
  871. 'instance_id' : instance_id,
  872. 'port' : portsymbol,
  873. 'minimum' : minimum,
  874. 'maximum' : maximum,
  875. # MIDI specific
  876. 'midichannel' : midichannel,
  877. 'midicontrol' : midicontrol,
  878. }
  879. if actuator_uri not in self.midi_addressings.keys():
  880. self.midi_addressings[actuator_uri] = []
  881. addressings = self.midi_addressings[actuator_uri]
  882. addressings.append(addressing_data)
  883. return addressing_data
  884. def load_addr(self, actuator_uri, addressing_data, callback, send_hmi=True):
  885. addressing_data = addressing_data.copy()
  886. actuator_hw = actuator_uri
  887. actuator_type = self.get_actuator_type(actuator_uri)
  888. def hmi_map_callback(resp):
  889. self.remap_host_hmi(actuator_hw, addressing_data)
  890. if callback is not None:
  891. callback(resp)
  892. shouldRemap = actuator_type == self.ADDRESSING_TYPE_HMI and not addressing_data.get('tempo', False)
  893. rcallback = hmi_map_callback if shouldRemap else callback
  894. if actuator_type == self.ADDRESSING_TYPE_HMI:
  895. try:
  896. actuator_hw = self.hmi_uri2hw_map[actuator_uri]
  897. actuator_subpage = self.hmi_hwsubpages[actuator_hw]
  898. except KeyError:
  899. if rcallback is not None:
  900. rcallback(False)
  901. print("ERROR: Why fail the hardware/URI mapping? Hardcoded number of actuators?")
  902. return
  903. if self.addressing_pages:
  904. # if new addressing page is not the same as the currently displayed page
  905. if self.current_page != addressing_data['page'] or actuator_subpage != addressing_data['subpage']:
  906. # then no need to send control_add to hmi
  907. if rcallback is not None:
  908. rcallback(True)
  909. return
  910. else:
  911. # HMI specific
  912. addressings = self.hmi_addressings[actuator_uri]
  913. addressing_data['addrs_idx'] = addressings['idx']+1
  914. addressing_data['addrs_max'] = len(addressings['addrs'])
  915. elif actuator_type == self.ADDRESSING_TYPE_CC:
  916. actuator_hw = self.cc_metadata[actuator_uri]['hw_id']
  917. self._task_addressing(actuator_type, actuator_hw, addressing_data, rcallback, send_hmi=send_hmi)
  918. def was_last_load_current_aborted(self):
  919. ret = self.last_load_current_aborted or self.pending_load_current
  920. self.last_load_current_aborted = False
  921. return ret
  922. def load_current_with_callback(self, actuator_uris, skippedPort, updateValue, from_hmi, abort_catcher, callback):
  923. self.load_current(actuator_uris, skippedPort, updateValue, from_hmi, abort_catcher, callback)
  924. @gen.coroutine
  925. def load_current(self, actuator_uris, skippedPort, updateValue, from_hmi, abort_catcher, callback=None):
  926. self.pending_load_current = True
  927. for actuator_uri in actuator_uris:
  928. if abort_catcher.get('abort', False):
  929. self.last_load_current_aborted = True
  930. self.pending_load_current = False
  931. if callback is not None:
  932. callback(False)
  933. print("WARNING: Abort triggered during load_current request, caller:", abort_catcher['caller'])
  934. return
  935. actuator_type = self.get_actuator_type(actuator_uri)
  936. if actuator_type == Addressings.ADDRESSING_TYPE_HMI:
  937. # if the request comes from HMI, we cannot wait for HMI stuff, as otherwise we stall
  938. if from_hmi:
  939. self.hmi_load_current(actuator_uri, None, skippedPort, updateValue)
  940. else:
  941. try:
  942. yield gen.Task(self.hmi_load_current, actuator_uri, skippedPort=skippedPort, updateValue=updateValue)
  943. except Exception as e:
  944. logging.exception(e)
  945. elif actuator_type == Addressings.ADDRESSING_TYPE_CC:
  946. actuator_cc = self.cc_metadata[actuator_uri]['hw_id']
  947. feedback = self.cc_metadata[actuator_uri]['feedback']
  948. addressings = self.cc_addressings[actuator_uri]
  949. for addressing in addressings:
  950. if (addressing['instance_id'], addressing['port']) == skippedPort:
  951. continue
  952. if abort_catcher.get('abort', False):
  953. self.last_load_current_aborted = True
  954. self.pending_load_current = False
  955. if callback is not None:
  956. callback(False)
  957. print("WARNING: Abort triggered in CC loop during load_current request, caller:",
  958. abort_catcher['caller'])
  959. return
  960. # reload value
  961. addressing['value'] = self._task_get_port_value(addressing['instance_id'], addressing['port'])
  962. # NOTE we never call `value_set` for CC lists, as it breaks pagination
  963. if feedback and (addressing['cctype'] & CC_MODE_OPTIONS) == 0x0:
  964. try:
  965. yield gen.Task(self._task_set_value, self.ADDRESSING_TYPE_CC, actuator_cc, addressing)
  966. except Exception as e:
  967. logging.exception(e)
  968. else:
  969. try:
  970. yield gen.Task(self._task_unaddressing, self.ADDRESSING_TYPE_CC,
  971. addressing['instance_id'], addressing['port'])
  972. yield gen.Task(self._task_addressing, self.ADDRESSING_TYPE_CC, actuator_cc, addressing)
  973. except Exception as e:
  974. logging.exception(e)
  975. self.pending_load_current = False
  976. if callback is not None:
  977. callback(True)
  978. def remove_hmi(self, addressing_data, actuator_uri):
  979. addressings = self.hmi_addressings[actuator_uri]
  980. actuator_hmi = self.hmi_uri2hw_map[actuator_uri]
  981. actuator_subpage = self.hmi_hwsubpages[actuator_hmi]
  982. addressings_addrs = addressings['addrs']
  983. actuator_uri = addressing_data['actuator_uri']
  984. instance_id = addressing_data['instance_id']
  985. portsymbol = addressing_data['port']
  986. if self.addressing_pages:
  987. was_assigned = self.is_page_assigned(addressings_addrs, self.current_page, actuator_subpage)
  988. for i, addr in enumerate(addressings_addrs):
  989. if actuator_uri != addr['actuator_uri']:
  990. continue
  991. if instance_id != addr['instance_id']:
  992. continue
  993. if portsymbol != addr['port']:
  994. continue
  995. index = i
  996. addressings_addrs.pop(index)
  997. break
  998. else:
  999. return False
  1000. if self._task_host_hmi_unmap is not None:
  1001. self._task_host_hmi_unmap(instance_id, portsymbol)
  1002. if self.addressing_pages:
  1003. return was_assigned
  1004. old_idx = addressings['idx']
  1005. if old_idx != 0 or (old_idx == 0 and not len(addressings_addrs)):
  1006. addressings['idx'] -= 1
  1007. return True
  1008. def remove_cc(self, addressing_data, actuator_uri):
  1009. addressings = self.cc_addressings[actuator_uri]
  1010. instance_id = addressing_data['instance_id']
  1011. portsymbol = addressing_data['port']
  1012. for i, addr in enumerate(addressings):
  1013. if actuator_uri != addr['actuator_uri']:
  1014. continue
  1015. if instance_id != addr['instance_id']:
  1016. continue
  1017. if portsymbol != addr['port']:
  1018. continue
  1019. addressings.pop(i)
  1020. break
  1021. def remove_virtual(self, addressing_data, actuator_uri):
  1022. addressings = self.virtual_addressings[actuator_uri]
  1023. instance_id = addressing_data['instance_id']
  1024. portsymbol = addressing_data['port']
  1025. for i, addr in enumerate(addressings):
  1026. if actuator_uri != addr['actuator_uri']:
  1027. continue
  1028. if instance_id != addr['instance_id']:
  1029. continue
  1030. if portsymbol != addr['port']:
  1031. continue
  1032. addressings.pop(i)
  1033. break
  1034. # NOTE: make sure to call hmi_load_current() afterwards if removing HMI addressings
  1035. def remove(self, addressing_data):
  1036. actuator_uri = addressing_data['actuator_uri']
  1037. actuator_type = self.get_actuator_type(actuator_uri)
  1038. if actuator_type == self.ADDRESSING_TYPE_HMI:
  1039. group_actuators = self.get_group_actuators(actuator_uri)
  1040. if group_actuators is not None:
  1041. for i in range(len(group_actuators)):
  1042. group_actuator_uri = group_actuators[i]
  1043. group_addressing_data = addressing_data.copy()
  1044. group_addressing_data['actuator_uri'] = group_actuator_uri
  1045. if i == 0: # first actuator has reverse enum hmi type
  1046. group_addressing_data['hmitype'] |= FLAG_CONTROL_REVERSE
  1047. else:
  1048. group_addressing_data['hmitype'] &= ~FLAG_CONTROL_REVERSE
  1049. was_active = self.remove_hmi(group_addressing_data, group_actuator_uri)
  1050. return was_active
  1051. else:
  1052. return self.remove_hmi(addressing_data, actuator_uri)
  1053. elif actuator_type == self.ADDRESSING_TYPE_CC:
  1054. self.remove_cc(addressing_data, actuator_uri)
  1055. elif actuator_type == self.ADDRESSING_TYPE_MIDI:
  1056. addressings = self.midi_addressings[actuator_uri]
  1057. addressings.remove(addressing_data)
  1058. elif actuator_type == self.ADDRESSING_TYPE_BPM:
  1059. self.remove_virtual(addressing_data, actuator_uri)
  1060. elif actuator_type == self.ADDRESSING_TYPE_CV:
  1061. addressings = self.cv_addressings[actuator_uri]
  1062. if self.is_hw_cv_port(actuator_uri):
  1063. addressings.remove(addressing_data)
  1064. else:
  1065. addressings['addrs'].remove(addressing_data)
  1066. def update_for_snapshots(self, actuator_uri, instance_id, portsymbol, newdata):
  1067. actuator_type = self.get_actuator_type(actuator_uri)
  1068. if actuator_type == self.ADDRESSING_TYPE_HMI:
  1069. addressings = self.hmi_addressings[actuator_uri]['addrs']
  1070. elif actuator_type == self.ADDRESSING_TYPE_CC:
  1071. addressings = self.cc_addressings[actuator_uri]
  1072. else:
  1073. return
  1074. for addr in addressings:
  1075. if actuator_uri != addr['actuator_uri']:
  1076. continue
  1077. if instance_id != addr['instance_id']:
  1078. continue
  1079. if portsymbol != addr['port']:
  1080. continue
  1081. addr.update(newdata)
  1082. return
  1083. def is_page_assigned(self, addrs, page, subpage):
  1084. return any('page' in a and a['page'] == page and a['subpage'] == subpage for a in addrs)
  1085. def get_addressing_for_page(self, addrs, page, subpage):
  1086. # Assumes is_page_assigned(addrs, page) has returned True
  1087. return next(a for a in addrs if 'page' in a and a['page'] == page and a['subpage'] == subpage)
  1088. # -----------------------------------------------------------------------------------------------------------------
  1089. # HMI specific functions
  1090. def hmi_load_current(self, actuator_uri, callback,
  1091. skippedPort = (None, None), updateValue = False, send_hmi = True, newValue = None):
  1092. actuator_hmi = self.hmi_uri2hw_map[actuator_uri]
  1093. actuator_subpage = self.hmi_hwsubpages[actuator_hmi]
  1094. addressings = self.hmi_addressings[actuator_uri]
  1095. addressings_addrs = addressings['addrs']
  1096. addressings_len = len(addressings['addrs'])
  1097. if addressings_len == 0:
  1098. print("T2 addressings_len == 0")
  1099. if callback is not None:
  1100. callback(False)
  1101. return
  1102. if self.addressing_pages: # device supports pages
  1103. current_page_assigned = self.is_page_assigned(addressings_addrs, self.current_page, actuator_subpage)
  1104. if not current_page_assigned:
  1105. if callback is not None:
  1106. callback(False)
  1107. return
  1108. else:
  1109. addressing_data = self.get_addressing_for_page(addressings_addrs, self.current_page, actuator_subpage)
  1110. if (addressing_data['instance_id'], addressing_data['port']) == skippedPort:
  1111. print("skippedPort", skippedPort)
  1112. if callback is not None:
  1113. callback(True)
  1114. return
  1115. if newValue is not None:
  1116. addressing_data['value'] = newValue
  1117. else:
  1118. try:
  1119. addressing_data['value'] = self._task_get_port_value(addressing_data['instance_id'],
  1120. addressing_data['port'])
  1121. except KeyError:
  1122. if callback is not None:
  1123. callback(False)
  1124. return
  1125. if addressing_data.get('tempo', False):
  1126. dividers = self._task_get_tempo_divider(addressing_data['instance_id'],
  1127. addressing_data['port'])
  1128. addressing_data['dividers'] = dividers
  1129. else:
  1130. addressings_idx = addressings['idx']
  1131. if addressings_len == addressings_idx:
  1132. canSkipAddressing = False
  1133. addressings['idx'] = addressings_idx = addressings_len - 1
  1134. else:
  1135. canSkipAddressing = True
  1136. # current addressing data
  1137. addressing_data = addressings_addrs[addressings_idx].copy()
  1138. if canSkipAddressing and (addressing_data['instance_id'], addressing_data['port']) == skippedPort:
  1139. print("skippedPort", skippedPort)
  1140. if callback is not None:
  1141. callback(True)
  1142. return
  1143. # needed fields for addressing task
  1144. addressing_data['addrs_idx'] = addressings_idx+1
  1145. addressing_data['addrs_max'] = addressings_len
  1146. # reload value
  1147. addressing = addressings_addrs[addressings_idx]
  1148. if newValue is None:
  1149. try:
  1150. newValue = self._task_get_port_value(addressing['instance_id'], addressing['port'])
  1151. except KeyError:
  1152. if callback is not None:
  1153. callback(False)
  1154. return
  1155. addressing['value'] = addressing_data['value'] = newValue
  1156. if addressing_data.get('tempo', False):
  1157. dividers = self._task_get_tempo_divider(addressing['instance_id'], addressing['port'])
  1158. addressing['dividers'] = addressing_data['dividers'] = dividers
  1159. # NOTE we never call `control_set` for HMI lists, as it breaks pagination
  1160. if updateValue and not (addressing_data['hmitype'] & FLAG_CONTROL_ENUMERATION):
  1161. self._task_set_value(self.ADDRESSING_TYPE_HMI, actuator_hmi, addressing_data, callback, send_hmi=send_hmi)
  1162. else:
  1163. self._task_addressing(self.ADDRESSING_TYPE_HMI, actuator_hmi, addressing_data, callback, send_hmi=send_hmi)
  1164. def hmi_load_footswitches(self, callback):
  1165. def footswitch1_callback(_):
  1166. self.hmi_load_current("/hmi/footswitch2", callback)
  1167. self.hmi_load_current("/hmi/footswitch1", footswitch1_callback)
  1168. def hmi_load_first(self, actuator_uri, callback):
  1169. addressings = self.hmi_addressings[actuator_uri]
  1170. addressings_len = len(addressings['addrs'])
  1171. if addressings_len == 0:
  1172. print("addressings_len == 0")
  1173. callback(False)
  1174. return
  1175. # jump to first addressing or page
  1176. addressings['idx'] = 0
  1177. self.current_page = 0
  1178. # ready to load
  1179. self.hmi_load_current(actuator_uri, callback)
  1180. def hmi_load_next_hw(self, hw_id):
  1181. actuator_uri = self.hmi_hw2uri_map[hw_id]
  1182. addressings = self.hmi_addressings[actuator_uri]
  1183. addressings_len = len(addressings['addrs'])
  1184. if addressings_len == 0:
  1185. print("ERROR: hmi_load_next_hw failed, empty list")
  1186. return
  1187. # jump to next available addressing
  1188. addressings['idx'] = (addressings['idx'] + 1) % addressings_len
  1189. # ready to load
  1190. self.hmi_load_current(actuator_uri, None)
  1191. def hmi_load_subpage(self, hw_id, subpage):
  1192. actuator_uri = self.hmi_hw2uri_map[hw_id]
  1193. addressings = self.hmi_addressings[actuator_uri]
  1194. addressings_len = len(addressings['addrs'])
  1195. # set actuator page
  1196. self.hmi_hwsubpages[hw_id] = subpage
  1197. # ready to load
  1198. self.hmi_load_current(actuator_uri, None)
  1199. def hmi_get_addr_data(self, hw_id):
  1200. actuator_uri = self.hmi_hw2uri_map[hw_id]
  1201. actuator_subpage = self.hmi_hwsubpages[hw_id]
  1202. addressings = self.hmi_addressings[actuator_uri]
  1203. addressings_addrs = addressings['addrs']
  1204. addressings_len = len(addressings_addrs)
  1205. if addressings_len == 0:
  1206. print("ERROR: hmi_get_addr_data failed, empty list")
  1207. return None
  1208. if self.addressing_pages: # device supports pages
  1209. if not self.is_page_assigned(addressings_addrs, self.current_page, actuator_subpage):
  1210. return None
  1211. return self.get_addressing_for_page(addressings_addrs, self.current_page, actuator_subpage)
  1212. else:
  1213. return addressings_addrs[addressings['idx']]
  1214. # def hmi_load_next_page(self, page_to_load, callback):
  1215. def remap_host_hmi(self, hw_id, data):
  1216. if self._task_host_hmi_map is None:
  1217. return
  1218. page = data['page'] or 0
  1219. subpage = data['subpage'] or 0
  1220. label = data['label']
  1221. hmitype = data['hmitype']
  1222. if data.get('group', None) is not None and self.hmi_show_actuator_group_prefix:
  1223. if hmitype & FLAG_CONTROL_REVERSE:
  1224. prefix = "- "
  1225. else:
  1226. prefix = "+ "
  1227. label = prefix + label
  1228. label = normalize_for_hw(label)
  1229. hostcaps = 0x0
  1230. for actuator in self.hw_actuators:
  1231. if actuator['id'] != hw_id:
  1232. continue
  1233. widgets = actuator.get('widgets', None)
  1234. if widgets is None:
  1235. break
  1236. if "led" in widgets:
  1237. hostcaps |= LV2_HMI_AddressingCapability_LED
  1238. if "label" in widgets:
  1239. hostcaps |= LV2_HMI_AddressingCapability_Label
  1240. if "value" in widgets:
  1241. hostcaps |= LV2_HMI_AddressingCapability_Value
  1242. if "unit" in widgets:
  1243. hostcaps |= LV2_HMI_AddressingCapability_Unit
  1244. if "indicator" in widgets:
  1245. hostcaps |= LV2_HMI_AddressingCapability_Indicator
  1246. break
  1247. hostflags = 0x0
  1248. if data.get('coloured', False):
  1249. hostflags |= LV2_HMI_AddressingFlag_Coloured
  1250. if hmitype & FLAG_CONTROL_MOMENTARY:
  1251. hostflags |= LV2_HMI_AddressingFlag_Momentary
  1252. if hmitype & FLAG_CONTROL_REVERSE:
  1253. hostflags |= LV2_HMI_AddressingFlag_Reverse
  1254. if hmitype & FLAG_CONTROL_TAP_TEMPO:
  1255. hostflags |= LV2_HMI_AddressingFlag_TapTempo
  1256. self._task_host_hmi_map(data['instance_id'], data['port'], hw_id, page, subpage,
  1257. hostcaps, hostflags, label, data['minimum'], data['maximum'], data['steps'])
  1258. # -----------------------------------------------------------------------------------------------------------------
  1259. # Control Chain specific functions
  1260. def cc_hardware_added(self, dev_id, dev_uri, label, labelsuffix, version):
  1261. print("cc_hardware_added", dev_id, dev_uri, label, labelsuffix, version)
  1262. self._task_hw_added(dev_uri, label, labelsuffix, version)
  1263. def cc_hardware_removed(self, dev_id, dev_uri, label, version):
  1264. removed_actuators = []
  1265. for actuator in self.cc_metadata.values():
  1266. if actuator['hw_id'][0] == dev_id:
  1267. removed_actuators.append(actuator['uri'])
  1268. for actuator_uri in removed_actuators:
  1269. print("cc_actuator_removed", actuator_uri)
  1270. self.cc_metadata.pop(actuator_uri)
  1271. self.cc_addressings.pop(actuator_uri)
  1272. self._task_act_removed(actuator_uri)
  1273. print("cc_hardware_removed", dev_id, dev_uri, label, version)
  1274. self._task_hw_removed(dev_uri, label, version)
  1275. def cc_actuator_added(self, dev_id, actuator_id, metadata):
  1276. print("cc_actuator_added", metadata['uri'])
  1277. actuator_uri = metadata['uri']
  1278. self.cc_metadata[actuator_uri] = metadata.copy()
  1279. self.cc_metadata[actuator_uri]['hw_id'] = (dev_id, actuator_id)
  1280. self.cc_addressings[actuator_uri] = []
  1281. self._task_act_added(metadata)
  1282. @gen.coroutine
  1283. def cc_load_all(self, actuator_uri):
  1284. actuator_cc = self.cc_metadata[actuator_uri]['hw_id']
  1285. addressings = self.cc_addressings[actuator_uri]
  1286. for addressing in addressings:
  1287. try:
  1288. yield gen.Task(self._task_addressing, self.ADDRESSING_TYPE_CC, actuator_cc, addressing)
  1289. except Exception as e:
  1290. logging.exception(e)
  1291. def wait_for_cc_if_needed(self, callback):
  1292. if not self.waiting_for_cc:
  1293. callback()
  1294. return
  1295. self.waiting_for_cc_cbs.append(callback)
  1296. # -----------------------------------------------------------------------------------------------------------------
  1297. # Utilities
  1298. def create_midi_cc_uri(self, channel, controller):
  1299. if controller == MIDI_PITCHBEND_AS_CC:
  1300. return "%sCh.%d_Pbend" % (kMidiCustomPrefixURI, channel+1)
  1301. return "%sCh.%i_CC#%i" % (kMidiCustomPrefixURI, channel+1, controller)
  1302. def get_midi_cc_from_uri(self, uri):
  1303. data = uri.replace(kMidiCustomPrefixURI+"Ch.","",1).split("_CC#",1)
  1304. if len(data) == 2:
  1305. channel = int(data[0])-1
  1306. if data[1].endswith("_Pbend"):
  1307. controller = MIDI_PITCHBEND_AS_CC
  1308. else:
  1309. controller = int(data[1])
  1310. return (channel, controller)
  1311. print("ERROR: get_midi_cc_from_uri() called with invalid uri:", uri)
  1312. return (-1,-1)
  1313. def is_hmi_actuator(self, actuator_uri):
  1314. return actuator_uri.startswith("/hmi/")
  1315. def get_actuator_type(self, actuator_uri):
  1316. if actuator_uri.startswith("/hmi/"):
  1317. return self.ADDRESSING_TYPE_HMI
  1318. if actuator_uri.startswith(kMidiCustomPrefixURI):
  1319. return self.ADDRESSING_TYPE_MIDI
  1320. if actuator_uri == kBpmURI:
  1321. return self.ADDRESSING_TYPE_BPM
  1322. if actuator_uri.startswith(CV_OPTION):
  1323. return self.ADDRESSING_TYPE_CV
  1324. return self.ADDRESSING_TYPE_CC
  1325. def get_group_actuators(self, actuator_uri):
  1326. if not self.is_hmi_actuator(actuator_uri) or actuator_uri not in self.hw_actuators_uris:
  1327. return None
  1328. actuator = next(a for a in self.hw_actuators if a['uri'] == actuator_uri)
  1329. group_actuators = actuator.get('actuator_group', None)
  1330. if group_actuators is None or len(group_actuators) == 0:
  1331. return None
  1332. return group_actuators
  1333. def get_presets_as_options(self, instance_id):
  1334. pluginData = self._task_get_plugin_data(instance_id)
  1335. presets = self._task_get_plugin_presets(pluginData["uri"])
  1336. handled = False
  1337. maximum = len(presets)
  1338. options = []
  1339. value = 0
  1340. # save preset mapping
  1341. pluginData['mapPresets'] = []
  1342. # safety check
  1343. if maximum == 0:
  1344. pluginData['preset'] = ""
  1345. print("ERROR: get_presets_as_options() called with 0 presets available for '%s'" % pluginData["uri"])
  1346. return None
  1347. # if no preset selected yet, we need to force one
  1348. if not pluginData['preset']:
  1349. pluginData['preset'] = presets[0]['uri']
  1350. handled = True
  1351. # save preset list, within a limit
  1352. for i in range(maximum):
  1353. uri = presets[i]['uri']
  1354. pluginData['mapPresets'].append(uri)
  1355. options.append((i, presets[i]['label']))
  1356. if handled:
  1357. continue
  1358. if pluginData['preset'] == uri:
  1359. value = i
  1360. handled = True
  1361. # check if selected preset is non-existent
  1362. if not handled:
  1363. print("WARNING: get_presets_as_options() called with an invalid preset uri '%s'" % pluginData['preset'])
  1364. value = 0
  1365. pluginData['preset'] = presets[0]['uri']
  1366. return (value, maximum, options, pluginData['preset'])
  1367. # -----------------------------------------------------------------------------------------------------------------
  1368. # CV specific functions
  1369. @gen.coroutine
  1370. def cv_load_all(self, actuator_uri):
  1371. addressings = self.cv_addressings[actuator_uri]
  1372. if not self.is_hw_cv_port(actuator_uri):
  1373. addressings = addressings['addrs']
  1374. for addressing in addressings:
  1375. data = {
  1376. 'instance_id' : addressing['instance_id'],
  1377. 'port' : addressing['port'],
  1378. 'label' : addressing['label'],
  1379. 'value' : addressing['value'],
  1380. 'minimum' : addressing['minimum'],
  1381. 'maximum' : addressing['maximum'],
  1382. 'steps' : addressing['steps'],
  1383. 'unit' : addressing['unit'],
  1384. 'options' : addressing['options'],
  1385. 'operational_mode': addressing['operational_mode'],
  1386. }
  1387. try:
  1388. yield gen.Task(self._task_addressing, self.ADDRESSING_TYPE_CV, actuator_uri, data)
  1389. except Exception as e:
  1390. logging.exception(e)
  1391. def is_hw_cv_port(self, actuator_uri):
  1392. if actuator_uri.startswith(HW_CV_PREFIX):
  1393. return True
  1394. return False
  1395. def add_hw_cv_port(self, actuator_uri):
  1396. if not self.is_hw_cv_port(actuator_uri):
  1397. return
  1398. if actuator_uri not in self.cv_addressings:
  1399. self.cv_addressings[actuator_uri] = []