6
0

WebServer.py 2.0 KB

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