app.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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 = connection_manager.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 = connection_manager.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. state.conn.close()
  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 connection on port {port}")
  63. connection_manager.restart_connection()
  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. if not (state.conn.is_connected() if state.conn else False):
  99. logger.warning("Attempted to run a pattern without a connection")
  100. return jsonify({"success": False, "error": "Connection not established"}), 400
  101. files_to_run = [file_path]
  102. logger.info(f'Running theta-rho file: {file_name} with pre_execution={pre_execution}')
  103. pattern_manager.run_theta_rho_files(files_to_run, clear_pattern=pre_execution)
  104. return jsonify({'success': True})
  105. except Exception as e:
  106. logger.error(f'Failed to run theta-rho file {file_name}: {str(e)}')
  107. return jsonify({'error': str(e)}), 500
  108. @app.route('/stop_execution', methods=['POST'])
  109. def stop_execution():
  110. if not (state.conn.is_connected() if state.conn else False):
  111. logger.warning("Attempted to stop without a connection")
  112. return jsonify({"success": False, "error": "Connection not established"}), 400
  113. pattern_manager.stop_actions()
  114. return jsonify({'success': True})
  115. @app.route('/send_home', methods=['POST'])
  116. def send_home():
  117. try:
  118. if not (state.conn.is_connected() if state.conn else False):
  119. logger.warning("Attempted to move to home without a connection")
  120. return jsonify({"success": False, "error": "Connection not established"}), 400
  121. connection_manager.home()
  122. return jsonify({'success': True})
  123. except Exception as e:
  124. logger.error(f"Failed to send home command: {str(e)}")
  125. return jsonify({'error': str(e)}), 500
  126. @app.route('/run_theta_rho_file/<file_name>', methods=['POST'])
  127. def run_specific_theta_rho_file(file_name):
  128. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_name)
  129. if not os.path.exists(file_path):
  130. return jsonify({'error': 'File not found'}), 404
  131. if not (state.conn.is_connected() if state.conn else False):
  132. logger.warning("Attempted to run a pattern without a connection")
  133. return jsonify({"success": False, "error": "Connection not established"}), 400
  134. pattern_manager.run_theta_rho_file(file_path)
  135. return jsonify({'success': True})
  136. @app.route('/delete_theta_rho_file', methods=['POST'])
  137. def delete_theta_rho_file():
  138. file_name = request.json.get('file_name')
  139. if not file_name:
  140. logger.warning("Delete theta-rho file request received without filename")
  141. return jsonify({"success": False, "error": "No file name provided"}), 400
  142. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_name)
  143. if not os.path.exists(file_path):
  144. logger.error(f"Attempted to delete non-existent file: {file_path}")
  145. return jsonify({"success": False, "error": "File not found"}), 404
  146. try:
  147. os.remove(file_path)
  148. logger.info(f"Successfully deleted theta-rho file: {file_name}")
  149. return jsonify({"success": True})
  150. except Exception as e:
  151. logger.error(f"Failed to delete theta-rho file {file_name}: {str(e)}")
  152. return jsonify({"success": False, "error": str(e)}), 500
  153. @app.route('/move_to_center', methods=['POST'])
  154. def move_to_center():
  155. global current_theta
  156. try:
  157. if not (state.conn.is_connected() if state.conn else False):
  158. logger.warning("Attempted to move to center without a connection")
  159. return jsonify({"success": False, "error": "Connection not established"}), 400
  160. logger.info("Moving device to center position")
  161. pattern_manager.reset_theta()
  162. pattern_manager.move_polar(0, 0)
  163. return jsonify({"success": True})
  164. except Exception as e:
  165. logger.error(f"Failed to move to center: {str(e)}")
  166. return jsonify({"success": False, "error": str(e)}), 500
  167. @app.route('/move_to_perimeter', methods=['POST'])
  168. def move_to_perimeter():
  169. global current_theta
  170. try:
  171. if not (state.conn.is_connected() if state.conn else False):
  172. logger.warning("Attempted to move to perimeter without a connection")
  173. return jsonify({"success": False, "error": "Connection not established"}), 400
  174. pattern_manager.reset_theta()
  175. pattern_manager.move_polar(0,1)
  176. return jsonify({"success": True})
  177. except Exception as e:
  178. logger.error(f"Failed to move to perimeter: {str(e)}")
  179. return jsonify({"success": False, "error": str(e)}), 500
  180. @app.route('/preview_thr', methods=['POST'])
  181. def preview_thr():
  182. file_name = request.json.get('file_name')
  183. if not file_name:
  184. logger.warning("Preview theta-rho request received without filename")
  185. return jsonify({'error': 'No file name provided'}), 400
  186. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_name)
  187. if not os.path.exists(file_path):
  188. logger.error(f"Attempted to preview non-existent file: {file_path}")
  189. return jsonify({'error': 'File not found'}), 404
  190. try:
  191. coordinates = pattern_manager.parse_theta_rho_file(file_path)
  192. return jsonify({'success': True, 'coordinates': coordinates})
  193. except Exception as e:
  194. logger.error(f"Failed to generate preview for {file_name}: {str(e)}")
  195. return jsonify({'error': str(e)}), 500
  196. @app.route('/send_coordinate', methods=['POST'])
  197. def send_coordinate():
  198. if not (state.conn.is_connected() if state.conn else False):
  199. logger.warning("Attempted to send coordinate without a connection")
  200. return jsonify({"success": False, "error": "connection not established"}), 400
  201. try:
  202. data = request.json
  203. theta = data.get('theta')
  204. rho = data.get('rho')
  205. if theta is None or rho is None:
  206. logger.warning("Send coordinate request missing theta or rho values")
  207. return jsonify({"success": False, "error": "Theta and Rho are required"}), 400
  208. logger.debug(f"Sending coordinate: theta={theta}, rho={rho}")
  209. pattern_manager.move_polar(theta, rho)
  210. return jsonify({"success": True})
  211. except Exception as e:
  212. logger.error(f"Failed to send coordinate: {str(e)}")
  213. return jsonify({"success": False, "error": str(e)}), 500
  214. @app.route('/download/<filename>', methods=['GET'])
  215. def download_file(filename):
  216. return send_from_directory(pattern_manager.THETA_RHO_DIR, filename)
  217. @app.route('/serial_status', methods=['GET'])
  218. def serial_status():
  219. connected = state.conn.is_connected() if state.conn else False
  220. port = state.port
  221. logger.debug(f"Serial status check - connected: {connected}, port: {port}")
  222. return jsonify({
  223. 'connected': connected,
  224. 'port': port
  225. })
  226. @app.route('/pause_execution', methods=['POST'])
  227. def pause_execution():
  228. if pattern_manager.pause_execution():
  229. return jsonify({'success': True, 'message': 'Execution paused'})
  230. @app.route('/status', methods=['GET'])
  231. def get_status():
  232. return jsonify(pattern_manager.get_status())
  233. @app.route('/resume_execution', methods=['POST'])
  234. def resume_execution():
  235. if pattern_manager.resume_execution():
  236. return jsonify({'success': True, 'message': 'Execution resumed'})
  237. # Playlist endpoints
  238. @app.route("/list_all_playlists", methods=["GET"])
  239. def list_all_playlists():
  240. playlist_names = playlist_manager.list_all_playlists()
  241. return jsonify(playlist_names)
  242. @app.route("/get_playlist", methods=["GET"])
  243. def get_playlist():
  244. playlist_name = request.args.get("name", "")
  245. if not playlist_name:
  246. return jsonify({"error": "Missing playlist 'name' parameter"}), 400
  247. playlist = playlist_manager.get_playlist(playlist_name)
  248. if not playlist:
  249. return jsonify({"error": f"Playlist '{playlist_name}' not found"}), 404
  250. return jsonify(playlist)
  251. @app.route("/create_playlist", methods=["POST"])
  252. def create_playlist():
  253. data = request.get_json()
  254. if not data or "name" not in data or "files" not in data:
  255. return jsonify({"success": False, "error": "Playlist 'name' and 'files' are required"}), 400
  256. success = playlist_manager.create_playlist(data["name"], data["files"])
  257. return jsonify({
  258. "success": success,
  259. "message": f"Playlist '{data['name']}' created/updated"
  260. })
  261. @app.route("/modify_playlist", methods=["POST"])
  262. def modify_playlist():
  263. data = request.get_json()
  264. if not data or "name" not in data or "files" not in data:
  265. return jsonify({"success": False, "error": "Playlist 'name' and 'files' are required"}), 400
  266. success = playlist_manager.modify_playlist(data["name"], data["files"])
  267. return jsonify({"success": success, "message": f"Playlist '{data['name']}' updated"})
  268. @app.route("/delete_playlist", methods=["DELETE"])
  269. def delete_playlist():
  270. data = request.get_json()
  271. if not data or "name" not in data:
  272. return jsonify({"success": False, "error": "Missing 'name' field"}), 400
  273. success = playlist_manager.delete_playlist(data["name"])
  274. if not success:
  275. return jsonify({"success": False, "error": f"Playlist '{data['name']}' not found"}), 404
  276. return jsonify({
  277. "success": True,
  278. "message": f"Playlist '{data['name']}' deleted"
  279. })
  280. @app.route('/add_to_playlist', methods=['POST'])
  281. def add_to_playlist():
  282. data = request.json
  283. playlist_name = data.get('playlist_name')
  284. pattern = data.get('pattern')
  285. success = playlist_manager.add_to_playlist(playlist_name, pattern)
  286. if not success:
  287. return jsonify(success=False, error='Playlist not found'), 404
  288. return jsonify(success=True)
  289. @app.route("/run_playlist", methods=["POST"])
  290. def run_playlist():
  291. data = request.get_json()
  292. if not data or "playlist_name" not in data:
  293. logger.warning("Run playlist request received without playlist name")
  294. return jsonify({"success": False, "error": "Missing 'playlist_name' field"}), 400
  295. if not (state.conn.is_connected() if state.conn else False):
  296. logger.warning("Attempted to run a playlist without a connection")
  297. return jsonify({"success": False, "error": "Connection not established"}), 400
  298. playlist_name = data["playlist_name"]
  299. pause_time = data.get("pause_time", 0)
  300. clear_pattern = data.get("clear_pattern", None)
  301. run_mode = data.get("run_mode", "single")
  302. shuffle = data.get("shuffle", False)
  303. schedule_hours = None
  304. start_time = data.get("start_time")
  305. end_time = data.get("end_time")
  306. if start_time and end_time:
  307. try:
  308. start_time_obj = datetime.strptime(start_time, "%H:%M").time()
  309. end_time_obj = datetime.strptime(end_time, "%H:%M").time()
  310. if start_time_obj >= end_time_obj:
  311. logger.error(f"Invalid schedule times: start_time {start_time} >= end_time {end_time}")
  312. return jsonify({"success": False, "error": "'start_time' must be earlier than 'end_time'"}), 400
  313. schedule_hours = (start_time_obj, end_time_obj)
  314. logger.info(f"Playlist {playlist_name} scheduled to run between {start_time} and {end_time}")
  315. except ValueError:
  316. logger.error(f"Invalid time format provided: start_time={start_time}, end_time={end_time}")
  317. return jsonify({"success": False, "error": "Invalid time format. Use HH:MM (e.g., '09:30')"}), 400
  318. logger.info(f"Starting playlist '{playlist_name}' with mode={run_mode}, shuffle={shuffle}")
  319. success, message = playlist_manager.run_playlist(
  320. playlist_name,
  321. pause_time=pause_time,
  322. clear_pattern=clear_pattern,
  323. run_mode=run_mode,
  324. shuffle=shuffle,
  325. schedule_hours=schedule_hours
  326. )
  327. if not success:
  328. logger.error(f"Failed to run playlist '{playlist_name}': {message}")
  329. return jsonify({"success": False, "error": message}), 500
  330. return jsonify({"success": True, "message": message})
  331. # Firmware endpoints
  332. @app.route('/set_speed', methods=['POST'])
  333. def set_speed():
  334. try:
  335. if not (state.conn.is_connected() if state.conn else False):
  336. logger.warning("Attempted to change speed without a connection")
  337. return jsonify({"success": False, "error": "Connection not established"}), 400
  338. data = request.json
  339. new_speed = data.get('speed')
  340. if new_speed is None:
  341. logger.warning("Set speed request received without speed value")
  342. return jsonify({"success": False, "error": "Speed is required"}), 400
  343. if not isinstance(new_speed, (int, float)) or new_speed <= 0:
  344. logger.warning(f"Invalid speed value received: {new_speed}")
  345. return jsonify({"success": False, "error": "Invalid speed value"}), 400
  346. state.speed = new_speed
  347. return jsonify({"success": True, "speed": new_speed})
  348. except Exception as e:
  349. logger.error(f"Failed to set speed: {str(e)}")
  350. return jsonify({"success": False, "error": str(e)}), 500
  351. @app.route('/check_software_update', methods=['GET'])
  352. def check_updates():
  353. update_info = update_manager.check_git_updates()
  354. return jsonify(update_info)
  355. @app.route('/update_software', methods=['POST'])
  356. def update_software():
  357. logger.info("Starting software update process")
  358. success, error_message, error_log = update_manager.update_software()
  359. if success:
  360. logger.info("Software update completed successfully")
  361. return jsonify({"success": True})
  362. else:
  363. logger.error(f"Software update failed: {error_message}\nDetails: {error_log}")
  364. return jsonify({
  365. "success": False,
  366. "error": error_message,
  367. "details": error_log
  368. }), 500
  369. @app.route('/set_wled_ip', methods=['POST'])
  370. def set_wled_ip():
  371. """Save the WLED IP address to state"""
  372. data = request.json
  373. wled_ip = data.get("wled_ip")
  374. # Save to state
  375. state.wled_ip = wled_ip
  376. state.save()
  377. logger.info(f"WLED IP updated: {wled_ip}")
  378. return jsonify({"success": True, "wled_ip": state.wled_ip})
  379. @app.route('/get_wled_ip', methods=['GET'])
  380. def get_wled_ip():
  381. """Retrieve the saved WLED IP address"""
  382. if not state.wled_ip:
  383. return jsonify({"success": False, "error": "No WLED IP set"}), 404
  384. return jsonify({"success": True, "wled_ip": state.wled_ip})
  385. def on_exit():
  386. """Function to execute on application shutdown."""
  387. logger.info("Shutting down gracefully, please wait for execution to complete")
  388. pattern_manager.stop_actions()
  389. state.save()
  390. mqtt.cleanup_mqtt()
  391. def entrypoint():
  392. logger.info("Starting Dune Weaver application...")
  393. # Register the on_exit function
  394. atexit.register(on_exit)
  395. # Auto-connect to serial
  396. try:
  397. connection_manager.connect_device()
  398. except Exception as e:
  399. logger.warning(f"Failed to auto-connect to serial port: {str(e)}")
  400. try:
  401. mqtt_handler = mqtt.init_mqtt()
  402. except Exception as e:
  403. logger.warning(f"Failed to initialize MQTT: {str(e)}")
  404. try:
  405. logger.info("Starting Flask server on port 8080...")
  406. app.run(debug=False, host='0.0.0.0', port=8080)
  407. except KeyboardInterrupt:
  408. logger.info("Keyboard interrupt received. Shutting down.")
  409. except Exception as e:
  410. logger.critical(f"Unexpected error during server startup: {str(e)}")
  411. finally:
  412. on_exit()