hmi.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. #!/usr/bin/env python3
  2. # SPDX-FileCopyrightText: 2012-2023 MOD Audio UG
  3. # SPDX-License-Identifier: AGPL-3.0-or-later
  4. from datetime import timedelta
  5. from tornado.iostream import BaseIOStream, StreamClosedError
  6. from tornado.ioloop import IOLoop
  7. from unicodedata import normalize
  8. from mod import get_hardware_actuators, get_hardware_descriptor, get_nearest_valid_scalepoint_value, normalize_for_hw
  9. from mod.protocol import Protocol, ProtocolError, process_resp
  10. from mod.mod_protocol import (
  11. CMD_PING,
  12. CMD_GUI_CONNECTED,
  13. CMD_GUI_DISCONNECTED,
  14. CMD_INITIAL_STATE,
  15. CMD_CONTROL_ADD,
  16. CMD_CONTROL_REMOVE,
  17. CMD_CONTROL_SET,
  18. CMD_PEDALBOARD_CHANGE,
  19. CMD_PEDALBOARD_CLEAR,
  20. CMD_PEDALBOARD_NAME_SET,
  21. CMD_SNAPSHOT_NAME_SET,
  22. CMD_TUNER,
  23. CMD_TUNER_INPUT,
  24. CMD_TUNER_REF_FREQ,
  25. CMD_MENU_ITEM_CHANGE,
  26. CMD_RESET_EEPROM,
  27. CMD_DUO_CONTROL_INDEX_SET,
  28. CMD_DUO_BANK_CONFIG,
  29. CMD_DUOX_PAGES_AVAILABLE,
  30. CMD_DUOX_EXP_OVERCURRENT,
  31. CMD_RESPONSE,
  32. CMD_RESTORE,
  33. CMD_SCREENSHOT,
  34. FLAG_CONTROL_MOMENTARY,
  35. FLAG_CONTROL_REVERSE,
  36. FLAG_CONTROL_TAP_TEMPO,
  37. FLAG_PAGINATION_PAGE_UP,
  38. FLAG_PAGINATION_WRAP_AROUND,
  39. FLAG_PAGINATION_INITIAL_REQ,
  40. FLAG_PAGINATION_ALT_LED_COLOR,
  41. MENU_ID_TEMPO,
  42. MENU_ID_PLAY_STATUS,
  43. MENU_ID_SL_IN,
  44. MENU_ID_SL_OUT,
  45. MENU_ID_MASTER_VOL_PORT,
  46. MENU_ID_MIDI_CLK_SOURCE,
  47. MENU_ID_MIDI_CLK_SEND,
  48. MENU_ID_SNAPSHOT_PRGCHGE,
  49. MENU_ID_PB_PRGCHNGE,
  50. cmd_to_str,
  51. )
  52. from mod.settings import LOG
  53. import logging
  54. import time
  55. try:
  56. import serial
  57. haveSerial = True
  58. except ImportError:
  59. haveSerial = False
  60. class SerialIOStream(BaseIOStream):
  61. def __init__(self, sp):
  62. self.sp = sp
  63. super(SerialIOStream, self).__init__()
  64. def fileno(self):
  65. return self.sp.fileno()
  66. def close_fd(self):
  67. return self.sp.close()
  68. def write_to_fd(self, data):
  69. try:
  70. return self.sp.write(data)
  71. except serial.SerialTimeoutException:
  72. return 0
  73. def read_from_fd(self):
  74. try:
  75. r = self.sp.read(self.read_chunk_size)
  76. except:
  77. print("SerialIOStream: failed to read from HMI serial")
  78. return None
  79. if r == '':
  80. return None
  81. return r
  82. class HMI(object):
  83. def __init__(self, port, baud_rate, timeout, init_cb, reinit_cb):
  84. self.sp = None
  85. self.port = port
  86. self.baud_rate = baud_rate
  87. self.queue = []
  88. self.queue_idle = True
  89. self.initialized = False
  90. self.connected = False
  91. self.handling_response = False
  92. self.need_flush = 0 # 0 means False, otherwise use it as counter
  93. self.flush_io = None
  94. self.last_write_time = 0
  95. self.timeout = timeout # in seconds
  96. self.reinit_cb = reinit_cb
  97. self.hw_desc = get_hardware_descriptor()
  98. hw_actuators = self.hw_desc.get('actuators', [])
  99. self.hw_ids = [actuator['id'] for actuator in hw_actuators]
  100. self.bpm = None
  101. self.init(init_cb)
  102. def isFake(self):
  103. return False
  104. # this can be overriden by subclasses to avoid any connection in DEV mode
  105. def init(self, callback):
  106. ioloop = IOLoop.instance()
  107. if not haveSerial:
  108. print("ERROR: This system has no python serial support")
  109. ioloop.call_later(1, callback)
  110. return
  111. virtual = self.port.startswith("/dev/ttyHMI")
  112. try:
  113. sp = None
  114. # pylint: disable=unexpected-keyword-arg
  115. try:
  116. sp = serial.Serial(self.port, self.baud_rate, rtscts=virtual, dsrdtr=virtual, timeout=0, write_timeout=0)
  117. except:
  118. sp = serial.Serial(self.port, self.baud_rate, rtscts=virtual, dsrdtr=virtual, timeout=0, writeTimeout=0)
  119. # pylint: enable=unexpected-keyword-arg
  120. sp.flushInput()
  121. sp.flushOutput()
  122. except Exception as e:
  123. print("ERROR: Failed to open HMI serial port, error was:\n%s" % e)
  124. return
  125. self.sp = SerialIOStream(sp)
  126. self.ping_io = None
  127. def clear_callback(ok):
  128. callback()
  129. # calls ping until ok is received
  130. def ping_callback(ok):
  131. if self.ping_io is not None:
  132. ioloop.remove_timeout(self.ping_io)
  133. self.ping_io = None
  134. if ok:
  135. self.clear(clear_callback)
  136. else:
  137. ioloop.call_later(1, call_ping)
  138. def call_ping():
  139. sp.flushInput()
  140. sp.flushOutput()
  141. self.queue = []
  142. self.queue_idle = True
  143. self.ping(ping_callback)
  144. self.ping_io = ioloop.call_later(1, call_ping)
  145. call_ping()
  146. self.checker()
  147. def checker(self, data=None):
  148. ioloop = IOLoop.instance()
  149. if data is not None and data != b'\0':
  150. self.last_write_time = 0
  151. try:
  152. msg = Protocol(data.decode("utf-8", errors="ignore"))
  153. except ProtocolError as e:
  154. logging.error('[hmi] error parsing msg %s', data)
  155. logging.error('[hmi] error code %s', e.error_code())
  156. self.reply_protocol_error(e.error_code())
  157. else:
  158. # reset timeout checks when a message is received
  159. self.need_flush = 0
  160. if self.flush_io is not None:
  161. ioloop.remove_timeout(self.flush_io)
  162. self.flush_io = None
  163. if msg.is_resp():
  164. try:
  165. original_msg, callback, datatype = self.queue.pop(0)
  166. withlog = LOG >= 2 or (LOG and original_msg not in ("pi",))
  167. if withlog:
  168. logging.debug('[hmi] received response <- %s', data)
  169. logging.debug("[hmi] popped from queue: %s | %s",
  170. original_msg, cmd_to_str(original_msg.split(" ",1)[0]))
  171. except IndexError:
  172. # something is wrong / not synced!!
  173. logging.error("[hmi] NOT SYNCED after receiving %s", data)
  174. else:
  175. if callback is not None:
  176. if withlog:
  177. logging.debug("[hmi] calling callback for %s", original_msg)
  178. callback(msg.process_resp(datatype))
  179. self.process_queue()
  180. else:
  181. def _callback(resp, resp_args=None):
  182. if not isinstance(resp, int):
  183. resp = 0 if resp else -1
  184. if resp_args is None:
  185. self.send_reply("%s %d" % (CMD_RESPONSE, resp))
  186. logging.debug('[hmi] sent "%s %d"', CMD_RESPONSE, resp)
  187. else:
  188. self.send_reply("%s %d %s" % (CMD_RESPONSE, resp, resp_args))
  189. logging.debug('[hmi] sent "%s %d %s"', CMD_RESPONSE, resp, resp_args)
  190. self.handling_response = False
  191. if self.queue_idle:
  192. self.process_queue()
  193. if LOG >= 1:
  194. logging.debug('[hmi] received <- %s | %s', data,
  195. cmd_to_str((data.split(b' ',1)[0] if b' ' in data else data[:-1]).decode("utf-8", errors="ignore")))
  196. self.handling_response = True
  197. msg.run_cmd(_callback)
  198. if self.need_flush != 0:
  199. if self.flush_io is not None:
  200. ioloop.remove_timeout(self.flush_io)
  201. self.flush_io = ioloop.call_later(self.timeout/2, self.flush)
  202. try:
  203. self.sp.read_until(b'\0', self.checker)
  204. except serial.SerialException as e:
  205. logging.error("[hmi] error while reading %s", e)
  206. def flush(self, forced = False):
  207. prev_queue = self.need_flush
  208. self.need_flush = 0
  209. if len(self.queue) < max(5, prev_queue) and not forced:
  210. logging.debug("[hmi] flushing ignored")
  211. return
  212. # FUCK!
  213. logging.warn("[hmi] flushing queue as workaround now: %d in queue", len(self.queue))
  214. self.sp.sp.flush()
  215. self.sp.sp.flushInput()
  216. self.sp.sp.flushOutput()
  217. self.sp.close()
  218. self.sp = None
  219. while len(self.queue) > 1:
  220. msg, callback, datatype = self.queue.pop(0)
  221. if any(msg.startswith(resp) for resp in Protocol.RESPONSES):
  222. if callback is not None:
  223. callback(process_resp(None, datatype))
  224. else:
  225. if callback is not None:
  226. callback("-1003")
  227. self.reinit_cb()
  228. #os.system("touch /tmp/reset-hmi; kill -9 {}".format(os.getpid()))
  229. def process_queue(self):
  230. if self.sp is None:
  231. return
  232. try:
  233. msg, callback, datatype = self.queue[0] # fist msg on the queue
  234. except IndexError:
  235. if LOG >= 2:
  236. logging.debug("[hmi] queue is empty, nothing to do")
  237. self.queue_idle = True
  238. self.last_write_time = 0
  239. else:
  240. if LOG >= 2 or (LOG and msg not in ("pi",)):
  241. logging.debug("[hmi] sending -> %s | %s", msg, cmd_to_str(msg.split(" ",1)[0]))
  242. try:
  243. self.sp.write(msg.encode('utf-8') + b'\0')
  244. except StreamClosedError as e:
  245. logging.exception(e)
  246. self.sp = None
  247. self.queue_idle = False
  248. self.last_write_time = time.time()
  249. def reply_protocol_error(self, error):
  250. #self.send(error) # TODO: proper error handling, needs to be implemented by HMI
  251. self.send("{} -1".format(CMD_RESPONSE), None)
  252. def send(self, msg, callback, datatype='int'):
  253. if self.sp is None:
  254. return
  255. if self.timeout > 0:
  256. if len(self.queue) > 30:
  257. self.need_flush = len(self.queue)
  258. elif self.last_write_time != 0 and time.time() - self.last_write_time > self.timeout:
  259. logging.warn("[hmi] no response for %ds, giving up", self.timeout)
  260. if self.flush_io is not None:
  261. IOLoop.instance().remove_timeout(self.flush_io)
  262. self.flush_io = None
  263. self.flush(True)
  264. if not any([ msg.startswith(resp) for resp in Protocol.RESPONSES ]):
  265. # make an exception for control_set, calling callback right away without waiting
  266. #if msg.startswith("s "):
  267. #self.queue.append((msg, None, datatype))
  268. #if callback is not None:
  269. #callback(True)
  270. #else:
  271. self.queue.append((msg, callback, datatype))
  272. if LOG >= 2 or (LOG and msg not in ("pi",)):
  273. logging.debug("[hmi] scheduling -> %s | %s", msg, cmd_to_str(msg.split(" ",1)[0]))
  274. if self.queue_idle and not self.handling_response:
  275. self.process_queue()
  276. return
  277. # is resp, just send
  278. self.sp.write(msg.encode('utf-8') + b'\0')
  279. def send_reply(self, msg):
  280. if self.sp is None:
  281. return
  282. self.sp.write(msg.encode('utf-8') + b'\0')
  283. def initial_state(self, data, callback):
  284. self.send('{} {}'.format(CMD_INITIAL_STATE, data), callback)
  285. def ui_con(self, callback):
  286. self.send(CMD_GUI_CONNECTED, callback, 'boolean')
  287. def ui_dis(self, callback):
  288. self.send(CMD_GUI_DISCONNECTED, callback, 'boolean')
  289. def control_add(self, data, hw_id, actuator_uri, callback):
  290. # instance_id = data['instance_id']
  291. # port = data['port']
  292. hasTempo = data.get('tempo', False)
  293. label = data['label']
  294. var_type = data['hmitype']
  295. unit = data['unit']
  296. value = data['dividers'] if hasTempo else data['value']
  297. xmin = data['minimum']
  298. xmax = data['maximum']
  299. steps = data['steps']
  300. options = data['options']
  301. hmi_set_index = self.hw_desc.get('hmi_set_index', False)
  302. if data.get('group', None) is not None and self.hw_desc.get('hmi_actuator_group_prefix', True):
  303. if var_type & FLAG_CONTROL_REVERSE:
  304. prefix = "- "
  305. else:
  306. prefix = "+ "
  307. label = prefix + label
  308. label = normalize_for_hw(label)
  309. unit = normalize_for_hw(unit, 7)
  310. if value < xmin:
  311. logging.error('[hmi] control_add received value < min for %s', label)
  312. value = xmin
  313. elif value > xmax:
  314. logging.error('[hmi] control_add received value > max for %s', label)
  315. value = xmax
  316. if options:
  317. numOpts = len(options)
  318. optionsData = []
  319. ivalue, value = get_nearest_valid_scalepoint_value(value, options)
  320. if hasTempo:
  321. unit = '""'
  322. startIndex = 0
  323. endIndex = numOpts
  324. else:
  325. if numOpts <= 5 or ivalue <= 2:
  326. startIndex = 0
  327. elif ivalue+2 >= numOpts:
  328. startIndex = numOpts-5
  329. else:
  330. startIndex = ivalue - 2
  331. endIndex = min(startIndex+5, numOpts)
  332. flags = 0x0
  333. if startIndex != 0 or endIndex != numOpts:
  334. flags |= FLAG_PAGINATION_PAGE_UP
  335. if data.get('group', None) is None:
  336. flags |= FLAG_PAGINATION_WRAP_AROUND
  337. if endIndex == numOpts:
  338. flags |= FLAG_PAGINATION_INITIAL_REQ
  339. if data.get('coloured', False):
  340. flags |= FLAG_PAGINATION_ALT_LED_COLOR
  341. data['steps'] = steps = numOpts - 1
  342. for i in range(startIndex, endIndex):
  343. option = options[i]
  344. xdata = '%s %f' % (normalize_for_hw(option[1]), float(option[0]))
  345. optionsData.append(xdata)
  346. options = "%d %d %d %s" % (len(optionsData), flags, ivalue, " ".join(optionsData))
  347. options = options.strip()
  348. else:
  349. flags = 0x0
  350. options = "0"
  351. def control_add_callback(ok):
  352. if not ok:
  353. callback(False)
  354. return
  355. n_controllers = data['addrs_max']
  356. index = data['addrs_idx']
  357. self.control_set_index(hw_id, index, n_controllers, callback)
  358. # FIXME this should be based on hw desc "max_assigns" instead of hardcoded
  359. if not actuator_uri.startswith("/hmi/footswitch") and hmi_set_index:
  360. cb = control_add_callback
  361. else:
  362. cb = callback
  363. self.send('%s %d %s %d %s %f %f %f %d %s' %
  364. ( CMD_CONTROL_ADD,
  365. hw_id,
  366. label,
  367. var_type,
  368. unit,
  369. value,
  370. xmax,
  371. xmin,
  372. steps,
  373. options,
  374. ),
  375. cb, 'boolean')
  376. def control_set_index(self, hw_id, index, n_controllers, callback):
  377. self.send('%s %d %d %d' % (CMD_DUO_CONTROL_INDEX_SET, hw_id, index, n_controllers), callback, 'boolean')
  378. def control_set(self, hw_id, value, callback):
  379. """Set a plug-in's control port value on the HMI."""
  380. # control_set <hw_id> <value>"""
  381. self.send('%s %d %f' % (CMD_CONTROL_SET, hw_id, value), callback, 'boolean')
  382. def control_rm(self, hw_ids, callback):
  383. """
  384. removes an addressing
  385. """
  386. ids = " ".join(str(i) for i in hw_ids).strip()
  387. self.send('%s %s' % (CMD_CONTROL_REMOVE, ids), callback, 'boolean')
  388. def ping(self, callback):
  389. self.send(CMD_PING, callback, 'boolean')
  390. def tuner(self, freq, note, cents, callback):
  391. self.send('%s %f %s %d' % (CMD_TUNER, freq, note, cents), callback)
  392. #TODO, This message should be handled by mod-system-control once in place
  393. def expression_overcurrent(self, callback):
  394. self.send(CMD_DUOX_EXP_OVERCURRENT, callback, 'boolean')
  395. def bank_config(self, hw_id, action, callback):
  396. """
  397. configures bank addressings
  398. action is one of the following:
  399. 0: None (usado para des-endereçar)
  400. 1: True Bypass
  401. 2: Pedalboard UP
  402. 3: Pedalboard DOWN
  403. """
  404. self.send('%s %d %d' % (CMD_DUO_BANK_CONFIG, hw_id, action), callback, 'boolean')
  405. def set_bpm(self, bpm):
  406. if round(bpm) != self.bpm:
  407. self.bpm = round(bpm)
  408. return True
  409. return False
  410. # new messages
  411. def clear(self, callback):
  412. self.send(CMD_PEDALBOARD_CLEAR, callback)
  413. def set_profile_value(self, key, value, callback):
  414. # Do not send new bpm value to HMI if its int value is the same
  415. if key == MENU_ID_TEMPO and not self.set_bpm(value):
  416. if callback is not None:
  417. callback(True)
  418. else:
  419. if key == MENU_ID_TEMPO:
  420. value = self.bpm # set rounded value for bpm
  421. self.send("%s %i %i" % (CMD_MENU_ITEM_CHANGE, key, int(value)), callback, 'boolean')
  422. def set_profile_values(self, playback_rolling, values, callback):
  423. msg = CMD_MENU_ITEM_CHANGE
  424. msg += " %i %i" % (MENU_ID_SL_IN, int(values['inputStereoLink']))
  425. msg += " %i %i" % (MENU_ID_SL_OUT, int(values['outputStereoLink']))
  426. msg += " %i %i" % (MENU_ID_PLAY_STATUS, int(playback_rolling))
  427. msg += " %i %i" % (MENU_ID_MIDI_CLK_SOURCE, values['transportSource'])
  428. msg += " %i %i" % (MENU_ID_MIDI_CLK_SEND, int(values['midiClockSend']))
  429. msg += " %i %i" % (MENU_ID_SNAPSHOT_PRGCHGE, values['midiChannelForSnapshotsNavigation'])
  430. msg += " %i %i" % (MENU_ID_PB_PRGCHNGE, values['midiChannelForPedalboardsNavigation'])
  431. msg += " %i %i" % (MENU_ID_MASTER_VOL_PORT, int(values['masterVolumeChannelMode']))
  432. self.send(msg, callback)
  433. # pages is a list of int (1 if page available else 0)
  434. # NOTE CMD_DUOX_PAGES_AVAILABLE and CMD_DWARF_PAGES_AVAILABLE have the same message prefix
  435. def set_available_pages(self, pages, callback):
  436. msg = CMD_DUOX_PAGES_AVAILABLE
  437. for page_enabled in pages:
  438. msg += " %i" % int(page_enabled)
  439. self.send(msg, callback, 'boolean')
  440. # even newer messages. really need to clean this up later..
  441. def restore(self, callback=None, datatype='int'):
  442. self.send(CMD_RESTORE, callback, datatype)
  443. def reset_eeprom(self, callback=None, datatype='int'):
  444. self.send(CMD_RESET_EEPROM, callback, datatype)
  445. def screenshot(self, screen, callback=None, datatype='int'):
  446. self.send('{} {} ignored'.format(CMD_SCREENSHOT, screen), callback, datatype)
  447. # FIXME this message should be generic, most likely
  448. def boot(self, bootdata, callback, datatype='int'):
  449. self.send("boot {}".format(bootdata), callback, datatype)
  450. def set_pedalboard_index(self, index, callback):
  451. self.send('{} {}'.format(CMD_PEDALBOARD_CHANGE, index), callback)
  452. def set_pedalboard_name(self, name, callback):
  453. self.send('{} {}'.format(CMD_PEDALBOARD_NAME_SET, normalize_for_hw(name)), callback)
  454. def set_snapshot_name(self, index, name, callback):
  455. self.send('{} {} {}'.format(CMD_SNAPSHOT_NAME_SET, index, normalize_for_hw(name)), callback)
  456. def set_tuner_input(self, port, callback, datatype='int'):
  457. self.send('{} {}'.format(CMD_TUNER_INPUT, port), callback, datatype)
  458. def set_tuner_ref_freq(self, freq, callback, datatype='int'):
  459. self.send('{} {}'.format(CMD_TUNER_REF_FREQ, freq), callback, datatype)