aboutsummaryrefslogtreecommitdiff
path: root/example-scripts/voctomidi/voctomidi.py
blob: b21f529ad9932382ca32cbd82526586be9fcb303 (plain)
  1. #!/usr/bin/env python3
  2. import atexit
  3. import socket
  4. import sys
  5. import time
  6. from rtmidi.midiutil import open_midiport
  7. from lib.config import Config
  8. NOTE_ON = 144
  9. host = Config.get("server", "host")
  10. port = 9999
  11. device = Config.get("midi", "device")
  12. event_map = dict(map(lambda x: (int(x[0]), x[1]), Config.items("eventmap")))
  13. class MidiInputHandler(object):
  14. def __init__(self, port):
  15. self.port = port
  16. def __call__(self, event, data=None):
  17. global conn
  18. message, _deltatime = event
  19. if message[0] != NOTE_ON:
  20. return
  21. if message[1] in event_map:
  22. note = message[1]
  23. msg = "set_videos_and_composite " + event_map[note]
  24. print("Sending: '{}'".format(msg))
  25. try:
  26. conn.sendall(msg.encode('ascii') + b"\n")
  27. except BrokenPipeError:
  28. print("voctocore disconnected, trying to reconnect")
  29. try:
  30. conn = socket.create_connection((host, port))
  31. print("Reconnected to voctocore")
  32. except:
  33. pass
  34. else:
  35. print("[{}]: Unhandled NOTE ON event {}".format(self.port,
  36. message[1]))
  37. @atexit.register
  38. def kthxbye():
  39. print("Exit")
  40. conn, midiin = None, None
  41. try:
  42. conn = socket.create_connection((host, port))
  43. except (ConnectionRefusedError, KeyboardInterrupt):
  44. print("Could not connect to voctocore")
  45. sys.exit()
  46. @atexit.register
  47. def close_conn():
  48. global conn
  49. conn and conn.close()
  50. try:
  51. midiin, port_name = open_midiport(device)
  52. except (EOFError, KeyboardInterrupt):
  53. print("Opening midi port failed")
  54. sys.exit()
  55. @atexit.register
  56. def close_midi():
  57. global midiin
  58. midiin and midiin.close_port()
  59. del midiin
  60. midiin.set_callback(MidiInputHandler(port_name))
  61. print("Entering main loop. Press Control-C to exit.")
  62. try:
  63. # just wait for keyboard interrupt in main thread
  64. while True:
  65. time.sleep(1)
  66. except KeyboardInterrupt:
  67. print("")