app.py 44 KB

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