app.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278
  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.RLock()
  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, serial_lock
  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 serial_lock:
  293. print(serial_lock)
  294. print(type(serial_lock))
  295. with tqdm(total=total_coordinates, unit="coords", desc="Executing Pattern", dynamic_ncols=True, disable=None) as pbar:
  296. for i in range(0, total_coordinates, batch_size):
  297. if stop_requested:
  298. print("Execution stopped by user after completing the current batch.")
  299. break
  300. with pause_condition:
  301. while pause_requested:
  302. print("Execution paused...")
  303. pause_condition.wait() # This will block execution until notified
  304. batch = coordinates[i:i + batch_size]
  305. if i == 0:
  306. send_coordinate_batch(ser, batch)
  307. execution_progress = (i + batch_size, total_coordinates, None) # No ETA yet
  308. pbar.update(batch_size)
  309. continue
  310. while True:
  311. schedule_checker(schedule_hours) # Check if within schedule
  312. if ser.in_waiting > 0:
  313. response = ser.readline().decode().strip()
  314. if response == "R":
  315. send_coordinate_batch(ser, batch)
  316. pbar.update(batch_size) # Update tqdm progress
  317. # Use tqdm's built-in ETA tracking
  318. estimated_remaining_time = pbar.format_dict['elapsed'] / (i + batch_size) * (total_coordinates - (i + batch_size))
  319. # Update execution progress with formatted ETA
  320. execution_progress = (i + batch_size, total_coordinates, estimated_remaining_time)
  321. break
  322. elif response.startswith("IGNORE"): # Retry the previous batch
  323. print("Received IGNORE. Resending the previous batch...")
  324. # Calculate the previous batch indices
  325. prev_start = max(0, i - batch_size) # Ensure we don't go below 0
  326. prev_end = i # End of the previous batch is `i`
  327. previous_batch = coordinates[prev_start:prev_end]
  328. # Resend the previous batch
  329. send_coordinate_batch(ser, previous_batch)
  330. break # Exit the retry loop after resending
  331. else:
  332. print(f"Arduino response: {response}")
  333. reset_theta()
  334. ser.write("FINISHED\n".encode())
  335. # Clear tracking variables when done
  336. current_playing_file = None
  337. execution_progress = None
  338. print("Pattern execution completed.")
  339. def get_clear_pattern_file(clear_pattern_mode, path=None):
  340. """Return a .thr file path based on pattern_name."""
  341. if not clear_pattern_mode or clear_pattern_mode == 'none':
  342. return
  343. print("Clear pattern mode: " + clear_pattern_mode)
  344. if clear_pattern_mode == "random":
  345. # Randomly pick one of the three known patterns
  346. return random.choice(list(CLEAR_PATTERNS.values()))
  347. if clear_pattern_mode == 'adaptive':
  348. _, first_rho = parse_theta_rho_file(path)[0]
  349. if first_rho < 0.5:
  350. return CLEAR_PATTERNS['clear_from_out']
  351. else:
  352. return random.choice([CLEAR_PATTERNS['clear_from_in'], CLEAR_PATTERNS['clear_sideway']])
  353. else:
  354. return CLEAR_PATTERNS[clear_pattern_mode]
  355. def run_theta_rho_files(
  356. file_paths,
  357. pause_time=0,
  358. clear_pattern=None,
  359. run_mode="single",
  360. shuffle=False,
  361. schedule_hours=None
  362. ):
  363. """
  364. Runs multiple .thr files in sequence with options for pausing, clearing, shuffling, and looping.
  365. Parameters:
  366. - file_paths (list): List of file paths to run.
  367. - pause_time (float): Seconds to pause between patterns.
  368. - clear_pattern (str): Specific clear pattern to run ("clear_from_in", "clear_from_out", "clear_sideway", "adaptive", or "random").
  369. - run_mode (str): "single" for one-time run or "indefinite" for looping.
  370. - shuffle (bool): Whether to shuffle the playlist before running.
  371. """
  372. global stop_requested
  373. global current_playlist
  374. global current_playing_index
  375. stop_requested = False # Reset stop flag at the start
  376. if shuffle:
  377. random.shuffle(file_paths)
  378. print("Playlist shuffled.")
  379. current_playlist = file_paths
  380. while True:
  381. for idx, path in enumerate(file_paths):
  382. print("Upcoming pattern: " + path)
  383. current_playing_index = idx
  384. schedule_checker(schedule_hours)
  385. if stop_requested:
  386. print("Execution stopped before starting next pattern.")
  387. return
  388. if clear_pattern:
  389. if stop_requested:
  390. print("Execution stopped before running the next clear pattern.")
  391. return
  392. # Determine the clear pattern to run
  393. clear_file_path = get_clear_pattern_file(clear_pattern, path)
  394. print(f"Running clear pattern: {clear_file_path}")
  395. run_theta_rho_file(clear_file_path, schedule_hours)
  396. if not stop_requested:
  397. # Run the main pattern
  398. print(f"Running pattern {idx + 1} of {len(file_paths)}: {path}")
  399. run_theta_rho_file(path, schedule_hours)
  400. if idx < len(file_paths) -1:
  401. if stop_requested:
  402. print("Execution stopped before running the next clear pattern.")
  403. return
  404. # Pause after each pattern if requested
  405. if pause_time > 0:
  406. print(f"Pausing for {pause_time} seconds...")
  407. time.sleep(pause_time)
  408. # After completing the playlist
  409. if run_mode == "indefinite":
  410. print("Playlist completed. Restarting as per 'indefinite' run mode.")
  411. if pause_time > 0:
  412. print(f"Pausing for {pause_time} seconds before restarting...")
  413. time.sleep(pause_time)
  414. if shuffle:
  415. random.shuffle(file_paths)
  416. print("Playlist reshuffled for the next loop.")
  417. continue
  418. else:
  419. print("Playlist completed.")
  420. break
  421. # Reset theta after execution or stopping
  422. reset_theta()
  423. ser.write("FINISHED\n".encode())
  424. print("All requested patterns completed (or stopped).")
  425. def reset_theta():
  426. """Reset theta on the Arduino."""
  427. ser.write("RESET_THETA\n".encode())
  428. while True:
  429. with serial_lock:
  430. if ser.in_waiting > 0:
  431. response = ser.readline().decode().strip()
  432. print(f"Arduino response: {response}")
  433. if response == "THETA_RESET":
  434. print("Theta successfully reset.")
  435. break
  436. time.sleep(0.5) # Small delay to avoid busy waiting
  437. # Flask API Endpoints
  438. @app.route('/')
  439. def index():
  440. return render_template('index.html')
  441. @app.route('/list_serial_ports', methods=['GET'])
  442. def list_ports():
  443. return jsonify(list_serial_ports())
  444. @app.route('/connect_serial', methods=['POST'])
  445. def connect_serial():
  446. port = request.json.get('port')
  447. if not port:
  448. return jsonify({'error': 'No port provided'}), 400
  449. try:
  450. connect_to_serial(port)
  451. return jsonify({'success': True})
  452. except Exception as e:
  453. return jsonify({'error': str(e)}), 500
  454. @app.route('/disconnect_serial', methods=['POST'])
  455. def disconnect():
  456. try:
  457. disconnect_serial()
  458. return jsonify({'success': True})
  459. except Exception as e:
  460. return jsonify({'error': str(e)}), 500
  461. @app.route('/restart_serial', methods=['POST'])
  462. def restart():
  463. port = request.json.get('port')
  464. if not port:
  465. return jsonify({'error': 'No port provided'}), 400
  466. try:
  467. restart_serial(port)
  468. return jsonify({'success': True})
  469. except Exception as e:
  470. return jsonify({'error': str(e)}), 500
  471. @app.route('/list_theta_rho_files', methods=['GET'])
  472. def list_theta_rho_files():
  473. files = []
  474. for root, _, filenames in os.walk(THETA_RHO_DIR):
  475. for file in filenames:
  476. # Construct the relative file path
  477. relative_path = os.path.relpath(os.path.join(root, file), THETA_RHO_DIR)
  478. files.append(relative_path)
  479. return jsonify(sorted(files))
  480. @app.route('/upload_theta_rho', methods=['POST'])
  481. def upload_theta_rho():
  482. custom_patterns_dir = os.path.join(THETA_RHO_DIR, 'custom_patterns')
  483. os.makedirs(custom_patterns_dir, exist_ok=True) # Ensure the directory exists
  484. file = request.files['file']
  485. if file:
  486. file.save(os.path.join(custom_patterns_dir, file.filename))
  487. return jsonify({'success': True})
  488. return jsonify({'success': False})
  489. @app.route('/run_theta_rho', methods=['POST'])
  490. def run_theta_rho():
  491. file_name = request.json.get('file_name')
  492. pre_execution = request.json.get('pre_execution')
  493. if not file_name:
  494. return jsonify({'error': 'No file name provided'}), 400
  495. file_path = os.path.join(THETA_RHO_DIR, file_name)
  496. if not os.path.exists(file_path):
  497. return jsonify({'error': 'File not found'}), 404
  498. try:
  499. # Build a list of files to run in sequence
  500. files_to_run = []
  501. # Finally, add the main file
  502. files_to_run.append(file_path)
  503. # Run them in one shot using run_theta_rho_files (blocking call)
  504. threading.Thread(
  505. target=run_theta_rho_files,
  506. args=(files_to_run,),
  507. kwargs={
  508. 'pause_time': 0,
  509. 'clear_pattern': pre_execution
  510. }
  511. ).start()
  512. return jsonify({'success': True})
  513. except Exception as e:
  514. return jsonify({'error': str(e)}), 500
  515. def stop_actions():
  516. global pause_requested
  517. with pause_condition:
  518. pause_requested = False
  519. pause_condition.notify_all()
  520. global stop_requested, current_playing_index, current_playlist, is_clearing, current_playing_file, execution_progress
  521. stop_requested = True
  522. current_playing_index = None
  523. current_playlist = None
  524. is_clearing = False
  525. current_playing_file = None
  526. execution_progress = None
  527. @app.route('/stop_execution', methods=['POST'])
  528. def stop_execution():
  529. stop_actions()
  530. return jsonify({'success': True})
  531. @app.route('/send_home', methods=['POST'])
  532. def send_home():
  533. """Send the HOME command to the Arduino."""
  534. try:
  535. send_command("HOME")
  536. return jsonify({'success': True})
  537. except Exception as e:
  538. return jsonify({'error': str(e)}), 500
  539. @app.route('/run_theta_rho_file/<file_name>', methods=['POST'])
  540. def run_specific_theta_rho_file(file_name):
  541. """Run a specific theta-rho file."""
  542. file_path = os.path.join(THETA_RHO_DIR, file_name)
  543. if not os.path.exists(file_path):
  544. return jsonify({'error': 'File not found'}), 404
  545. threading.Thread(target=run_theta_rho_file, args=(file_path,)).start()
  546. return jsonify({'success': True})
  547. @app.route('/delete_theta_rho_file', methods=['POST'])
  548. def delete_theta_rho_file():
  549. data = request.json
  550. file_name = data.get('file_name')
  551. if not file_name:
  552. return jsonify({"success": False, "error": "No file name provided"}), 400
  553. file_path = os.path.join(THETA_RHO_DIR, file_name)
  554. if not os.path.exists(file_path):
  555. return jsonify({"success": False, "error": "File not found"}), 404
  556. try:
  557. os.remove(file_path)
  558. return jsonify({"success": True})
  559. except Exception as e:
  560. return jsonify({"success": False, "error": str(e)}), 500
  561. @app.route('/move_to_center', methods=['POST'])
  562. def move_to_center():
  563. """Move the sand table to the center position."""
  564. try:
  565. if ser is None or not ser.is_open:
  566. return jsonify({"success": False, "error": "Serial connection not established"}), 400
  567. coordinates = [(0, 0)] # Center position
  568. send_coordinate_batch(ser, coordinates)
  569. return jsonify({"success": True})
  570. except Exception as e:
  571. return jsonify({"success": False, "error": str(e)}), 500
  572. @app.route('/move_to_perimeter', methods=['POST'])
  573. def move_to_perimeter():
  574. """Move the sand table to the perimeter position."""
  575. try:
  576. if ser is None or not ser.is_open:
  577. return jsonify({"success": False, "error": "Serial connection not established"}), 400
  578. MAX_RHO = 1
  579. coordinates = [(0, MAX_RHO)] # Perimeter position
  580. send_coordinate_batch(ser, coordinates)
  581. return jsonify({"success": True})
  582. except Exception as e:
  583. return jsonify({"success": False, "error": str(e)}), 500
  584. @app.route('/preview_thr', methods=['POST'])
  585. def preview_thr():
  586. file_name = request.json.get('file_name')
  587. if not file_name:
  588. return jsonify({'error': 'No file name provided'}), 400
  589. file_path = os.path.join(THETA_RHO_DIR, file_name)
  590. if not os.path.exists(file_path):
  591. return jsonify({'error': 'File not found'}), 404
  592. try:
  593. # Parse the .thr file with transformations
  594. coordinates = parse_theta_rho_file(file_path)
  595. return jsonify({'success': True, 'coordinates': coordinates})
  596. except Exception as e:
  597. return jsonify({'error': str(e)}), 500
  598. @app.route('/send_coordinate', methods=['POST'])
  599. def send_coordinate():
  600. """Send a single (theta, rho) coordinate to the Arduino."""
  601. global ser
  602. if ser is None or not ser.is_open:
  603. return jsonify({"success": False, "error": "Serial connection not established"}), 400
  604. try:
  605. data = request.json
  606. theta = data.get('theta')
  607. rho = data.get('rho')
  608. if theta is None or rho is None:
  609. return jsonify({"success": False, "error": "Theta and Rho are required"}), 400
  610. # Send the coordinate to the Arduino
  611. send_coordinate_batch(ser, [(theta, rho)])
  612. return jsonify({"success": True})
  613. except Exception as e:
  614. return jsonify({"success": False, "error": str(e)}), 500
  615. # Expose files for download if needed
  616. @app.route('/download/<filename>', methods=['GET'])
  617. def download_file(filename):
  618. """Download a file from the theta-rho directory."""
  619. return send_from_directory(THETA_RHO_DIR, filename)
  620. @app.route('/serial_status', methods=['GET'])
  621. def serial_status():
  622. global ser, ser_port
  623. return jsonify({
  624. 'connected': ser.is_open if ser else False,
  625. 'port': ser_port # Include the port name
  626. })
  627. @app.route('/pause_execution', methods=['POST'])
  628. def pause_execution():
  629. """Pause the current execution."""
  630. global pause_requested
  631. with pause_condition:
  632. pause_requested = True
  633. return jsonify({'success': True, 'message': 'Execution paused'})
  634. @app.route('/status', methods=['GET'])
  635. def get_status():
  636. """Returns the current status of the sand table."""
  637. global is_clearing
  638. if current_playing_file in CLEAR_PATTERNS.values():
  639. is_clearing = True
  640. else:
  641. is_clearing = False
  642. return jsonify({
  643. "ser_port": ser_port,
  644. "stop_requested": stop_requested,
  645. "pause_requested": pause_requested,
  646. "current_playing_file": current_playing_file,
  647. "execution_progress": execution_progress,
  648. "current_playing_index": current_playing_index,
  649. "current_playlist": current_playlist,
  650. "is_clearing": is_clearing
  651. })
  652. @app.route('/resume_execution', methods=['POST'])
  653. def resume_execution():
  654. """Resume execution after pausing."""
  655. global pause_requested
  656. with pause_condition:
  657. pause_requested = False
  658. pause_condition.notify_all() # Unblock the waiting thread
  659. return jsonify({'success': True, 'message': 'Execution resumed'})
  660. def load_playlists():
  661. """
  662. Load the entire playlists dictionary from the JSON file.
  663. Returns something like: {
  664. "My Playlist": ["file1.thr", "file2.thr"],
  665. "Another": ["x.thr"]
  666. }
  667. """
  668. with open(PLAYLISTS_FILE, "r") as f:
  669. return json.load(f)
  670. def save_playlists(playlists_dict):
  671. """
  672. Save the entire playlists dictionary back to the JSON file.
  673. """
  674. with open(PLAYLISTS_FILE, "w") as f:
  675. json.dump(playlists_dict, f, indent=2)
  676. @app.route("/list_all_playlists", methods=["GET"])
  677. def list_all_playlists():
  678. """
  679. Returns a list of all playlist names.
  680. Example return: ["My Playlist", "Another Playlist"]
  681. """
  682. playlists_dict = load_playlists()
  683. playlist_names = list(playlists_dict.keys())
  684. return jsonify(playlist_names)
  685. @app.route("/get_playlist", methods=["GET"])
  686. def get_playlist():
  687. """
  688. GET /get_playlist?name=My%20Playlist
  689. Returns: { "name": "My Playlist", "files": [... ] }
  690. """
  691. playlist_name = request.args.get("name", "")
  692. if not playlist_name:
  693. return jsonify({"error": "Missing playlist 'name' parameter"}), 400
  694. playlists_dict = load_playlists()
  695. if playlist_name not in playlists_dict:
  696. return jsonify({"error": f"Playlist '{playlist_name}' not found"}), 404
  697. files = playlists_dict[playlist_name] # e.g. ["file1.thr", "file2.thr"]
  698. return jsonify({
  699. "name": playlist_name,
  700. "files": files
  701. })
  702. @app.route("/create_playlist", methods=["POST"])
  703. def create_playlist():
  704. """
  705. POST /create_playlist
  706. Body: { "name": "My Playlist", "files": ["file1.thr", "file2.thr"] }
  707. Creates or overwrites a playlist with the given name.
  708. """
  709. data = request.get_json()
  710. if not data or "name" not in data or "files" not in data:
  711. return jsonify({"success": False, "error": "Playlist 'name' and 'files' are required"}), 400
  712. playlist_name = data["name"]
  713. files = data["files"]
  714. # Load all playlists
  715. playlists_dict = load_playlists()
  716. # Overwrite or create new
  717. playlists_dict[playlist_name] = files
  718. # Save changes
  719. save_playlists(playlists_dict)
  720. return jsonify({
  721. "success": True,
  722. "message": f"Playlist '{playlist_name}' created/updated"
  723. })
  724. @app.route("/modify_playlist", methods=["POST"])
  725. def modify_playlist():
  726. """
  727. POST /modify_playlist
  728. Body: { "name": "My Playlist", "files": ["file1.thr", "file2.thr"] }
  729. Updates (or creates) the existing playlist with a new file list.
  730. You can 404 if you only want to allow modifications to existing playlists.
  731. """
  732. data = request.get_json()
  733. if not data or "name" not in data or "files" not in data:
  734. return jsonify({"success": False, "error": "Playlist 'name' and 'files' are required"}), 400
  735. playlist_name = data["name"]
  736. files = data["files"]
  737. # Load all playlists
  738. playlists_dict = load_playlists()
  739. # Optional: If you want to disallow creating a new playlist here:
  740. # if playlist_name not in playlists_dict:
  741. # return jsonify({"success": False, "error": f"Playlist '{playlist_name}' not found"}), 404
  742. # Overwrite or create new
  743. playlists_dict[playlist_name] = files
  744. # Save
  745. save_playlists(playlists_dict)
  746. return jsonify({"success": True, "message": f"Playlist '{playlist_name}' updated"})
  747. @app.route("/delete_playlist", methods=["DELETE"])
  748. def delete_playlist():
  749. """
  750. DELETE /delete_playlist
  751. Body: { "name": "My Playlist" }
  752. Removes the playlist from the single JSON file.
  753. """
  754. data = request.get_json()
  755. if not data or "name" not in data:
  756. return jsonify({"success": False, "error": "Missing 'name' field"}), 400
  757. playlist_name = data["name"]
  758. playlists_dict = load_playlists()
  759. if playlist_name not in playlists_dict:
  760. return jsonify({"success": False, "error": f"Playlist '{playlist_name}' not found"}), 404
  761. # Remove from dict
  762. del playlists_dict[playlist_name]
  763. save_playlists(playlists_dict)
  764. return jsonify({
  765. "success": True,
  766. "message": f"Playlist '{playlist_name}' deleted"
  767. })
  768. @app.route('/add_to_playlist', methods=['POST'])
  769. def add_to_playlist():
  770. data = request.json
  771. playlist_name = data.get('playlist_name')
  772. pattern = data.get('pattern')
  773. # Load existing playlists
  774. with open('playlists.json', 'r') as f:
  775. playlists = json.load(f)
  776. # Add pattern to the selected playlist
  777. if playlist_name in playlists:
  778. playlists[playlist_name].append(pattern)
  779. with open('playlists.json', 'w') as f:
  780. json.dump(playlists, f)
  781. return jsonify(success=True)
  782. else:
  783. return jsonify(success=False, error='Playlist not found'), 404
  784. @app.route("/run_playlist", methods=["POST"])
  785. def run_playlist():
  786. """
  787. POST /run_playlist
  788. Body (JSON):
  789. {
  790. "playlist_name": "My Playlist",
  791. "pause_time": 1.0, # Optional: seconds to pause between patterns
  792. "clear_pattern": "random", # Optional: "clear_from_in", "clear_from_out", "clear_sideway", "adaptive" or "random"
  793. "run_mode": "single", # 'single' or 'indefinite'
  794. "shuffle": True # true or false
  795. "start_time": ""
  796. "end_time": ""
  797. }
  798. """
  799. data = request.get_json()
  800. # Validate input
  801. if not data or "playlist_name" not in data:
  802. return jsonify({"success": False, "error": "Missing 'playlist_name' field"}), 400
  803. playlist_name = data["playlist_name"]
  804. pause_time = data.get("pause_time", 0)
  805. clear_pattern = data.get("clear_pattern", None)
  806. run_mode = data.get("run_mode", "single") # Default to 'single' run
  807. shuffle = data.get("shuffle", False) # Default to no shuffle
  808. start_time = data.get("start_time", None)
  809. end_time = data.get("end_time", None)
  810. # Validate pause_time
  811. if not isinstance(pause_time, (int, float)) or pause_time < 0:
  812. return jsonify({"success": False, "error": "'pause_time' must be a non-negative number"}), 400
  813. # Validate clear_pattern
  814. valid_patterns = ["clear_from_in", "clear_from_out", "clear_sideway", "random", "adaptive"]
  815. if clear_pattern not in valid_patterns:
  816. clear_pattern = None
  817. # Validate run_mode
  818. if run_mode not in ["single", "indefinite"]:
  819. return jsonify({"success": False, "error": "'run_mode' must be 'single' or 'indefinite'"}), 400
  820. # Validate shuffle
  821. if not isinstance(shuffle, bool):
  822. return jsonify({"success": False, "error": "'shuffle' must be a boolean value"}), 400
  823. schedule_hours = None
  824. if start_time and end_time:
  825. try:
  826. # Convert HH:MM to datetime.time objects
  827. start_time_obj = datetime.strptime(start_time, "%H:%M").time()
  828. end_time_obj = datetime.strptime(end_time, "%H:%M").time()
  829. # Ensure start_time is before end_time
  830. if start_time_obj >= end_time_obj:
  831. return jsonify({"success": False, "error": "'start_time' must be earlier than 'end_time'"}), 400
  832. # Create schedule tuple with full time
  833. schedule_hours = (start_time_obj, end_time_obj)
  834. except ValueError:
  835. return jsonify({"success": False, "error": "Invalid time format. Use HH:MM (e.g., '09:30')"}), 400
  836. # Load playlists
  837. playlists = load_playlists()
  838. if playlist_name not in playlists:
  839. return jsonify({"success": False, "error": f"Playlist '{playlist_name}' not found"}), 404
  840. file_paths = playlists[playlist_name]
  841. file_paths = [os.path.join(THETA_RHO_DIR, file) for file in file_paths]
  842. if not file_paths:
  843. return jsonify({"success": False, "error": f"Playlist '{playlist_name}' is empty"}), 400
  844. # Start the playlist execution in a separate thread
  845. try:
  846. threading.Thread(
  847. target=run_theta_rho_files,
  848. args=(file_paths,),
  849. kwargs={
  850. 'pause_time': pause_time,
  851. 'clear_pattern': clear_pattern,
  852. 'run_mode': run_mode,
  853. 'shuffle': shuffle,
  854. 'schedule_hours': schedule_hours
  855. },
  856. daemon=True # Daemonize thread to exit with the main program
  857. ).start()
  858. return jsonify({"success": True, "message": f"Playlist '{playlist_name}' is now running."})
  859. except Exception as e:
  860. return jsonify({"success": False, "error": str(e)}), 500
  861. @app.route('/set_speed', methods=['POST'])
  862. def set_speed():
  863. """Set the speed for the Arduino."""
  864. global ser
  865. if ser is None or not ser.is_open:
  866. return jsonify({"success": False, "error": "Serial connection not established"}), 400
  867. try:
  868. # Parse the speed value from the request
  869. data = request.json
  870. speed = data.get('speed')
  871. if speed is None:
  872. return jsonify({"success": False, "error": "Speed is required"}), 400
  873. if not isinstance(speed, (int, float)) or speed <= 0:
  874. return jsonify({"success": False, "error": "Invalid speed value"}), 400
  875. # Send the SET_SPEED command to the Arduino
  876. command = f"SET_SPEED {speed}"
  877. send_command(command)
  878. return jsonify({"success": True, "speed": speed})
  879. except Exception as e:
  880. return jsonify({"success": False, "error": str(e)}), 500
  881. @app.route('/get_firmware_info', methods=['GET', 'POST'])
  882. def get_firmware_info():
  883. """
  884. Compare the installed firmware version and motor type with the one in the .ino file.
  885. """
  886. global firmware_version, arduino_driver_type, ser
  887. if ser is None or not ser.is_open:
  888. return jsonify({"success": False, "error": "Arduino not connected or serial port not open"}), 400
  889. try:
  890. if request.method == "GET":
  891. # Attempt to retrieve installed firmware details from the Arduino
  892. time.sleep(0.5)
  893. installed_version = firmware_version
  894. installed_type = arduino_driver_type
  895. # If Arduino provides valid details, proceed with comparison
  896. if installed_version != 'Unknown' and installed_type != 'Unknown':
  897. ino_path = MOTOR_TYPE_MAPPING.get(installed_type)
  898. firmware_details = get_ino_firmware_details(ino_path)
  899. if not firmware_details or not firmware_details.get("version") or not firmware_details.get("motorType"):
  900. return jsonify({"success": False, "error": "Failed to retrieve .ino firmware details"}), 500
  901. update_available = (
  902. installed_version != firmware_details["version"] or
  903. installed_type != firmware_details["motorType"]
  904. )
  905. return jsonify({
  906. "success": True,
  907. "installedVersion": installed_version,
  908. "installedType": installed_type,
  909. "inoVersion": firmware_details["version"],
  910. "inoType": firmware_details["motorType"],
  911. "updateAvailable": update_available
  912. })
  913. # If Arduino details are unknown, indicate the need for POST
  914. return jsonify({
  915. "success": True,
  916. "installedVersion": installed_version,
  917. "installedType": installed_type,
  918. "updateAvailable": False
  919. })
  920. elif request.method == "POST":
  921. motor_type = request.json.get("motorType", None)
  922. if not motor_type or motor_type not in MOTOR_TYPE_MAPPING:
  923. return jsonify({
  924. "success": False,
  925. "error": "Invalid or missing motor type"
  926. }), 400
  927. # Fetch firmware details for the given motor type
  928. ino_path = MOTOR_TYPE_MAPPING[motor_type]
  929. firmware_details = get_ino_firmware_details(ino_path)
  930. if not firmware_details:
  931. return jsonify({
  932. "success": False,
  933. "error": "Failed to retrieve .ino firmware details"
  934. }), 500
  935. return jsonify({
  936. "success": True,
  937. "installedVersion": 'Unknown',
  938. "installedType": motor_type,
  939. "inoVersion": firmware_details["version"],
  940. "inoType": firmware_details["motorType"],
  941. "updateAvailable": True
  942. })
  943. except Exception as e:
  944. return jsonify({"success": False, "error": str(e)}), 500
  945. @app.route('/flash_firmware', methods=['POST'])
  946. def flash_firmware():
  947. """
  948. Flash the pre-compiled firmware to the connected device (Arduino or ESP32).
  949. """
  950. global ser_port
  951. # Ensure the device is connected
  952. if ser_port is None or ser is None or not ser.is_open:
  953. return jsonify({"success": False, "error": "No device connected or connection lost"}), 400
  954. try:
  955. data = request.json
  956. motor_type = data.get("motorType", None)
  957. # Validate motor type
  958. if not motor_type or motor_type not in MOTOR_TYPE_MAPPING:
  959. return jsonify({"success": False, "error": "Invalid or missing motor type"}), 400
  960. # Determine the firmware file
  961. ino_file_path = MOTOR_TYPE_MAPPING[motor_type] # Path to .ino file
  962. hex_file_path = f"{ino_file_path}.hex"
  963. bin_file_path = f"{ino_file_path}.bin" # For ESP32 firmware
  964. # Check the device type
  965. if motor_type.lower() == "esp32":
  966. if not os.path.exists(bin_file_path):
  967. return jsonify({"success": False, "error": f"Firmware binary not found: {bin_file_path}"}), 404
  968. # Flash ESP32 firmware
  969. flash_command = [
  970. "esptool.py",
  971. "--chip", "esp32",
  972. "--port", ser_port,
  973. "--baud", "115200",
  974. "write_flash", "-z", "0x1000", bin_file_path
  975. ]
  976. else:
  977. if not os.path.exists(hex_file_path):
  978. return jsonify({"success": False, "error": f"Hex file not found: {hex_file_path}"}), 404
  979. # Flash Arduino firmware
  980. flash_command = [
  981. "avrdude",
  982. "-v",
  983. "-c", "arduino",
  984. "-p", "atmega328p",
  985. "-P", ser_port,
  986. "-b", "115200",
  987. "-D",
  988. "-U", f"flash:w:{hex_file_path}:i"
  989. ]
  990. # Execute the flash command
  991. flash_process = subprocess.run(flash_command, capture_output=True, text=True)
  992. if flash_process.returncode != 0:
  993. return jsonify({
  994. "success": False,
  995. "error": flash_process.stderr
  996. }), 500
  997. return jsonify({"success": True, "message": "Firmware flashed successfully"})
  998. except Exception as e:
  999. return jsonify({"success": False, "error": str(e)}), 500
  1000. @app.route('/check_software_update', methods=['GET'])
  1001. def check_updates():
  1002. update_info = check_git_updates()
  1003. return jsonify(update_info)
  1004. @app.route('/update_software', methods=['POST'])
  1005. def update_software():
  1006. error_log = []
  1007. def run_command(command, error_message):
  1008. try:
  1009. subprocess.run(command, check=True)
  1010. except subprocess.CalledProcessError as e:
  1011. print(f"{error_message}: {e}")
  1012. error_log.append(error_message)
  1013. # Fetch the latest version tag from remote
  1014. try:
  1015. subprocess.run(["git", "fetch", "--tags"], check=True)
  1016. latest_remote_tag = subprocess.check_output(
  1017. ["git", "describe", "--tags", "--abbrev=0", "origin/main"]
  1018. ).strip().decode()
  1019. except subprocess.CalledProcessError as e:
  1020. error_log.append(f"Failed to fetch tags or get latest remote tag: {e}")
  1021. return jsonify({
  1022. "success": False,
  1023. "error": "Failed to fetch tags or determine the latest version.",
  1024. "details": error_log
  1025. }), 500
  1026. # Checkout the latest tag
  1027. run_command(["git", "checkout", latest_remote_tag, '--force'], f"Failed to checkout version {latest_remote_tag}")
  1028. # Restart Docker containers
  1029. run_command(["docker", "compose", "up", "-d"], "Failed to restart Docker containers")
  1030. # Check if the update was successful
  1031. update_status = check_git_updates()
  1032. if (
  1033. update_status["updates_available"] is False
  1034. and update_status["latest_local_tag"] == update_status["latest_remote_tag"]
  1035. ):
  1036. # Update was successful
  1037. return jsonify({"success": True})
  1038. else:
  1039. # Update failed; include the errors in the response
  1040. return jsonify({
  1041. "success": False,
  1042. "error": "Update incomplete",
  1043. "details": error_log
  1044. }), 500
  1045. def on_exit():
  1046. """Function to execute on application shutdown."""
  1047. print("Shutting down the application...")
  1048. stop_actions()
  1049. time.sleep(5)
  1050. print("Execution stopped and resources cleaned up.")
  1051. # Register the on_exit function
  1052. atexit.register(on_exit)
  1053. if __name__ == '__main__':
  1054. # Auto-connect to serial
  1055. connect_to_serial()
  1056. try:
  1057. app.run(debug=False, host='0.0.0.0', port=8080)
  1058. except KeyboardInterrupt:
  1059. print("Keyboard interrupt received. Shutting down.")
  1060. finally:
  1061. on_exit() # Ensure cleanup if app is interrupted