You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

113 lines
2.6KB

  1. import importlib
  2. import threading
  3. import time
  4. import traceback
  5. import json
  6. import logging
  7. log = logging.getLogger('werkzeug')
  8. log.setLevel(logging.ERROR)
  9. from flask import Flask
  10. from flask_cors import CORS
  11. build_folder = 'web_interface/build'
  12. app = Flask(__name__, template_folder=build_folder, static_folder=build_folder, static_url_path='')
  13. CORS(app)
  14. from munch import Munch
  15. from watchdog.observers import Observer
  16. from watchdog.events import PatternMatchingEventHandler
  17. from mosfet import bot
  18. global_state = Munch()
  19. g = global_state
  20. g.connection = False
  21. g.name = None
  22. g.mcdata = False
  23. g.pos = False
  24. g.dimension = None
  25. g.item_lock = False
  26. g.inv = {}
  27. g.objects = {}
  28. g.mobs = {}
  29. g.players = {}
  30. g.player_names = {}
  31. g.window = None
  32. g.job = None
  33. g.correction_count = 0
  34. g.holding = 0
  35. g.afk = False
  36. g.health = 20
  37. g.food = 20
  38. g.sand_origin = None
  39. @app.route('/api/global')
  40. def api_global():
  41. data = json.dumps(g, default=lambda o: str(o), indent=4)
  42. response = app.response_class(
  43. response=data,
  44. status=200,
  45. mimetype='application/json'
  46. )
  47. return response
  48. @app.route('/')
  49. def root():
  50. return app.send_static_file('index.html')
  51. reload_timeout = time.time()
  52. def main():
  53. def reload_bot(event):
  54. global reload_timeout
  55. if time.time() - reload_timeout > 2.0:
  56. reload_timeout = time.time()
  57. print('Reloading...')
  58. g.running = False
  59. event_handler = PatternMatchingEventHandler(patterns=['*.py'], ignore_patterns=['./main.py'])
  60. event_handler.on_any_event = reload_bot
  61. observer = Observer()
  62. observer.schedule(event_handler, 'mosfet', recursive=True)
  63. observer.start()
  64. try:
  65. while True:
  66. try:
  67. g.running = True
  68. bot.bot(global_state)
  69. importlib.reload(bot)
  70. except BaseException as e:
  71. g.running = True
  72. traceback.print_exc()
  73. print('Locking...')
  74. while g.running:
  75. time.sleep(1)
  76. importlib.reload(bot)
  77. except KeyboardInterrupt:
  78. observer.stop()
  79. observer.join()
  80. def run_api():
  81. host = '0.0.0.0'
  82. port = 3300
  83. while True:
  84. print('Trying to run web interface on port:', port)
  85. print('If it works, go to http://localhost:' + str(port))
  86. try:
  87. app.run(host=host, port=port)
  88. except OSError:
  89. print()
  90. print('Error: Port already taken.')
  91. port += 1
  92. if __name__ == '__main__':
  93. threading.Thread(target=run_api).start()
  94. time.sleep(1)
  95. main()