1
0

app.py 17 KB

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