ws.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. '''This file is part of AToMPM - A Tool for Multi-Paradigm Modelling
  2. Copyright 2011 by the AToMPM team and licensed under the LGPL
  3. See COPYING.lesser and README.md in the root of this project for full details'''
  4. import threading, json, logging, sys
  5. import socketio
  6. '''
  7. a friendly wrapper around a socketio client
  8. _opened true when the socket is first opened
  9. _chlogh a reference to an object that implements onchangelog(), this
  10. method is called upon reception of changelogs from the asworker
  11. we're subscribed to
  12. subscribed describes the current state of our subscription to our asworker
  13. None: don't know yet
  14. True: subscribed
  15. False: subscription failed
  16. _ws the python-websocket '''
  17. class WebSocket :
  18. def __init__(self, _aswid, chlogh=None) :
  19. assert chlogh is None or 'onchangelog' in dir(chlogh)
  20. self._opened = False
  21. self._chlogh = chlogh
  22. self.subscribed = None
  23. self._aswid = _aswid
  24. self.socketIO = None
  25. thr = threading.Thread(target = self._start_ws)
  26. thr.start()
  27. def _start_ws(self):
  28. try:
  29. self.socketIO = socketio.Client(logger=False, engineio_logger=False)
  30. self.socketIO.on('connect', self._onopen)
  31. self.socketIO.on('message', self._onmessage)
  32. self.socketIO.connect('http://127.0.0.1:8124')
  33. self.socketIO.sleep(1)
  34. data = {'method': 'POST', 'url': '/changeListener?wid='+self._aswid}
  35. self.socketIO.emit('message', data)
  36. self.socketIO.wait()
  37. except Exception as e:
  38. raise e
  39. '''
  40. mark socket connection as opened '''
  41. def _onopen(self) :
  42. self._opened = True
  43. '''
  44. close the socket '''
  45. def close(self) :
  46. self.socketIO.close()
  47. '''
  48. parse and handle incoming message '''
  49. def _onmessage(self, data) :
  50. logging.debug('## data recvd '+ str(data))
  51. if 'statusCode' in data and data['statusCode'] is not None :
  52. #on POST /changeListener response
  53. if data['statusCode'] == 201 :
  54. self.subscribed = True
  55. else :
  56. self.subscribed = False
  57. elif self._chlogh and self.subscribed :
  58. self._chlogh.onchangelog(data['data'])