app.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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.send_command("HOME", ack="HOMED")
  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. try:
  141. if not serial_manager.is_connected():
  142. logger.warning("Attempted to move to center without serial connection")
  143. return jsonify({"success": False, "error": "Serial connection not established"}), 400
  144. logger.info("Moving device to center position")
  145. coordinates = [(0, 0)]
  146. serial_manager.send_coordinate_batch(coordinates)
  147. return jsonify({"success": True})
  148. except Exception as e:
  149. logger.error(f"Failed to move to center: {str(e)}")
  150. return jsonify({"success": False, "error": str(e)}), 500
  151. @app.route('/move_to_perimeter', methods=['POST'])
  152. def move_to_perimeter():
  153. try:
  154. if not serial_manager.is_connected():
  155. logger.warning("Attempted to move to perimeter without serial connection")
  156. return jsonify({"success": False, "error": "Serial connection not established"}), 400
  157. MAX_RHO = 1
  158. coordinates = [(0, MAX_RHO)]
  159. serial_manager.send_coordinate_batch(coordinates)
  160. return jsonify({"success": True})
  161. except Exception as e:
  162. logger.error(f"Failed to move to perimeter: {str(e)}")
  163. return jsonify({"success": False, "error": str(e)}), 500
  164. @app.route('/preview_thr', methods=['POST'])
  165. def preview_thr():
  166. file_name = request.json.get('file_name')
  167. if not file_name:
  168. logger.warning("Preview theta-rho request received without filename")
  169. return jsonify({'error': 'No file name provided'}), 400
  170. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_name)
  171. if not os.path.exists(file_path):
  172. logger.error(f"Attempted to preview non-existent file: {file_path}")
  173. return jsonify({'error': 'File not found'}), 404
  174. try:
  175. coordinates = pattern_manager.parse_theta_rho_file(file_path)
  176. return jsonify({'success': True, 'coordinates': coordinates})
  177. except Exception as e:
  178. logger.error(f"Failed to generate preview for {file_name}: {str(e)}")
  179. return jsonify({'error': str(e)}), 500
  180. @app.route('/send_coordinate', methods=['POST'])
  181. def send_coordinate():
  182. if not serial_manager.is_connected():
  183. logger.warning("Attempted to send coordinate without serial connection")
  184. return jsonify({"success": False, "error": "Serial connection not established"}), 400
  185. try:
  186. data = request.json
  187. theta = data.get('theta')
  188. rho = data.get('rho')
  189. if theta is None or rho is None:
  190. logger.warning("Send coordinate request missing theta or rho values")
  191. return jsonify({"success": False, "error": "Theta and Rho are required"}), 400
  192. logger.debug(f"Sending coordinate: theta={theta}, rho={rho}")
  193. serial_manager.send_coordinate_batch([(theta, rho)])
  194. return jsonify({"success": True})
  195. except Exception as e:
  196. logger.error(f"Failed to send coordinate: {str(e)}")
  197. return jsonify({"success": False, "error": str(e)}), 500
  198. @app.route('/download/<filename>', methods=['GET'])
  199. def download_file(filename):
  200. return send_from_directory(pattern_manager.THETA_RHO_DIR, filename)
  201. @app.route('/serial_status', methods=['GET'])
  202. def serial_status():
  203. connected = serial_manager.is_connected()
  204. port = serial_manager.get_port()
  205. logger.debug(f"Serial status check - connected: {connected}, port: {port}")
  206. return jsonify({
  207. 'connected': connected,
  208. 'port': port
  209. })
  210. @app.route('/pause_execution', methods=['POST'])
  211. def pause_execution():
  212. logger.info("Pausing pattern execution")
  213. pattern_manager.pause_requested = True
  214. return jsonify({'success': True, 'message': 'Execution paused'})
  215. @app.route('/status', methods=['GET'])
  216. def get_status():
  217. return jsonify(pattern_manager.get_status())
  218. @app.route('/resume_execution', methods=['POST'])
  219. def resume_execution():
  220. logger.info("Resuming pattern execution")
  221. with pattern_manager.pause_condition:
  222. pattern_manager.pause_requested = False
  223. pattern_manager.pause_condition.notify_all()
  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. if not serial_manager.is_connected():
  320. logger.warning("Attempted to set speed without serial connection")
  321. return jsonify({"success": False, "error": "Serial connection not established"}), 400
  322. try:
  323. data = request.json
  324. speed = data.get('speed')
  325. if speed is None:
  326. logger.warning("Set speed request received without speed value")
  327. return jsonify({"success": False, "error": "Speed is required"}), 400
  328. if not isinstance(speed, (int, float)) or speed <= 0:
  329. logger.warning(f"Invalid speed value received: {speed}")
  330. return jsonify({"success": False, "error": "Invalid speed value"}), 400
  331. serial_manager.send_command(f"SET_SPEED {speed}", ack="SPEED_SET")
  332. return jsonify({"success": True, "speed": speed})
  333. except Exception as e:
  334. logger.error(f"Failed to set speed: {str(e)}")
  335. return jsonify({"success": False, "error": str(e)}), 500
  336. @app.route('/get_firmware_info', methods=['GET', 'POST'])
  337. def get_firmware_info():
  338. if not serial_manager.is_connected():
  339. logger.warning("Attempted to get firmware info without serial connection")
  340. return jsonify({"success": False, "error": "Arduino not connected or serial port not open"}), 400
  341. try:
  342. if request.method == "POST":
  343. motor_type = request.json.get("motorType", None)
  344. success, result = firmware_manager.get_firmware_info(motor_type)
  345. else:
  346. success, result = firmware_manager.get_firmware_info()
  347. if not success:
  348. logger.error(f"Failed to get firmware info: {result}")
  349. return jsonify({"success": False, "error": result}), 500
  350. return jsonify({"success": True, **result})
  351. except Exception as e:
  352. logger.error(f"Unexpected error while getting firmware info: {str(e)}")
  353. return jsonify({"success": False, "error": str(e)}), 500
  354. @app.route('/flash_firmware', methods=['POST'])
  355. def flash_firmware():
  356. try:
  357. motor_type = request.json.get("motorType", None)
  358. logger.info(f"Starting firmware flash for motor type: {motor_type}")
  359. success, message = firmware_manager.flash_firmware(motor_type)
  360. if not success:
  361. logger.error(f"Firmware flash failed: {message}")
  362. return jsonify({"success": False, "error": message}), 500
  363. logger.info("Firmware flash completed successfully")
  364. return jsonify({"success": True, "message": message})
  365. except Exception as e:
  366. logger.critical(f"Unexpected error during firmware flash: {str(e)}")
  367. return jsonify({"success": False, "error": str(e)}), 500
  368. @app.route('/check_software_update', methods=['GET'])
  369. def check_updates():
  370. update_info = firmware_manager.check_git_updates()
  371. return jsonify(update_info)
  372. @app.route('/update_software', methods=['POST'])
  373. def update_software():
  374. logger.info("Starting software update process")
  375. success, error_message, error_log = firmware_manager.update_software()
  376. if success:
  377. logger.info("Software update completed successfully")
  378. return jsonify({"success": True})
  379. else:
  380. logger.error(f"Software update failed: {error_message}\nDetails: {error_log}")
  381. return jsonify({
  382. "success": False,
  383. "error": error_message,
  384. "details": error_log
  385. }), 500
  386. def on_exit():
  387. """Function to execute on application shutdown."""
  388. pattern_manager.stop_actions()
  389. # Register the on_exit function
  390. atexit.register(on_exit)
  391. def entrypoint():
  392. logger.info("Starting Dune Weaver application...")
  393. # Auto-connect to serial
  394. try:
  395. serial_manager.connect_to_serial()
  396. except Exception as e:
  397. logger.warning(f"Failed to auto-connect to serial port: {str(e)}")
  398. try:
  399. logger.info("Starting Flask server on port 8080...")
  400. app.run(debug=False, host='0.0.0.0', port=8080)
  401. except KeyboardInterrupt:
  402. logger.info("Keyboard interrupt received. Shutting down.")
  403. except Exception as e:
  404. logger.critical(f"Unexpected error during server startup: {str(e)}")
  405. finally:
  406. on_exit()