app.py 18 KB

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