WebServer.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from os.path import exists
  2. import eventlet
  3. import socketio
  4. from pycs.ApplicationStatus import ApplicationStatus
  5. from pycs.frontend.FileProvider import FileProvider
  6. class WebServer:
  7. def __init__(self, app_status: ApplicationStatus):
  8. # initialize web server
  9. # TODO svg files need the correct mime type to be displayed correctly
  10. if exists('webui/index.html'):
  11. print('production build')
  12. files = FileProvider(app_status)
  13. self.__sio = socketio.Server()
  14. self.__app = socketio.WSGIApp(self.__sio, files, static_files={'/': 'webui/'})
  15. elif exists('webui/dist/index.html'):
  16. print('production build')
  17. files = FileProvider(app_status)
  18. self.__sio = socketio.Server()
  19. self.__app = socketio.WSGIApp(self.__sio, files, static_files={'/': 'webui/dist/'})
  20. else:
  21. print('development build')
  22. files = FileProvider(app_status, cors=True)
  23. self.__sio = socketio.Server(cors_allowed_origins='*')
  24. self.__app = socketio.WSGIApp(self.__sio, files)
  25. # save every change in application status and send it to the client
  26. app_status.subscribe(self.__update_application_status, immediate=True)
  27. # define events
  28. @self.__sio.event
  29. def connect(id, msg):
  30. self.__sio.emit('app_status', self.__status, to=id)
  31. @self.__sio.on('set')
  32. def set_status(id, msg):
  33. path = msg['path'].split('/')
  34. value = msg['value']
  35. obj = app_status
  36. for p in path[:-1]:
  37. obj = obj[p]
  38. obj[path[-1]] = value
  39. @self.__sio.on('add')
  40. def add_status(id, msg):
  41. path = msg['path'].split('/')
  42. value = msg['value']
  43. obj = app_status
  44. for p in path[:-1]:
  45. obj = obj[p]
  46. obj[path[-1]].append(value)
  47. # finally start web server
  48. host = app_status['settings']['frontend']['host']
  49. port = app_status['settings']['frontend']['port']
  50. eventlet.wsgi.server(eventlet.listen((host, port)), self.__app)
  51. def __update_application_status(self, status):
  52. self.__status = status
  53. self.__sio.emit('app_status', status)