websocket.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import asyncio
  2. import websockets
  3. import threading
  4. import json
  5. class Websocket(threading.Thread):
  6. def __init__(self, add_question, handle_diapo, handle_rec, toggle, handle_video):
  7. super(Websocket, self).__init__()
  8. self.start_server = websockets.serve(self.handle_input, '127.0.0.1', 5678)
  9. self.callbacks={
  10. "add_preg": add_question,
  11. "diapo": add_question,
  12. "startrec":handle_rec,
  13. "startrectrat":handle_rec,
  14. "stoprec":handle_rec,
  15. "toggle":toggle,
  16. "video":handle_video
  17. }
  18. self.valid_data_types=["add_preg", "diapo", "startrec","startrectrat","stoprec","toggle","video"]
  19. self.loop = asyncio.get_event_loop()
  20. def run(self):
  21. asyncio.set_event_loop(self.loop)
  22. self.loop.run_until_complete(self.start_server)
  23. self.loop.run_forever()
  24. print("finitO?")
  25. @asyncio.coroutine
  26. def handle_input(self,websocket, path):
  27. while True:
  28. try:
  29. #data = await websocket.recv()
  30. data = yield from websocket.recv()
  31. try:
  32. data=json.loads(data)
  33. except Exception as e:
  34. print(e)
  35. print(data)
  36. print("No pude hacer loads")
  37. continue
  38. print(data)
  39. if not "type" in data:
  40. print("data!= type?")
  41. continue
  42. #add preg, diapo, start|stop rec, switch mode, add video
  43. if data["type"] in self.valid_data_types:
  44. print("{}".format(data))
  45. self.callbacks[data["type"]]()
  46. except websockets.exceptions.ConnectionClosed as c:
  47. print( "client dc'd")
  48. break