summaryrefslogtreecommitdiff
path: root/voctogui/lib/connection.py
blob: 20197d006c659d1f91e86f283ee2e94585d8e781 (plain)
  1. #!/usr/bin/python3
  2. import logging
  3. import socket
  4. import json
  5. import sys
  6. from queue import Queue
  7. from gi.repository import Gtk, GObject
  8. log = logging.getLogger('Connection')
  9. conn = None
  10. port = 9999
  11. command_queue = Queue()
  12. signal_handlers = {}
  13. def establish(host):
  14. global conn, port, log
  15. log.info('establishing Connection to %s', host)
  16. conn = socket.create_connection( (host, port) )
  17. log.debug('Connection successful \o/')
  18. def fetchServerConfig():
  19. global conn, log
  20. log.info('reading server-config')
  21. fd = conn.makefile('rw')
  22. fd.write("get_config\n")
  23. fd.flush()
  24. while True:
  25. line = fd.readline()
  26. words = line.split(' ')
  27. signal = words[0]
  28. args = words[1:]
  29. if signal != 'server_config':
  30. continue
  31. server_config_json = " ".join(args)
  32. server_config = json.loads(server_config_json)
  33. return server_config
  34. def enterNonblockingMode():
  35. global conn, log
  36. log.debug('entering nonblocking-mode')
  37. conn.setblocking(False)
  38. GObject.io_add_watch(conn, GObject.IO_IN, on_data, [''])
  39. GObject.idle_add(on_loop)
  40. def on_data(conn, _, leftovers, *args):
  41. global log
  42. '''Asynchronous connection handler. Pushes data from socket
  43. into command queue linewise'''
  44. try:
  45. while True:
  46. try:
  47. leftovers.append(conn.recv(4096).decode(errors='replace'))
  48. if len(leftovers[-1]) == 0:
  49. log.info("Socket was closed")
  50. # FIXME try to reconnect
  51. conn.close()
  52. Gtk.main_quit()
  53. return False
  54. except UnicodeDecodeError as e:
  55. continue
  56. except:
  57. pass
  58. data = "".join(leftovers)
  59. del leftovers[:]
  60. lines = data.split('\n')
  61. for line in lines[:-1]:
  62. log.debug("got line: %r", line)
  63. line = line.strip()
  64. command_queue.put((line, conn))
  65. if lines[-1] != '':
  66. log.debug("remaining %r", lines[-1])
  67. leftovers.append(lines[-1])
  68. return True
  69. def on_loop():
  70. global command_queue
  71. '''Command handler. Processes commands in the command queue whenever
  72. nothing else is happening (registered as GObject idle callback)'''
  73. if command_queue.empty():
  74. return True
  75. line, requestor = command_queue.get()
  76. words = line.split()
  77. if len(words) < 1:
  78. return True
  79. signal = words[0]
  80. args = words[1:]
  81. log.info('received signal %s, dispatching', signal)
  82. if signal not in signal_handlers:
  83. return True
  84. for handler in signal_handlers[signal]:
  85. cb = handler['cb']
  86. if 'one' in handler and handler['one']:
  87. log.debug('removing one-time handler')
  88. del signal_handlers[signal]
  89. cb(*args)
  90. return True
  91. def send(command, *args):
  92. global conn, log
  93. if len(args) > 0:
  94. command += ' '+(' '.join(args))
  95. command += '\n'
  96. conn.send(command.encode('ascii'))
  97. def on(signal, cb):
  98. if signal not in signal_handlers:
  99. signal_handlers[signal] = []
  100. signal_handlers[signal].append({'cb': cb})
  101. def one(signal, cb):
  102. if signal not in signal_handlers:
  103. signal_handlers[signal] = []
  104. signal_handlers[signal].append({'cb': cb, 'one': True})