aboutsummaryrefslogtreecommitdiff
path: root/voctogui/lib/connection.py
blob: 6bece3d13d7f3cdf7e002a5cba1deef6d4a86594 (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 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. sys.exit(1)
  52. except UnicodeDecodeError as e:
  53. continue
  54. except:
  55. pass
  56. data = "".join(leftovers)
  57. del leftovers[:]
  58. lines = data.split('\n')
  59. for line in lines[:-1]:
  60. log.debug("got line: %r", line)
  61. line = line.strip()
  62. command_queue.put((line, conn))
  63. if lines[-1] != '':
  64. log.debug("remaining %r", lines[-1])
  65. leftovers.append(lines[-1])
  66. return True
  67. def on_loop():
  68. global command_queue
  69. '''Command handler. Processes commands in the command queue whenever
  70. nothing else is happening (registered as GObject idle callback)'''
  71. if command_queue.empty():
  72. return True
  73. line, requestor = command_queue.get()
  74. words = line.split()
  75. if len(words) < 1:
  76. return True
  77. signal = words[0]
  78. args = words[1:]
  79. log.info('received signal %s, dispatching', signal)
  80. if signal not in signal_handlers:
  81. return True
  82. for handler in signal_handlers[signal]:
  83. cb = handler['cb']
  84. if 'one' in handler and handler['one']:
  85. log.debug('removing one-time handler')
  86. del signal_handlers[signal]
  87. cb(*args)
  88. return True
  89. def send(command, *args):
  90. global conn, log
  91. if len(args) > 0:
  92. command += ' '+(' '.join(args))
  93. command += '\n'
  94. conn.send(command.encode('ascii'))
  95. def on(signal, cb):
  96. if signal not in signal_handlers:
  97. signal_handlers[signal] = []
  98. signal_handlers[signal].append({'cb': cb})
  99. def one(signal, cb):
  100. if signal not in signal_handlers:
  101. signal_handlers[signal] = []
  102. signal_handlers[signal].append({'cb': cb, 'one': True})