6
0

WebServer.py 2.3 KB

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