app.py 45 KB

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