app.py 43 KB

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