app.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275
  1. from flask import Flask, request, jsonify, render_template
  2. import atexit
  3. import os
  4. import serial
  5. import time
  6. import random
  7. import threading
  8. import serial.tools.list_ports
  9. import math
  10. import json
  11. from datetime import datetime
  12. import subprocess
  13. from tqdm import tqdm
  14. app = Flask(__name__)
  15. # Configuration
  16. THETA_RHO_DIR = './patterns'
  17. IGNORE_PORTS = ['/dev/cu.debug-console', '/dev/cu.Bluetooth-Incoming-Port']
  18. CLEAR_PATTERNS = {
  19. "clear_from_in": "./patterns/clear_from_in.thr",
  20. "clear_from_out": "./patterns/clear_from_out.thr",
  21. "clear_sideway": "./patterns/clear_sideway.thr"
  22. }
  23. os.makedirs(THETA_RHO_DIR, exist_ok=True)
  24. # Serial connection (First available will be selected by default)
  25. ser = None
  26. ser_port = None # Global variable to store the serial port name
  27. stop_requested = False
  28. pause_requested = False
  29. pause_condition = threading.Condition()
  30. # Global variables to store device information
  31. arduino_table_name = None
  32. arduino_driver_type = 'Unknown'
  33. # Table status
  34. current_playing_file = None
  35. execution_progress = None
  36. firmware_version = 'Unknown'
  37. current_playing_index = None
  38. current_playlist = None
  39. is_clearing = False
  40. serial_lock = threading.Lock()
  41. PLAYLISTS_FILE = os.path.join(os.getcwd(), "playlists.json")
  42. MOTOR_TYPE_MAPPING = {
  43. "TMC2209": "./firmware/arduino_code_TMC2209/arduino_code_TMC2209.ino",
  44. "DRV8825": "./firmware/arduino_code/arduino_code.ino",
  45. "esp32": "./firmware/esp32/esp32.ino"
  46. }
  47. # Ensure the file exists and contains at least an empty JSON object
  48. if not os.path.exists(PLAYLISTS_FILE):
  49. with open(PLAYLISTS_FILE, "w") as f:
  50. json.dump({}, f, indent=2)
  51. def get_ino_firmware_details(ino_file_path):
  52. """
  53. Extract firmware details, including version and motor type, from the given .ino file.
  54. Args:
  55. ino_file_path (str): Path to the .ino file.
  56. Returns:
  57. dict: Dictionary containing firmware details such as version and motor type, or None if not found.
  58. """
  59. try:
  60. if not ino_file_path:
  61. raise ValueError("Invalid path: ino_file_path is None or empty.")
  62. firmware_details = {"version": None, "motorType": None}
  63. with open(ino_file_path, "r") as file:
  64. for line in file:
  65. # Extract firmware version
  66. if "firmwareVersion" in line:
  67. start = line.find('"') + 1
  68. end = line.rfind('"')
  69. if start != -1 and end != -1 and start < end:
  70. firmware_details["version"] = line[start:end]
  71. # Extract motor type
  72. if "motorType" in line:
  73. start = line.find('"') + 1
  74. end = line.rfind('"')
  75. if start != -1 and end != -1 and start < end:
  76. firmware_details["motorType"] = line[start:end]
  77. if not firmware_details["version"]:
  78. print(f"Firmware version not found in file: {ino_file_path}")
  79. if not firmware_details["motorType"]:
  80. print(f"Motor type not found in file: {ino_file_path}")
  81. return firmware_details if any(firmware_details.values()) else None
  82. except FileNotFoundError:
  83. print(f"File not found: {ino_file_path}")
  84. return None
  85. except Exception as e:
  86. print(f"Error reading .ino file: {str(e)}")
  87. return None
  88. def check_git_updates():
  89. try:
  90. # Fetch the latest updates from the remote repository
  91. subprocess.run(["git", "fetch", "--tags", "--force"], check=True)
  92. # Get the latest tag from the remote
  93. latest_remote_tag = subprocess.check_output(
  94. ["git", "describe", "--tags", "--abbrev=0", "origin/main"]
  95. ).strip().decode()
  96. # Get the latest tag from the local branch
  97. latest_local_tag = subprocess.check_output(
  98. ["git", "describe", "--tags", "--abbrev=0"]
  99. ).strip().decode()
  100. # Count how many tags the local branch is behind
  101. tag_behind_count = 0
  102. if latest_local_tag != latest_remote_tag:
  103. tags = subprocess.check_output(
  104. ["git", "tag", "--merged", "origin/main"], text=True
  105. ).splitlines()
  106. found_local = False
  107. for tag in tags:
  108. if tag == latest_local_tag:
  109. found_local = True
  110. elif found_local:
  111. tag_behind_count += 1
  112. if tag == latest_remote_tag:
  113. break
  114. # Check if there are new commits
  115. updates_available = latest_remote_tag != latest_local_tag
  116. return {
  117. "updates_available": updates_available,
  118. "tag_behind_count": tag_behind_count, # Tags behind
  119. "latest_remote_tag": latest_remote_tag,
  120. "latest_local_tag": latest_local_tag,
  121. }
  122. except subprocess.CalledProcessError as e:
  123. print(f"Error checking Git updates: {e}")
  124. return {
  125. "updates_available": False,
  126. "tag_behind_count": 0,
  127. "latest_remote_tag": None,
  128. "latest_local_tag": None,
  129. }
  130. def list_serial_ports():
  131. """Return a list of available serial ports."""
  132. ports = serial.tools.list_ports.comports()
  133. return [port.device for port in ports if port.device not in IGNORE_PORTS]
  134. def connect_to_serial(port=None, baudrate=115200):
  135. """Automatically connect to the first available serial port or a specified port."""
  136. global ser, ser_port, arduino_table_name, arduino_driver_type, firmware_version
  137. try:
  138. if port is None:
  139. ports = list_serial_ports()
  140. if not ports:
  141. print("No serial port connected")
  142. return False
  143. port = ports[0] # Auto-select the first available port
  144. with serial_lock:
  145. if ser and ser.is_open:
  146. ser.close()
  147. ser = serial.Serial(port, baudrate, timeout=2) # Set timeout to avoid infinite waits
  148. ser_port = port # Store the connected port globally
  149. print(f"Connected to serial port: {port}")
  150. time.sleep(2) # Allow time for the connection to establish
  151. # Read initial startup messages from Arduino
  152. arduino_table_name = None
  153. arduino_driver_type = None
  154. while ser.in_waiting > 0:
  155. line = ser.readline().decode().strip()
  156. print(f"Arduino: {line}") # Print the received message
  157. # Store the device details based on the expected messages
  158. if "Table:" in line:
  159. arduino_table_name = line.replace("Table: ", "").strip()
  160. elif "Drivers:" in line:
  161. arduino_driver_type = line.replace("Drivers: ", "").strip()
  162. elif "Version:" in line:
  163. firmware_version = line.replace("Version: ", "").strip()
  164. # Display stored values
  165. print(f"Detected Table: {arduino_table_name or 'Unknown'}")
  166. print(f"Detected Drivers: {arduino_driver_type or 'Unknown'}")
  167. return True # Successfully connected
  168. except serial.SerialException as e:
  169. print(f"Failed to connect to serial port {port}: {e}")
  170. port = None # Reset the port to try the next available one
  171. print("Max retries reached. Could not connect to a serial port.")
  172. return False
  173. def disconnect_serial():
  174. """Disconnect the current serial connection."""
  175. global ser, ser_port
  176. if ser and ser.is_open:
  177. ser.close()
  178. ser = None
  179. ser_port = None # Reset the port name
  180. def restart_serial(port, baudrate=115200):
  181. """Restart the serial connection."""
  182. disconnect_serial()
  183. connect_to_serial(port, baudrate)
  184. def parse_theta_rho_file(file_path):
  185. """
  186. Parse a theta-rho file and return a list of (theta, rho) pairs.
  187. Normalizes the list so the first theta is always 0.
  188. """
  189. coordinates = []
  190. try:
  191. with open(file_path, 'r') as file:
  192. for line in file:
  193. line = line.strip()
  194. # Skip header or comment lines (starting with '#' or empty lines)
  195. if not line or line.startswith("#"):
  196. continue
  197. # Parse lines with theta and rho separated by spaces
  198. try:
  199. theta, rho = map(float, line.split())
  200. coordinates.append((theta, rho))
  201. except ValueError:
  202. print(f"Skipping invalid line: {line}")
  203. continue
  204. except Exception as e:
  205. print(f"Error reading file: {e}")
  206. return coordinates
  207. # ---- Normalization Step ----
  208. if coordinates:
  209. # Take the first coordinate's theta
  210. first_theta = coordinates[0][0]
  211. # Shift all thetas so the first coordinate has theta=0
  212. normalized = []
  213. for (theta, rho) in coordinates:
  214. normalized.append((theta - first_theta, rho))
  215. # Replace original list with normalized data
  216. coordinates = normalized
  217. return coordinates
  218. def send_coordinate_batch(ser, coordinates):
  219. """Send a batch of theta-rho pairs to the Arduino."""
  220. # print("Sending batch:", coordinates)
  221. batch_str = ";".join(f"{theta:.5f},{rho:.5f}" for theta, rho in coordinates) + ";\n"
  222. ser.write(batch_str.encode())
  223. def send_command(command):
  224. """Send a single command to the Arduino."""
  225. ser.write(f"{command}\n".encode())
  226. print(f"Sent: {command}")
  227. # Wait for "R" acknowledgment from Arduino
  228. while True:
  229. with serial_lock:
  230. if ser.in_waiting > 0:
  231. response = ser.readline().decode().strip()
  232. print(f"Arduino response: {response}")
  233. if response == "R":
  234. print("Command execution completed.")
  235. break
  236. def wait_for_start_time(schedule_hours):
  237. """
  238. Keep checking every 30 seconds if the time is within the schedule to resume execution.
  239. """
  240. global pause_requested
  241. start_time, end_time = schedule_hours
  242. while pause_requested:
  243. now = datetime.now().time()
  244. if start_time <= now < end_time:
  245. print("Resuming execution: Within schedule.")
  246. pause_requested = False
  247. with pause_condition:
  248. pause_condition.notify_all()
  249. break # Exit the loop once resumed
  250. else:
  251. time.sleep(30) # Wait for 30 seconds before checking again
  252. # Function to check schedule based on start and end time
  253. def schedule_checker(schedule_hours):
  254. """
  255. Pauses/resumes execution based on a given time range.
  256. Parameters:
  257. - schedule_hours (tuple): (start_time, end_time) as `datetime.time` objects.
  258. """
  259. global pause_requested
  260. if not schedule_hours:
  261. return # No scheduling restriction
  262. start_time, end_time = schedule_hours
  263. now = datetime.now().time() # Get the current time as `datetime.time`
  264. # Check if we are currently within the scheduled time
  265. if start_time <= now < end_time:
  266. if pause_requested:
  267. print("Starting execution: Within schedule.")
  268. pause_requested = False # Resume execution
  269. with pause_condition:
  270. pause_condition.notify_all()
  271. else:
  272. if not pause_requested:
  273. print("Pausing execution: Outside schedule.")
  274. pause_requested = True # Pause execution
  275. # Start a background thread to periodically check for start time
  276. threading.Thread(target=wait_for_start_time, args=(schedule_hours,), daemon=True).start()
  277. def run_theta_rho_file(file_path, schedule_hours=None):
  278. """Run a theta-rho file by sending data in optimized batches with tqdm ETA tracking."""
  279. global stop_requested, current_playing_file, execution_progress
  280. stop_requested = False
  281. current_playing_file = file_path # Track current playing file
  282. execution_progress = (0, 0, None) # Reset progress (ETA starts as None)
  283. coordinates = parse_theta_rho_file(file_path)
  284. total_coordinates = len(coordinates)
  285. if total_coordinates < 2:
  286. print("Not enough coordinates for interpolation.")
  287. current_playing_file = None # Clear tracking if failed
  288. execution_progress = None
  289. return
  290. execution_progress = (0, total_coordinates, None) # Initialize progress with ETA as None
  291. batch_size = 10 # Smaller batches may smooth movement further
  292. with tqdm(total=total_coordinates, unit="coords", desc="Executing Pattern", dynamic_ncols=True, disable=None) as pbar:
  293. for i in range(0, total_coordinates, batch_size):
  294. if stop_requested:
  295. print("Execution stopped by user after completing the current batch.")
  296. break
  297. with pause_condition:
  298. while pause_requested:
  299. print("Execution paused...")
  300. pause_condition.wait() # This will block execution until notified
  301. batch = coordinates[i:i + batch_size]
  302. if i == 0:
  303. send_coordinate_batch(ser, batch)
  304. execution_progress = (i + batch_size, total_coordinates, None) # No ETA yet
  305. pbar.update(batch_size)
  306. continue
  307. while True:
  308. schedule_checker(schedule_hours) # Check if within schedule
  309. with serial_lock:
  310. if ser.in_waiting > 0:
  311. response = ser.readline().decode().strip()
  312. if response == "R":
  313. send_coordinate_batch(ser, batch)
  314. pbar.update(batch_size) # Update tqdm progress
  315. # Use tqdm's built-in ETA tracking
  316. estimated_remaining_time = pbar.format_dict['elapsed'] / (i + batch_size) * (total_coordinates - (i + batch_size))
  317. # Update execution progress with formatted ETA
  318. execution_progress = (i + batch_size, total_coordinates, estimated_remaining_time)
  319. break
  320. elif response.startswith("IGNORE"): # Retry the previous batch
  321. print("Received IGNORE. Resending the previous batch...")
  322. # Calculate the previous batch indices
  323. prev_start = max(0, i - batch_size) # Ensure we don't go below 0
  324. prev_end = i # End of the previous batch is `i`
  325. previous_batch = coordinates[prev_start:prev_end]
  326. # Resend the previous batch
  327. send_coordinate_batch(ser, previous_batch)
  328. break # Exit the retry loop after resending
  329. else:
  330. print(f"Arduino response: {response}")
  331. reset_theta()
  332. ser.write("FINISHED\n".encode())
  333. # Clear tracking variables when done
  334. current_playing_file = None
  335. execution_progress = None
  336. print("Pattern execution completed.")
  337. def get_clear_pattern_file(clear_pattern_mode, path=None):
  338. """Return a .thr file path based on pattern_name."""
  339. if not clear_pattern_mode or clear_pattern_mode == 'none':
  340. return
  341. print("Clear pattern mode: " + clear_pattern_mode)
  342. if clear_pattern_mode == "random":
  343. # Randomly pick one of the three known patterns
  344. return random.choice(list(CLEAR_PATTERNS.values()))
  345. if clear_pattern_mode == 'adaptive':
  346. _, first_rho = parse_theta_rho_file(path)[0]
  347. if first_rho < 0.5:
  348. return CLEAR_PATTERNS['clear_from_out']
  349. else:
  350. return random.choice([CLEAR_PATTERNS['clear_from_in'], CLEAR_PATTERNS['clear_sideway']])
  351. def run_theta_rho_files(
  352. file_paths,
  353. pause_time=0,
  354. clear_pattern=None,
  355. run_mode="single",
  356. shuffle=False,
  357. schedule_hours=None
  358. ):
  359. """
  360. Runs multiple .thr files in sequence with options for pausing, clearing, shuffling, and looping.
  361. Parameters:
  362. - file_paths (list): List of file paths to run.
  363. - pause_time (float): Seconds to pause between patterns.
  364. - clear_pattern (str): Specific clear pattern to run ("clear_from_in", "clear_from_out", "clear_sideway", "adaptive", or "random").
  365. - run_mode (str): "single" for one-time run or "indefinite" for looping.
  366. - shuffle (bool): Whether to shuffle the playlist before running.
  367. """
  368. global stop_requested
  369. global current_playlist
  370. global current_playing_index
  371. stop_requested = False # Reset stop flag at the start
  372. if shuffle:
  373. random.shuffle(file_paths)
  374. print("Playlist shuffled.")
  375. current_playlist = file_paths
  376. while True:
  377. for idx, path in enumerate(file_paths):
  378. print("Upcoming pattern: " + path)
  379. current_playing_index = idx
  380. schedule_checker(schedule_hours)
  381. if stop_requested:
  382. print("Execution stopped before starting next pattern.")
  383. return
  384. if clear_pattern:
  385. if stop_requested:
  386. print("Execution stopped before running the next clear pattern.")
  387. return
  388. # Determine the clear pattern to run
  389. clear_file_path = get_clear_pattern_file(clear_pattern, path)
  390. print(f"Running clear pattern: {clear_file_path}")
  391. run_theta_rho_file(clear_file_path, schedule_hours)
  392. if not stop_requested:
  393. # Run the main pattern
  394. print(f"Running pattern {idx + 1} of {len(file_paths)}: {path}")
  395. run_theta_rho_file(path, schedule_hours)
  396. if idx < len(file_paths) -1:
  397. if stop_requested:
  398. print("Execution stopped before running the next clear pattern.")
  399. return
  400. # Pause after each pattern if requested
  401. if pause_time > 0:
  402. print(f"Pausing for {pause_time} seconds...")
  403. time.sleep(pause_time)
  404. # After completing the playlist
  405. if run_mode == "indefinite":
  406. print("Playlist completed. Restarting as per 'indefinite' run mode.")
  407. if pause_time > 0:
  408. print(f"Pausing for {pause_time} seconds before restarting...")
  409. time.sleep(pause_time)
  410. if shuffle:
  411. random.shuffle(file_paths)
  412. print("Playlist reshuffled for the next loop.")
  413. continue
  414. else:
  415. print("Playlist completed.")
  416. break
  417. # Reset theta after execution or stopping
  418. reset_theta()
  419. ser.write("FINISHED\n".encode())
  420. print("All requested patterns completed (or stopped).")
  421. def reset_theta():
  422. """Reset theta on the Arduino."""
  423. ser.write("RESET_THETA\n".encode())
  424. while True:
  425. with serial_lock:
  426. if ser.in_waiting > 0:
  427. response = ser.readline().decode().strip()
  428. print(f"Arduino response: {response}")
  429. if response == "THETA_RESET":
  430. print("Theta successfully reset.")
  431. break
  432. time.sleep(0.5) # Small delay to avoid busy waiting
  433. # Flask API Endpoints
  434. @app.route('/')
  435. def index():
  436. return render_template('index.html')
  437. @app.route('/list_serial_ports', methods=['GET'])
  438. def list_ports():
  439. return jsonify(list_serial_ports())
  440. @app.route('/connect_serial', methods=['POST'])
  441. def connect_serial():
  442. port = request.json.get('port')
  443. if not port:
  444. return jsonify({'error': 'No port provided'}), 400
  445. try:
  446. connect_to_serial(port)
  447. return jsonify({'success': True})
  448. except Exception as e:
  449. return jsonify({'error': str(e)}), 500
  450. @app.route('/disconnect_serial', methods=['POST'])
  451. def disconnect():
  452. try:
  453. disconnect_serial()
  454. return jsonify({'success': True})
  455. except Exception as e:
  456. return jsonify({'error': str(e)}), 500
  457. @app.route('/restart_serial', methods=['POST'])
  458. def restart():
  459. port = request.json.get('port')
  460. if not port:
  461. return jsonify({'error': 'No port provided'}), 400
  462. try:
  463. restart_serial(port)
  464. return jsonify({'success': True})
  465. except Exception as e:
  466. return jsonify({'error': str(e)}), 500
  467. @app.route('/list_theta_rho_files', methods=['GET'])
  468. def list_theta_rho_files():
  469. files = []
  470. for root, _, filenames in os.walk(THETA_RHO_DIR):
  471. for file in filenames:
  472. # Construct the relative file path
  473. relative_path = os.path.relpath(os.path.join(root, file), THETA_RHO_DIR)
  474. files.append(relative_path)
  475. return jsonify(sorted(files))
  476. @app.route('/upload_theta_rho', methods=['POST'])
  477. def upload_theta_rho():
  478. custom_patterns_dir = os.path.join(THETA_RHO_DIR, 'custom_patterns')
  479. os.makedirs(custom_patterns_dir, exist_ok=True) # Ensure the directory exists
  480. file = request.files['file']
  481. if file:
  482. file.save(os.path.join(custom_patterns_dir, file.filename))
  483. return jsonify({'success': True})
  484. return jsonify({'success': False})
  485. @app.route('/run_theta_rho', methods=['POST'])
  486. def run_theta_rho():
  487. file_name = request.json.get('file_name')
  488. pre_execution = request.json.get('pre_execution')
  489. if not file_name:
  490. return jsonify({'error': 'No file name provided'}), 400
  491. file_path = os.path.join(THETA_RHO_DIR, file_name)
  492. if not os.path.exists(file_path):
  493. return jsonify({'error': 'File not found'}), 404
  494. try:
  495. # Build a list of files to run in sequence
  496. files_to_run = []
  497. # Finally, add the main file
  498. files_to_run.append(file_path)
  499. # Run them in one shot using run_theta_rho_files (blocking call)
  500. threading.Thread(
  501. target=run_theta_rho_files,
  502. args=(files_to_run,),
  503. kwargs={
  504. 'pause_time': 0,
  505. 'clear_pattern': pre_execution
  506. }
  507. ).start()
  508. return jsonify({'success': True})
  509. except Exception as e:
  510. return jsonify({'error': str(e)}), 500
  511. def stop_actions():
  512. global pause_requested
  513. with pause_condition:
  514. pause_requested = False
  515. pause_condition.notify_all()
  516. global stop_requested, current_playing_index, current_playlist, is_clearing, current_playing_file, execution_progress
  517. stop_requested = True
  518. current_playing_index = None
  519. current_playlist = None
  520. is_clearing = False
  521. current_playing_file = None
  522. execution_progress = None
  523. @app.route('/stop_execution', methods=['POST'])
  524. def stop_execution():
  525. stop_actions()
  526. return jsonify({'success': True})
  527. @app.route('/send_home', methods=['POST'])
  528. def send_home():
  529. """Send the HOME command to the Arduino."""
  530. try:
  531. send_command("HOME")
  532. return jsonify({'success': True})
  533. except Exception as e:
  534. return jsonify({'error': str(e)}), 500
  535. @app.route('/run_theta_rho_file/<file_name>', methods=['POST'])
  536. def run_specific_theta_rho_file(file_name):
  537. """Run a specific theta-rho file."""
  538. file_path = os.path.join(THETA_RHO_DIR, file_name)
  539. if not os.path.exists(file_path):
  540. return jsonify({'error': 'File not found'}), 404
  541. threading.Thread(target=run_theta_rho_file, args=(file_path,)).start()
  542. return jsonify({'success': True})
  543. @app.route('/delete_theta_rho_file', methods=['POST'])
  544. def delete_theta_rho_file():
  545. data = request.json
  546. file_name = data.get('file_name')
  547. if not file_name:
  548. return jsonify({"success": False, "error": "No file name provided"}), 400
  549. file_path = os.path.join(THETA_RHO_DIR, file_name)
  550. if not os.path.exists(file_path):
  551. return jsonify({"success": False, "error": "File not found"}), 404
  552. try:
  553. os.remove(file_path)
  554. return jsonify({"success": True})
  555. except Exception as e:
  556. return jsonify({"success": False, "error": str(e)}), 500
  557. @app.route('/move_to_center', methods=['POST'])
  558. def move_to_center():
  559. """Move the sand table to the center position."""
  560. try:
  561. if ser is None or not ser.is_open:
  562. return jsonify({"success": False, "error": "Serial connection not established"}), 400
  563. coordinates = [(0, 0)] # Center position
  564. send_coordinate_batch(ser, coordinates)
  565. return jsonify({"success": True})
  566. except Exception as e:
  567. return jsonify({"success": False, "error": str(e)}), 500
  568. @app.route('/move_to_perimeter', methods=['POST'])
  569. def move_to_perimeter():
  570. """Move the sand table to the perimeter position."""
  571. try:
  572. if ser is None or not ser.is_open:
  573. return jsonify({"success": False, "error": "Serial connection not established"}), 400
  574. MAX_RHO = 1
  575. coordinates = [(0, MAX_RHO)] # Perimeter position
  576. send_coordinate_batch(ser, coordinates)
  577. return jsonify({"success": True})
  578. except Exception as e:
  579. return jsonify({"success": False, "error": str(e)}), 500
  580. @app.route('/preview_thr', methods=['POST'])
  581. def preview_thr():
  582. file_name = request.json.get('file_name')
  583. if not file_name:
  584. return jsonify({'error': 'No file name provided'}), 400
  585. file_path = os.path.join(THETA_RHO_DIR, file_name)
  586. if not os.path.exists(file_path):
  587. return jsonify({'error': 'File not found'}), 404
  588. try:
  589. # Parse the .thr file with transformations
  590. coordinates = parse_theta_rho_file(file_path)
  591. return jsonify({'success': True, 'coordinates': coordinates})
  592. except Exception as e:
  593. return jsonify({'error': str(e)}), 500
  594. @app.route('/send_coordinate', methods=['POST'])
  595. def send_coordinate():
  596. """Send a single (theta, rho) coordinate to the Arduino."""
  597. global ser
  598. if ser is None or not ser.is_open:
  599. return jsonify({"success": False, "error": "Serial connection not established"}), 400
  600. try:
  601. data = request.json
  602. theta = data.get('theta')
  603. rho = data.get('rho')
  604. if theta is None or rho is None:
  605. return jsonify({"success": False, "error": "Theta and Rho are required"}), 400
  606. # Send the coordinate to the Arduino
  607. send_coordinate_batch(ser, [(theta, rho)])
  608. return jsonify({"success": True})
  609. except Exception as e:
  610. return jsonify({"success": False, "error": str(e)}), 500
  611. # Expose files for download if needed
  612. @app.route('/download/<filename>', methods=['GET'])
  613. def download_file(filename):
  614. """Download a file from the theta-rho directory."""
  615. return send_from_directory(THETA_RHO_DIR, filename)
  616. @app.route('/serial_status', methods=['GET'])
  617. def serial_status():
  618. global ser, ser_port
  619. return jsonify({
  620. 'connected': ser.is_open if ser else False,
  621. 'port': ser_port # Include the port name
  622. })
  623. @app.route('/pause_execution', methods=['POST'])
  624. def pause_execution():
  625. """Pause the current execution."""
  626. global pause_requested
  627. with pause_condition:
  628. pause_requested = True
  629. return jsonify({'success': True, 'message': 'Execution paused'})
  630. @app.route('/status', methods=['GET'])
  631. def get_status():
  632. """Returns the current status of the sand table."""
  633. global is_clearing
  634. if current_playing_file in CLEAR_PATTERNS.values():
  635. is_clearing = True
  636. else:
  637. is_clearing = False
  638. return jsonify({
  639. "ser_port": ser_port,
  640. "stop_requested": stop_requested,
  641. "pause_requested": pause_requested,
  642. "current_playing_file": current_playing_file,
  643. "execution_progress": execution_progress,
  644. "current_playing_index": current_playing_index,
  645. "current_playlist": current_playlist,
  646. "is_clearing": is_clearing
  647. })
  648. @app.route('/resume_execution', methods=['POST'])
  649. def resume_execution():
  650. """Resume execution after pausing."""
  651. global pause_requested
  652. with pause_condition:
  653. pause_requested = False
  654. pause_condition.notify_all() # Unblock the waiting thread
  655. return jsonify({'success': True, 'message': 'Execution resumed'})
  656. def load_playlists():
  657. """
  658. Load the entire playlists dictionary from the JSON file.
  659. Returns something like: {
  660. "My Playlist": ["file1.thr", "file2.thr"],
  661. "Another": ["x.thr"]
  662. }
  663. """
  664. with open(PLAYLISTS_FILE, "r") as f:
  665. return json.load(f)
  666. def save_playlists(playlists_dict):
  667. """
  668. Save the entire playlists dictionary back to the JSON file.
  669. """
  670. with open(PLAYLISTS_FILE, "w") as f:
  671. json.dump(playlists_dict, f, indent=2)
  672. @app.route("/list_all_playlists", methods=["GET"])
  673. def list_all_playlists():
  674. """
  675. Returns a list of all playlist names.
  676. Example return: ["My Playlist", "Another Playlist"]
  677. """
  678. playlists_dict = load_playlists()
  679. playlist_names = list(playlists_dict.keys())
  680. return jsonify(playlist_names)
  681. @app.route("/get_playlist", methods=["GET"])
  682. def get_playlist():
  683. """
  684. GET /get_playlist?name=My%20Playlist
  685. Returns: { "name": "My Playlist", "files": [... ] }
  686. """
  687. playlist_name = request.args.get("name", "")
  688. if not playlist_name:
  689. return jsonify({"error": "Missing playlist 'name' parameter"}), 400
  690. playlists_dict = load_playlists()
  691. if playlist_name not in playlists_dict:
  692. return jsonify({"error": f"Playlist '{playlist_name}' not found"}), 404
  693. files = playlists_dict[playlist_name] # e.g. ["file1.thr", "file2.thr"]
  694. return jsonify({
  695. "name": playlist_name,
  696. "files": files
  697. })
  698. @app.route("/create_playlist", methods=["POST"])
  699. def create_playlist():
  700. """
  701. POST /create_playlist
  702. Body: { "name": "My Playlist", "files": ["file1.thr", "file2.thr"] }
  703. Creates or overwrites a playlist with the given name.
  704. """
  705. data = request.get_json()
  706. if not data or "name" not in data or "files" not in data:
  707. return jsonify({"success": False, "error": "Playlist 'name' and 'files' are required"}), 400
  708. playlist_name = data["name"]
  709. files = data["files"]
  710. # Load all playlists
  711. playlists_dict = load_playlists()
  712. # Overwrite or create new
  713. playlists_dict[playlist_name] = files
  714. # Save changes
  715. save_playlists(playlists_dict)
  716. return jsonify({
  717. "success": True,
  718. "message": f"Playlist '{playlist_name}' created/updated"
  719. })
  720. @app.route("/modify_playlist", methods=["POST"])
  721. def modify_playlist():
  722. """
  723. POST /modify_playlist
  724. Body: { "name": "My Playlist", "files": ["file1.thr", "file2.thr"] }
  725. Updates (or creates) the existing playlist with a new file list.
  726. You can 404 if you only want to allow modifications to existing playlists.
  727. """
  728. data = request.get_json()
  729. if not data or "name" not in data or "files" not in data:
  730. return jsonify({"success": False, "error": "Playlist 'name' and 'files' are required"}), 400
  731. playlist_name = data["name"]
  732. files = data["files"]
  733. # Load all playlists
  734. playlists_dict = load_playlists()
  735. # Optional: If you want to disallow creating a new playlist here:
  736. # if playlist_name not in playlists_dict:
  737. # return jsonify({"success": False, "error": f"Playlist '{playlist_name}' not found"}), 404
  738. # Overwrite or create new
  739. playlists_dict[playlist_name] = files
  740. # Save
  741. save_playlists(playlists_dict)
  742. return jsonify({"success": True, "message": f"Playlist '{playlist_name}' updated"})
  743. @app.route("/delete_playlist", methods=["DELETE"])
  744. def delete_playlist():
  745. """
  746. DELETE /delete_playlist
  747. Body: { "name": "My Playlist" }
  748. Removes the playlist from the single JSON file.
  749. """
  750. data = request.get_json()
  751. if not data or "name" not in data:
  752. return jsonify({"success": False, "error": "Missing 'name' field"}), 400
  753. playlist_name = data["name"]
  754. playlists_dict = load_playlists()
  755. if playlist_name not in playlists_dict:
  756. return jsonify({"success": False, "error": f"Playlist '{playlist_name}' not found"}), 404
  757. # Remove from dict
  758. del playlists_dict[playlist_name]
  759. save_playlists(playlists_dict)
  760. return jsonify({
  761. "success": True,
  762. "message": f"Playlist '{playlist_name}' deleted"
  763. })
  764. @app.route('/add_to_playlist', methods=['POST'])
  765. def add_to_playlist():
  766. data = request.json
  767. playlist_name = data.get('playlist_name')
  768. pattern = data.get('pattern')
  769. # Load existing playlists
  770. with open('playlists.json', 'r') as f:
  771. playlists = json.load(f)
  772. # Add pattern to the selected playlist
  773. if playlist_name in playlists:
  774. playlists[playlist_name].append(pattern)
  775. with open('playlists.json', 'w') as f:
  776. json.dump(playlists, f)
  777. return jsonify(success=True)
  778. else:
  779. return jsonify(success=False, error='Playlist not found'), 404
  780. @app.route("/run_playlist", methods=["POST"])
  781. def run_playlist():
  782. """
  783. POST /run_playlist
  784. Body (JSON):
  785. {
  786. "playlist_name": "My Playlist",
  787. "pause_time": 1.0, # Optional: seconds to pause between patterns
  788. "clear_pattern": "random", # Optional: "clear_from_in", "clear_from_out", "clear_sideway", "adaptive" or "random"
  789. "run_mode": "single", # 'single' or 'indefinite'
  790. "shuffle": True # true or false
  791. "start_time": ""
  792. "end_time": ""
  793. }
  794. """
  795. data = request.get_json()
  796. # Validate input
  797. if not data or "playlist_name" not in data:
  798. return jsonify({"success": False, "error": "Missing 'playlist_name' field"}), 400
  799. playlist_name = data["playlist_name"]
  800. pause_time = data.get("pause_time", 0)
  801. clear_pattern = data.get("clear_pattern", None)
  802. run_mode = data.get("run_mode", "single") # Default to 'single' run
  803. shuffle = data.get("shuffle", False) # Default to no shuffle
  804. start_time = data.get("start_time", None)
  805. end_time = data.get("end_time", None)
  806. # Validate pause_time
  807. if not isinstance(pause_time, (int, float)) or pause_time < 0:
  808. return jsonify({"success": False, "error": "'pause_time' must be a non-negative number"}), 400
  809. # Validate clear_pattern
  810. valid_patterns = ["clear_from_in", "clear_from_out", "clear_sideway", "random", "adaptive"]
  811. if clear_pattern not in valid_patterns:
  812. clear_pattern = None
  813. # Validate run_mode
  814. if run_mode not in ["single", "indefinite"]:
  815. return jsonify({"success": False, "error": "'run_mode' must be 'single' or 'indefinite'"}), 400
  816. # Validate shuffle
  817. if not isinstance(shuffle, bool):
  818. return jsonify({"success": False, "error": "'shuffle' must be a boolean value"}), 400
  819. schedule_hours = None
  820. if start_time and end_time:
  821. try:
  822. # Convert HH:MM to datetime.time objects
  823. start_time_obj = datetime.strptime(start_time, "%H:%M").time()
  824. end_time_obj = datetime.strptime(end_time, "%H:%M").time()
  825. # Ensure start_time is before end_time
  826. if start_time_obj >= end_time_obj:
  827. return jsonify({"success": False, "error": "'start_time' must be earlier than 'end_time'"}), 400
  828. # Create schedule tuple with full time
  829. schedule_hours = (start_time_obj, end_time_obj)
  830. except ValueError:
  831. return jsonify({"success": False, "error": "Invalid time format. Use HH:MM (e.g., '09:30')"}), 400
  832. # Load playlists
  833. playlists = load_playlists()
  834. if playlist_name not in playlists:
  835. return jsonify({"success": False, "error": f"Playlist '{playlist_name}' not found"}), 404
  836. file_paths = playlists[playlist_name]
  837. file_paths = [os.path.join(THETA_RHO_DIR, file) for file in file_paths]
  838. if not file_paths:
  839. return jsonify({"success": False, "error": f"Playlist '{playlist_name}' is empty"}), 400
  840. # Start the playlist execution in a separate thread
  841. try:
  842. threading.Thread(
  843. target=run_theta_rho_files,
  844. args=(file_paths,),
  845. kwargs={
  846. 'pause_time': pause_time,
  847. 'clear_pattern': clear_pattern,
  848. 'run_mode': run_mode,
  849. 'shuffle': shuffle,
  850. 'schedule_hours': schedule_hours
  851. },
  852. daemon=True # Daemonize thread to exit with the main program
  853. ).start()
  854. return jsonify({"success": True, "message": f"Playlist '{playlist_name}' is now running."})
  855. except Exception as e:
  856. return jsonify({"success": False, "error": str(e)}), 500
  857. @app.route('/set_speed', methods=['POST'])
  858. def set_speed():
  859. """Set the speed for the Arduino."""
  860. global ser
  861. if ser is None or not ser.is_open:
  862. return jsonify({"success": False, "error": "Serial connection not established"}), 400
  863. try:
  864. # Parse the speed value from the request
  865. data = request.json
  866. speed = data.get('speed')
  867. if speed is None:
  868. return jsonify({"success": False, "error": "Speed is required"}), 400
  869. if not isinstance(speed, (int, float)) or speed <= 0:
  870. return jsonify({"success": False, "error": "Invalid speed value"}), 400
  871. # Send the SET_SPEED command to the Arduino
  872. command = f"SET_SPEED {speed}"
  873. send_command(command)
  874. return jsonify({"success": True, "speed": speed})
  875. except Exception as e:
  876. return jsonify({"success": False, "error": str(e)}), 500
  877. @app.route('/get_firmware_info', methods=['GET', 'POST'])
  878. def get_firmware_info():
  879. """
  880. Compare the installed firmware version and motor type with the one in the .ino file.
  881. """
  882. global firmware_version, arduino_driver_type, ser
  883. if ser is None or not ser.is_open:
  884. return jsonify({"success": False, "error": "Arduino not connected or serial port not open"}), 400
  885. try:
  886. if request.method == "GET":
  887. # Attempt to retrieve installed firmware details from the Arduino
  888. time.sleep(0.5)
  889. installed_version = firmware_version
  890. installed_type = arduino_driver_type
  891. # If Arduino provides valid details, proceed with comparison
  892. if installed_version != 'Unknown' and installed_type != 'Unknown':
  893. ino_path = MOTOR_TYPE_MAPPING.get(installed_type)
  894. firmware_details = get_ino_firmware_details(ino_path)
  895. if not firmware_details or not firmware_details.get("version") or not firmware_details.get("motorType"):
  896. return jsonify({"success": False, "error": "Failed to retrieve .ino firmware details"}), 500
  897. update_available = (
  898. installed_version != firmware_details["version"] or
  899. installed_type != firmware_details["motorType"]
  900. )
  901. return jsonify({
  902. "success": True,
  903. "installedVersion": installed_version,
  904. "installedType": installed_type,
  905. "inoVersion": firmware_details["version"],
  906. "inoType": firmware_details["motorType"],
  907. "updateAvailable": update_available
  908. })
  909. # If Arduino details are unknown, indicate the need for POST
  910. return jsonify({
  911. "success": True,
  912. "installedVersion": installed_version,
  913. "installedType": installed_type,
  914. "updateAvailable": False
  915. })
  916. elif request.method == "POST":
  917. motor_type = request.json.get("motorType", None)
  918. if not motor_type or motor_type not in MOTOR_TYPE_MAPPING:
  919. return jsonify({
  920. "success": False,
  921. "error": "Invalid or missing motor type"
  922. }), 400
  923. # Fetch firmware details for the given motor type
  924. ino_path = MOTOR_TYPE_MAPPING[motor_type]
  925. firmware_details = get_ino_firmware_details(ino_path)
  926. if not firmware_details:
  927. return jsonify({
  928. "success": False,
  929. "error": "Failed to retrieve .ino firmware details"
  930. }), 500
  931. return jsonify({
  932. "success": True,
  933. "installedVersion": 'Unknown',
  934. "installedType": motor_type,
  935. "inoVersion": firmware_details["version"],
  936. "inoType": firmware_details["motorType"],
  937. "updateAvailable": True
  938. })
  939. except Exception as e:
  940. return jsonify({"success": False, "error": str(e)}), 500
  941. @app.route('/flash_firmware', methods=['POST'])
  942. def flash_firmware():
  943. """
  944. Flash the pre-compiled firmware to the connected device (Arduino or ESP32).
  945. """
  946. global ser_port
  947. # Ensure the device is connected
  948. if ser_port is None or ser is None or not ser.is_open:
  949. return jsonify({"success": False, "error": "No device connected or connection lost"}), 400
  950. try:
  951. data = request.json
  952. motor_type = data.get("motorType", None)
  953. # Validate motor type
  954. if not motor_type or motor_type not in MOTOR_TYPE_MAPPING:
  955. return jsonify({"success": False, "error": "Invalid or missing motor type"}), 400
  956. # Determine the firmware file
  957. ino_file_path = MOTOR_TYPE_MAPPING[motor_type] # Path to .ino file
  958. hex_file_path = f"{ino_file_path}.hex"
  959. bin_file_path = f"{ino_file_path}.bin" # For ESP32 firmware
  960. # Check the device type
  961. if motor_type.lower() == "esp32":
  962. if not os.path.exists(bin_file_path):
  963. return jsonify({"success": False, "error": f"Firmware binary not found: {bin_file_path}"}), 404
  964. # Flash ESP32 firmware
  965. flash_command = [
  966. "esptool.py",
  967. "--chip", "esp32",
  968. "--port", ser_port,
  969. "--baud", "115200",
  970. "write_flash", "-z", "0x1000", bin_file_path
  971. ]
  972. else:
  973. if not os.path.exists(hex_file_path):
  974. return jsonify({"success": False, "error": f"Hex file not found: {hex_file_path}"}), 404
  975. # Flash Arduino firmware
  976. flash_command = [
  977. "avrdude",
  978. "-v",
  979. "-c", "arduino",
  980. "-p", "atmega328p",
  981. "-P", ser_port,
  982. "-b", "115200",
  983. "-D",
  984. "-U", f"flash:w:{hex_file_path}:i"
  985. ]
  986. # Execute the flash command
  987. flash_process = subprocess.run(flash_command, capture_output=True, text=True)
  988. if flash_process.returncode != 0:
  989. return jsonify({
  990. "success": False,
  991. "error": flash_process.stderr
  992. }), 500
  993. return jsonify({"success": True, "message": "Firmware flashed successfully"})
  994. except Exception as e:
  995. return jsonify({"success": False, "error": str(e)}), 500
  996. @app.route('/check_software_update', methods=['GET'])
  997. def check_updates():
  998. update_info = check_git_updates()
  999. return jsonify(update_info)
  1000. @app.route('/update_software', methods=['POST'])
  1001. def update_software():
  1002. error_log = []
  1003. def run_command(command, error_message):
  1004. try:
  1005. subprocess.run(command, check=True)
  1006. except subprocess.CalledProcessError as e:
  1007. print(f"{error_message}: {e}")
  1008. error_log.append(error_message)
  1009. # Fetch the latest version tag from remote
  1010. try:
  1011. subprocess.run(["git", "fetch", "--tags"], check=True)
  1012. latest_remote_tag = subprocess.check_output(
  1013. ["git", "describe", "--tags", "--abbrev=0", "origin/main"]
  1014. ).strip().decode()
  1015. except subprocess.CalledProcessError as e:
  1016. error_log.append(f"Failed to fetch tags or get latest remote tag: {e}")
  1017. return jsonify({
  1018. "success": False,
  1019. "error": "Failed to fetch tags or determine the latest version.",
  1020. "details": error_log
  1021. }), 500
  1022. # Checkout the latest tag
  1023. run_command(["git", "checkout", latest_remote_tag, '--force'], f"Failed to checkout version {latest_remote_tag}")
  1024. # Restart Docker containers
  1025. run_command(["docker", "compose", "up", "-d"], "Failed to restart Docker containers")
  1026. # Check if the update was successful
  1027. update_status = check_git_updates()
  1028. if (
  1029. update_status["updates_available"] is False
  1030. and update_status["latest_local_tag"] == update_status["latest_remote_tag"]
  1031. ):
  1032. # Update was successful
  1033. return jsonify({"success": True})
  1034. else:
  1035. # Update failed; include the errors in the response
  1036. return jsonify({
  1037. "success": False,
  1038. "error": "Update incomplete",
  1039. "details": error_log
  1040. }), 500
  1041. def on_exit():
  1042. """Function to execute on application shutdown."""
  1043. print("Shutting down the application...")
  1044. stop_actions()
  1045. time.sleep(5)
  1046. print("Execution stopped and resources cleaned up.")
  1047. # Register the on_exit function
  1048. atexit.register(on_exit)
  1049. if __name__ == '__main__':
  1050. # Auto-connect to serial
  1051. connect_to_serial()
  1052. try:
  1053. app.run(debug=False, host='0.0.0.0', port=8080)
  1054. except KeyboardInterrupt:
  1055. print("Keyboard interrupt received. Shutting down.")
  1056. finally:
  1057. on_exit() # Ensure cleanup if app is interrupted