app.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. from flask import Flask, request, jsonify, render_template, send_from_directory
  2. import atexit
  3. import os
  4. import logging
  5. from datetime import datetime
  6. from .modules.connection import connection_manager
  7. from dune_weaver_flask.modules.core import pattern_manager
  8. from dune_weaver_flask.modules.core import playlist_manager
  9. from .modules.update import update_manager
  10. from dune_weaver_flask.modules.core.state import state
  11. from dune_weaver_flask.modules import mqtt
  12. # Configure logging
  13. logging.basicConfig(
  14. level=logging.INFO,
  15. format='%(asctime)s - %(name)s:%(lineno)d - %(levelname)s - %(message)s',
  16. handlers=[
  17. logging.StreamHandler(),
  18. # disable file logging for now, to not gobble up resources
  19. # logging.FileHandler('dune_weaver.log')
  20. ]
  21. )
  22. logger = logging.getLogger(__name__)
  23. app = Flask(__name__)
  24. # Flask API Endpoints
  25. @app.route('/')
  26. def index():
  27. return render_template('index.html')
  28. @app.route('/list_serial_ports', methods=['GET'])
  29. def list_ports():
  30. logger.debug("Listing available serial ports")
  31. return jsonify(connection_manager.list_serial_ports())
  32. @app.route('/connect', methods=['POST'])
  33. def connect():
  34. port = request.json.get('port')
  35. if not port:
  36. state.conn = WebSocketConnection('ws://fluidnc.local:81')
  37. logger.info(f'Successfully connected to websocket ws://fluidnc.local:81')
  38. return jsonify({'success': True})
  39. try:
  40. state.conn = SerialConnection(port)
  41. logger.info(f'Successfully connected to serial port {port}')
  42. return jsonify({'success': True})
  43. except Exception as e:
  44. logger.error(f'Failed to connect to serial port {port}: {str(e)}')
  45. return jsonify({'error': str(e)}), 500
  46. @app.route('/disconnect', methods=['POST'])
  47. def disconnect():
  48. try:
  49. connection_manager.disconnect()
  50. logger.info('Successfully disconnected from serial port')
  51. return jsonify({'success': True})
  52. except Exception as e:
  53. logger.error(f'Failed to disconnect serial: {str(e)}')
  54. return jsonify({'error': str(e)}), 500
  55. @app.route('/restart_connection', methods=['POST'])
  56. def restart():
  57. port = request.json.get('port')
  58. if not port:
  59. logger.warning("Restart serial request received without port")
  60. return jsonify({'error': 'No port provided'}), 400
  61. try:
  62. logger.info(f"Restarting serial connection on port {port}")
  63. connection_manager.restart_connection(port)
  64. return jsonify({'success': True})
  65. except Exception as e:
  66. logger.error(f"Failed to restart serial on port {port}: {str(e)}")
  67. return jsonify({'error': str(e)}), 500
  68. @app.route('/list_theta_rho_files', methods=['GET'])
  69. def list_theta_rho_files():
  70. logger.debug("Listing theta-rho files")
  71. files = pattern_manager.list_theta_rho_files()
  72. return jsonify(sorted(files))
  73. @app.route('/upload_theta_rho', methods=['POST'])
  74. def upload_theta_rho():
  75. custom_patterns_dir = os.path.join(pattern_manager.THETA_RHO_DIR, 'custom_patterns')
  76. os.makedirs(custom_patterns_dir, exist_ok=True)
  77. logger.debug(f'Ensuring custom patterns directory exists: {custom_patterns_dir}')
  78. file = request.files['file']
  79. if file:
  80. file_path = os.path.join(custom_patterns_dir, file.filename)
  81. file.save(file_path)
  82. logger.info(f'Successfully uploaded theta-rho file: {file.filename}')
  83. return jsonify({'success': True})
  84. logger.warning('Upload theta-rho request received without file')
  85. return jsonify({'success': False})
  86. @app.route('/run_theta_rho', methods=['POST'])
  87. def run_theta_rho():
  88. file_name = request.json.get('file_name')
  89. pre_execution = request.json.get('pre_execution')
  90. if not file_name:
  91. logger.warning('Run theta-rho request received without file name')
  92. return jsonify({'error': 'No file name provided'}), 400
  93. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_name)
  94. if not os.path.exists(file_path):
  95. logger.error(f'Theta-rho file not found: {file_path}')
  96. return jsonify({'error': 'File not found'}), 404
  97. try:
  98. files_to_run = [file_path]
  99. logger.info(f'Running theta-rho file: {file_name} with pre_execution={pre_execution}')
  100. pattern_manager.run_theta_rho_files(files_to_run, clear_pattern=pre_execution)
  101. return jsonify({'success': True})
  102. except Exception as e:
  103. logger.error(f'Failed to run theta-rho file {file_name}: {str(e)}')
  104. return jsonify({'error': str(e)}), 500
  105. @app.route('/stop_execution', methods=['POST'])
  106. def stop_execution():
  107. pattern_manager.stop_actions()
  108. return jsonify({'success': True})
  109. @app.route('/send_home', methods=['POST'])
  110. def send_home():
  111. try:
  112. connection_manager.home()
  113. return jsonify({'success': True})
  114. except Exception as e:
  115. logger.error(f"Failed to send home command: {str(e)}")
  116. return jsonify({'error': str(e)}), 500
  117. @app.route('/run_theta_rho_file/<file_name>', methods=['POST'])
  118. def run_specific_theta_rho_file(file_name):
  119. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_name)
  120. if not os.path.exists(file_path):
  121. return jsonify({'error': 'File not found'}), 404
  122. pattern_manager.run_theta_rho_file(file_path)
  123. return jsonify({'success': True})
  124. @app.route('/delete_theta_rho_file', methods=['POST'])
  125. def delete_theta_rho_file():
  126. file_name = request.json.get('file_name')
  127. if not file_name:
  128. logger.warning("Delete theta-rho file request received without filename")
  129. return jsonify({"success": False, "error": "No file name provided"}), 400
  130. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_name)
  131. if not os.path.exists(file_path):
  132. logger.error(f"Attempted to delete non-existent file: {file_path}")
  133. return jsonify({"success": False, "error": "File not found"}), 404
  134. try:
  135. os.remove(file_path)
  136. logger.info(f"Successfully deleted theta-rho file: {file_name}")
  137. return jsonify({"success": True})
  138. except Exception as e:
  139. logger.error(f"Failed to delete theta-rho file {file_name}: {str(e)}")
  140. return jsonify({"success": False, "error": str(e)}), 500
  141. @app.route('/move_to_center', methods=['POST'])
  142. def move_to_center():
  143. global current_theta
  144. try:
  145. if not state.conn.is_connected():
  146. logger.warning("Attempted to move to center without serial connection")
  147. return jsonify({"success": False, "error": "Serial connection not established"}), 400
  148. logger.info("Moving device to center position")
  149. pattern_manager.reset_theta()
  150. pattern_manager.move_polar(0, 0)
  151. return jsonify({"success": True})
  152. except Exception as e:
  153. logger.error(f"Failed to move to center: {str(e)}")
  154. return jsonify({"success": False, "error": str(e)}), 500
  155. @app.route('/move_to_perimeter', methods=['POST'])
  156. def move_to_perimeter():
  157. global current_theta
  158. try:
  159. if not state.conn.is_connected():
  160. logger.warning("Attempted to move to perimeter without serial connection")
  161. return jsonify({"success": False, "error": "Serial connection not established"}), 400
  162. pattern_manager.reset_theta()
  163. pattern_manager.move_polar(0,1)
  164. return jsonify({"success": True})
  165. except Exception as e:
  166. logger.error(f"Failed to move to perimeter: {str(e)}")
  167. return jsonify({"success": False, "error": str(e)}), 500
  168. @app.route('/preview_thr', methods=['POST'])
  169. def preview_thr():
  170. file_name = request.json.get('file_name')
  171. if not file_name:
  172. logger.warning("Preview theta-rho request received without filename")
  173. return jsonify({'error': 'No file name provided'}), 400
  174. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_name)
  175. if not os.path.exists(file_path):
  176. logger.error(f"Attempted to preview non-existent file: {file_path}")
  177. return jsonify({'error': 'File not found'}), 404
  178. try:
  179. coordinates = pattern_manager.parse_theta_rho_file(file_path)
  180. return jsonify({'success': True, 'coordinates': coordinates})
  181. except Exception as e:
  182. logger.error(f"Failed to generate preview for {file_name}: {str(e)}")
  183. return jsonify({'error': str(e)}), 500
  184. @app.route('/send_coordinate', methods=['POST'])
  185. def send_coordinate():
  186. if not state.conn.is_connected():
  187. logger.warning("Attempted to send coordinate without serial connection")
  188. return jsonify({"success": False, "error": "Serial connection not established"}), 400
  189. try:
  190. data = request.json
  191. theta = data.get('theta')
  192. rho = data.get('rho')
  193. if theta is None or rho is None:
  194. logger.warning("Send coordinate request missing theta or rho values")
  195. return jsonify({"success": False, "error": "Theta and Rho are required"}), 400
  196. logger.debug(f"Sending coordinate: theta={theta}, rho={rho}")
  197. pattern_manager.move_polar(theta, rho)
  198. return jsonify({"success": True})
  199. except Exception as e:
  200. logger.error(f"Failed to send coordinate: {str(e)}")
  201. return jsonify({"success": False, "error": str(e)}), 500
  202. @app.route('/download/<filename>', methods=['GET'])
  203. def download_file(filename):
  204. return send_from_directory(pattern_manager.THETA_RHO_DIR, filename)
  205. @app.route('/serial_status', methods=['GET'])
  206. def serial_status():
  207. connected = state.conn.is_connected()
  208. port = state.port
  209. logger.debug(f"Serial status check - connected: {connected}, port: {port}")
  210. return jsonify({
  211. 'connected': connected,
  212. 'port': port
  213. })
  214. @app.route('/pause_execution', methods=['POST'])
  215. def pause_execution():
  216. if pattern_manager.pause_execution():
  217. return jsonify({'success': True, 'message': 'Execution paused'})
  218. @app.route('/status', methods=['GET'])
  219. def get_status():
  220. return jsonify(pattern_manager.get_status())
  221. @app.route('/resume_execution', methods=['POST'])
  222. def resume_execution():
  223. if pattern_manager.resume_execution():
  224. return jsonify({'success': True, 'message': 'Execution resumed'})
  225. # Playlist endpoints
  226. @app.route("/list_all_playlists", methods=["GET"])
  227. def list_all_playlists():
  228. playlist_names = playlist_manager.list_all_playlists()
  229. return jsonify(playlist_names)
  230. @app.route("/get_playlist", methods=["GET"])
  231. def get_playlist():
  232. playlist_name = request.args.get("name", "")
  233. if not playlist_name:
  234. return jsonify({"error": "Missing playlist 'name' parameter"}), 400
  235. playlist = playlist_manager.get_playlist(playlist_name)
  236. if not playlist:
  237. return jsonify({"error": f"Playlist '{playlist_name}' not found"}), 404
  238. return jsonify(playlist)
  239. @app.route("/create_playlist", methods=["POST"])
  240. def create_playlist():
  241. data = request.get_json()
  242. if not data or "name" not in data or "files" not in data:
  243. return jsonify({"success": False, "error": "Playlist 'name' and 'files' are required"}), 400
  244. success = playlist_manager.create_playlist(data["name"], data["files"])
  245. return jsonify({
  246. "success": success,
  247. "message": f"Playlist '{data['name']}' created/updated"
  248. })
  249. @app.route("/modify_playlist", methods=["POST"])
  250. def modify_playlist():
  251. data = request.get_json()
  252. if not data or "name" not in data or "files" not in data:
  253. return jsonify({"success": False, "error": "Playlist 'name' and 'files' are required"}), 400
  254. success = playlist_manager.modify_playlist(data["name"], data["files"])
  255. return jsonify({"success": success, "message": f"Playlist '{data['name']}' updated"})
  256. @app.route("/delete_playlist", methods=["DELETE"])
  257. def delete_playlist():
  258. data = request.get_json()
  259. if not data or "name" not in data:
  260. return jsonify({"success": False, "error": "Missing 'name' field"}), 400
  261. success = playlist_manager.delete_playlist(data["name"])
  262. if not success:
  263. return jsonify({"success": False, "error": f"Playlist '{data['name']}' not found"}), 404
  264. return jsonify({
  265. "success": True,
  266. "message": f"Playlist '{data['name']}' deleted"
  267. })
  268. @app.route('/add_to_playlist', methods=['POST'])
  269. def add_to_playlist():
  270. data = request.json
  271. playlist_name = data.get('playlist_name')
  272. pattern = data.get('pattern')
  273. success = playlist_manager.add_to_playlist(playlist_name, pattern)
  274. if not success:
  275. return jsonify(success=False, error='Playlist not found'), 404
  276. return jsonify(success=True)
  277. @app.route("/run_playlist", methods=["POST"])
  278. def run_playlist():
  279. data = request.get_json()
  280. if not data or "playlist_name" not in data:
  281. logger.warning("Run playlist request received without playlist name")
  282. return jsonify({"success": False, "error": "Missing 'playlist_name' field"}), 400
  283. playlist_name = data["playlist_name"]
  284. pause_time = data.get("pause_time", 0)
  285. clear_pattern = data.get("clear_pattern", None)
  286. run_mode = data.get("run_mode", "single")
  287. shuffle = data.get("shuffle", False)
  288. schedule_hours = None
  289. start_time = data.get("start_time")
  290. end_time = data.get("end_time")
  291. if start_time and end_time:
  292. try:
  293. start_time_obj = datetime.strptime(start_time, "%H:%M").time()
  294. end_time_obj = datetime.strptime(end_time, "%H:%M").time()
  295. if start_time_obj >= end_time_obj:
  296. logger.error(f"Invalid schedule times: start_time {start_time} >= end_time {end_time}")
  297. return jsonify({"success": False, "error": "'start_time' must be earlier than 'end_time'"}), 400
  298. schedule_hours = (start_time_obj, end_time_obj)
  299. logger.info(f"Playlist {playlist_name} scheduled to run between {start_time} and {end_time}")
  300. except ValueError:
  301. logger.error(f"Invalid time format provided: start_time={start_time}, end_time={end_time}")
  302. return jsonify({"success": False, "error": "Invalid time format. Use HH:MM (e.g., '09:30')"}), 400
  303. logger.info(f"Starting playlist '{playlist_name}' with mode={run_mode}, shuffle={shuffle}")
  304. success, message = playlist_manager.run_playlist(
  305. playlist_name,
  306. pause_time=pause_time,
  307. clear_pattern=clear_pattern,
  308. run_mode=run_mode,
  309. shuffle=shuffle,
  310. schedule_hours=schedule_hours
  311. )
  312. if not success:
  313. logger.error(f"Failed to run playlist '{playlist_name}': {message}")
  314. return jsonify({"success": False, "error": message}), 500
  315. return jsonify({"success": True, "message": message})
  316. # Firmware endpoints
  317. @app.route('/set_speed', methods=['POST'])
  318. def set_speed():
  319. try:
  320. data = request.json
  321. new_speed = data.get('speed')
  322. if new_speed is None:
  323. logger.warning("Set speed request received without speed value")
  324. return jsonify({"success": False, "error": "Speed is required"}), 400
  325. if not isinstance(new_speed, (int, float)) or new_speed <= 0:
  326. logger.warning(f"Invalid speed value received: {new_speed}")
  327. return jsonify({"success": False, "error": "Invalid speed value"}), 400
  328. state.speed = new_speed
  329. return jsonify({"success": True, "speed": new_speed})
  330. except Exception as e:
  331. logger.error(f"Failed to set speed: {str(e)}")
  332. return jsonify({"success": False, "error": str(e)}), 500
  333. @app.route('/check_software_update', methods=['GET'])
  334. def check_updates():
  335. update_info = update_manager.check_git_updates()
  336. return jsonify(update_info)
  337. @app.route('/update_software', methods=['POST'])
  338. def update_software():
  339. logger.info("Starting software update process")
  340. success, error_message, error_log = update_manager.update_software()
  341. if success:
  342. logger.info("Software update completed successfully")
  343. return jsonify({"success": True})
  344. else:
  345. logger.error(f"Software update failed: {error_message}\nDetails: {error_log}")
  346. return jsonify({
  347. "success": False,
  348. "error": error_message,
  349. "details": error_log
  350. }), 500
  351. def on_exit():
  352. """Function to execute on application shutdown."""
  353. logger.info("Shutting down gracefully, please wait for executiong to complete")
  354. pattern_manager.stop_actions()
  355. state.save()
  356. mqtt.cleanup_mqtt()
  357. def entrypoint():
  358. logger.info("Starting Dune Weaver application...")
  359. # Register the on_exit function
  360. atexit.register(on_exit)
  361. # Auto-connect to serial
  362. try:
  363. connection_manager.connect_device()
  364. except Exception as e:
  365. logger.warning(f"Failed to auto-connect to serial port: {str(e)}")
  366. try:
  367. mqtt_handler = mqtt.init_mqtt()
  368. except Exception as e:
  369. logger.warning(f"Failed to initialize MQTT: {str(e)}")
  370. try:
  371. logger.info("Starting Flask server on port 8080...")
  372. app.run(debug=False, host='0.0.0.0', port=8080)
  373. except KeyboardInterrupt:
  374. logger.info("Keyboard interrupt received. Shutting down.")
  375. except Exception as e:
  376. logger.critical(f"Unexpected error during server startup: {str(e)}")
  377. finally:
  378. on_exit()