app.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  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. app = Flask(__name__)
  11. # Configuration
  12. THETA_RHO_DIR = './patterns'
  13. IGNORE_PORTS = ['/dev/cu.debug-console', '/dev/cu.Bluetooth-Incoming-Port']
  14. CLEAR_PATTERNS = {
  15. "clear_from_in": "./patterns/clear_from_in.thr",
  16. "clear_from_out": "./patterns/clear_from_out.thr",
  17. "clear_sideway": "./patterns/clear_sideway.thr"
  18. }
  19. os.makedirs(THETA_RHO_DIR, exist_ok=True)
  20. # Serial connection (First available will be selected by default)
  21. ser = None
  22. ser_port = None # Global variable to store the serial port name
  23. stop_requested = False
  24. serial_lock = threading.Lock()
  25. PLAYLISTS_FILE = os.path.join(os.getcwd(), "playlists.json")
  26. # Ensure the file exists and contains at least an empty JSON object
  27. if not os.path.exists(PLAYLISTS_FILE):
  28. with open(PLAYLISTS_FILE, "w") as f:
  29. json.dump({}, f, indent=2)
  30. def list_serial_ports():
  31. """Return a list of available serial ports."""
  32. ports = serial.tools.list_ports.comports()
  33. return [port.device for port in ports if port.device not in IGNORE_PORTS]
  34. def connect_to_serial(port=None, baudrate=115200):
  35. """Automatically connect to the first available serial port or a specified port."""
  36. global ser, ser_port
  37. try:
  38. if port is None:
  39. ports = list_serial_ports()
  40. if not ports:
  41. print("No serial port connected")
  42. return False
  43. port = ports[0] # Auto-select the first available port
  44. with serial_lock:
  45. if ser and ser.is_open:
  46. ser.close()
  47. ser = serial.Serial(port, baudrate)
  48. ser_port = port # Store the connected port globally
  49. print(f"Connected to serial port: {port}")
  50. time.sleep(2) # Allow time for the connection to establish
  51. return True # Successfully connected
  52. except serial.SerialException as e:
  53. print(f"Failed to connect to serial port {port}: {e}")
  54. port = None # Reset the port to try the next available one
  55. print("Max retries reached. Could not connect to a serial port.")
  56. return False
  57. def disconnect_serial():
  58. """Disconnect the current serial connection."""
  59. global ser, ser_port
  60. if ser and ser.is_open:
  61. ser.close()
  62. ser = None
  63. ser_port = None # Reset the port name
  64. def restart_serial(port, baudrate=115200):
  65. """Restart the serial connection."""
  66. disconnect_serial()
  67. connect_to_serial(port, baudrate)
  68. def parse_theta_rho_file(file_path):
  69. """
  70. Parse a theta-rho file and return a list of (theta, rho) pairs.
  71. Normalizes the list so the first theta is always 0.
  72. """
  73. coordinates = []
  74. try:
  75. with open(file_path, 'r') as file:
  76. for line in file:
  77. line = line.strip()
  78. # Skip header or comment lines (starting with '#' or empty lines)
  79. if not line or line.startswith("#"):
  80. continue
  81. # Parse lines with theta and rho separated by spaces
  82. try:
  83. theta, rho = map(float, line.split())
  84. coordinates.append((theta, rho))
  85. except ValueError:
  86. print(f"Skipping invalid line: {line}")
  87. continue
  88. except Exception as e:
  89. print(f"Error reading file: {e}")
  90. return coordinates
  91. return coordinates
  92. def send_coordinate_batch(ser, coordinates):
  93. """Send a batch of theta-rho pairs to the Arduino."""
  94. # print("Sending batch:", coordinates)
  95. batch_str = ";".join(f"{theta:.5f},{rho:.5f}" for theta, rho in coordinates) + ";\n"
  96. ser.write(batch_str.encode())
  97. def send_command(command):
  98. """Send a single command to the Arduino."""
  99. ser.write(f"{command}\n".encode())
  100. print(f"Sent: {command}")
  101. # Wait for "DONE" acknowledgment from Arduino
  102. while True:
  103. with serial_lock:
  104. if ser.in_waiting > 0:
  105. response = ser.readline().decode().strip()
  106. print(f"Arduino response: {response}")
  107. if response == "DONE":
  108. print("Command execution completed.")
  109. break
  110. def run_theta_rho_file(file_path):
  111. """Run a theta-rho file by sending data in optimized batches."""
  112. global stop_requested
  113. stop_requested = False
  114. coordinates = parse_theta_rho_file(file_path)
  115. if len(coordinates) < 2:
  116. print("Not enough coordinates for interpolation.")
  117. return
  118. # Optimize batch size for smoother execution
  119. batch_size = 10 # Smaller batches may smooth movement further
  120. for i in range(0, len(coordinates), batch_size):
  121. # Check stop_requested flag after sending the batch
  122. if stop_requested:
  123. print("Execution stopped by user after completing the current batch.")
  124. break
  125. batch = coordinates[i:i + batch_size]
  126. if i == 0:
  127. send_coordinate_batch(ser, batch)
  128. continue
  129. # Wait until Arduino is READY before sending the batch
  130. while True:
  131. with serial_lock:
  132. if ser.in_waiting > 0:
  133. response = ser.readline().decode().strip()
  134. if response == "R":
  135. send_coordinate_batch(ser, batch)
  136. break
  137. else:
  138. print(f"Arduino response: {response}")
  139. # Reset theta after execution or stopping
  140. reset_theta()
  141. ser.write("FINISHED\n".encode())
  142. def get_clear_pattern_file(pattern_name):
  143. """Return a .thr file path based on pattern_name."""
  144. if pattern_name == "random":
  145. # Randomly pick one of the three known patterns
  146. return random.choice(list(CLEAR_PATTERNS.values()))
  147. # If pattern_name is invalid or absent, default to 'clear_from_in'
  148. return CLEAR_PATTERNS.get(pattern_name, CLEAR_PATTERNS["clear_from_in"])
  149. def run_theta_rho_files(
  150. file_paths,
  151. pause_time=0,
  152. clear_pattern=None,
  153. run_mode="single",
  154. shuffle=False
  155. ):
  156. """
  157. Runs multiple .thr files in sequence with options for pausing, clearing, shuffling, and looping.
  158. Parameters:
  159. - file_paths (list): List of file paths to run.
  160. - pause_time (float): Seconds to pause between patterns.
  161. - clear_pattern (str): Specific clear pattern to run ("clear_in", "clear_out", "clear_sideway", or "random").
  162. - run_mode (str): "single" for one-time run or "indefinite" for looping.
  163. - shuffle (bool): Whether to shuffle the playlist before running.
  164. """
  165. global stop_requested
  166. stop_requested = False # Reset stop flag at the start
  167. if shuffle:
  168. random.shuffle(file_paths)
  169. print("Playlist shuffled.")
  170. while True:
  171. for idx, path in enumerate(file_paths):
  172. if stop_requested:
  173. print("Execution stopped before starting next pattern.")
  174. return
  175. # Run the main pattern
  176. print(f"Running pattern {idx + 1} of {len(file_paths)}: {path}")
  177. run_theta_rho_file(path)
  178. if idx < len(file_paths) -1:
  179. if stop_requested:
  180. print("Execution stopped before running the next clear pattern.")
  181. return
  182. # Pause after each pattern if requested
  183. if pause_time > 0:
  184. print(f"Pausing for {pause_time} seconds...")
  185. time.sleep(pause_time)
  186. if clear_pattern:
  187. if stop_requested:
  188. print("Execution stopped before running the next clear pattern.")
  189. return
  190. # Determine the clear pattern to run
  191. clear_file_path = get_clear_pattern_file(clear_pattern)
  192. print(f"Running clear pattern: {clear_file_path}")
  193. run_theta_rho_file(clear_file_path)
  194. # After completing the playlist
  195. if run_mode == "indefinite":
  196. print("Playlist completed. Restarting as per 'indefinite' run mode.")
  197. if pause_time > 0:
  198. print(f"Pausing for {pause_time} seconds before restarting...")
  199. time.sleep(pause_time)
  200. if shuffle:
  201. random.shuffle(file_paths)
  202. print("Playlist reshuffled for the next loop.")
  203. continue
  204. else:
  205. print("Playlist completed.")
  206. break
  207. # Reset theta after execution or stopping
  208. reset_theta()
  209. ser.write("FINISHED\n".encode())
  210. print("All requested patterns completed (or stopped).")
  211. def reset_theta():
  212. """Reset theta on the Arduino."""
  213. ser.write("RESET_THETA\n".encode())
  214. while True:
  215. with serial_lock:
  216. if ser.in_waiting > 0:
  217. response = ser.readline().decode().strip()
  218. print(f"Arduino response: {response}")
  219. if response == "THETA_RESET":
  220. print("Theta successfully reset.")
  221. break
  222. time.sleep(0.5) # Small delay to avoid busy waiting
  223. # Flask API Endpoints
  224. @app.route('/')
  225. def index():
  226. return render_template('index.html')
  227. @app.route('/list_serial_ports', methods=['GET'])
  228. def list_ports():
  229. return jsonify(list_serial_ports())
  230. @app.route('/connect_serial', methods=['POST'])
  231. def connect_serial():
  232. port = request.json.get('port')
  233. if not port:
  234. return jsonify({'error': 'No port provided'}), 400
  235. try:
  236. connect_to_serial(port)
  237. return jsonify({'success': True})
  238. except Exception as e:
  239. return jsonify({'error': str(e)}), 500
  240. @app.route('/disconnect_serial', methods=['POST'])
  241. def disconnect():
  242. try:
  243. disconnect_serial()
  244. return jsonify({'success': True})
  245. except Exception as e:
  246. return jsonify({'error': str(e)}), 500
  247. @app.route('/restart_serial', methods=['POST'])
  248. def restart():
  249. port = request.json.get('port')
  250. if not port:
  251. return jsonify({'error': 'No port provided'}), 400
  252. try:
  253. restart_serial(port)
  254. return jsonify({'success': True})
  255. except Exception as e:
  256. return jsonify({'error': str(e)}), 500
  257. @app.route('/list_theta_rho_files', methods=['GET'])
  258. def list_theta_rho_files():
  259. files = []
  260. for root, _, filenames in os.walk(THETA_RHO_DIR):
  261. for file in filenames:
  262. # Construct the relative file path
  263. relative_path = os.path.relpath(os.path.join(root, file), THETA_RHO_DIR)
  264. files.append(relative_path)
  265. return jsonify(sorted(files))
  266. @app.route('/upload_theta_rho', methods=['POST'])
  267. def upload_theta_rho():
  268. custom_patterns_dir = os.path.join(THETA_RHO_DIR, 'custom_patterns')
  269. os.makedirs(custom_patterns_dir, exist_ok=True) # Ensure the directory exists
  270. file = request.files['file']
  271. if file:
  272. file.save(os.path.join(custom_patterns_dir, file.filename))
  273. return jsonify({'success': True})
  274. return jsonify({'success': False})
  275. @app.route('/run_theta_rho', methods=['POST'])
  276. def run_theta_rho():
  277. file_name = request.json.get('file_name')
  278. pre_execution = request.json.get('pre_execution') # 'clear_in', 'clear_out', or 'none'
  279. if not file_name:
  280. return jsonify({'error': 'No file name provided'}), 400
  281. file_path = os.path.join(THETA_RHO_DIR, file_name)
  282. if not os.path.exists(file_path):
  283. return jsonify({'error': 'File not found'}), 404
  284. try:
  285. # Build a list of files to run in sequence
  286. files_to_run = []
  287. if pre_execution == 'clear_in':
  288. files_to_run.append('./patterns/clear_from_in.thr')
  289. elif pre_execution == 'clear_out':
  290. files_to_run.append('./patterns/clear_from_out.thr')
  291. elif pre_execution == 'clear_sideway':
  292. files_to_run.append('./patterns/clear_sideway.thr')
  293. elif pre_execution == 'none':
  294. pass # No pre-execution action required
  295. # Finally, add the main file
  296. files_to_run.append(file_path)
  297. # Run them in one shot using run_theta_rho_files (blocking call)
  298. threading.Thread(
  299. target=run_theta_rho_files,
  300. args=(files_to_run,),
  301. kwargs={
  302. 'pause_time': 0,
  303. 'clear_pattern': None
  304. }
  305. ).start()
  306. return jsonify({'success': True})
  307. except Exception as e:
  308. return jsonify({'error': str(e)}), 500
  309. @app.route('/stop_execution', methods=['POST'])
  310. def stop_execution():
  311. global stop_requested
  312. stop_requested = True
  313. return jsonify({'success': True})
  314. @app.route('/send_home', methods=['POST'])
  315. def send_home():
  316. """Send the HOME command to the Arduino."""
  317. try:
  318. send_command("HOME")
  319. return jsonify({'success': True})
  320. except Exception as e:
  321. return jsonify({'error': str(e)}), 500
  322. @app.route('/run_theta_rho_file/<file_name>', methods=['POST'])
  323. def run_specific_theta_rho_file(file_name):
  324. """Run a specific theta-rho file."""
  325. file_path = os.path.join(THETA_RHO_DIR, file_name)
  326. if not os.path.exists(file_path):
  327. return jsonify({'error': 'File not found'}), 404
  328. threading.Thread(target=run_theta_rho_file, args=(file_path,)).start()
  329. return jsonify({'success': True})
  330. @app.route('/delete_theta_rho_file', methods=['POST'])
  331. def delete_theta_rho_file():
  332. data = request.json
  333. file_name = data.get('file_name')
  334. if not file_name:
  335. return jsonify({"success": False, "error": "No file name provided"}), 400
  336. file_path = os.path.join(THETA_RHO_DIR, file_name)
  337. if not os.path.exists(file_path):
  338. return jsonify({"success": False, "error": "File not found"}), 404
  339. try:
  340. os.remove(file_path)
  341. return jsonify({"success": True})
  342. except Exception as e:
  343. return jsonify({"success": False, "error": str(e)}), 500
  344. @app.route('/move_to_center', methods=['POST'])
  345. def move_to_center():
  346. """Move the sand table to the center position."""
  347. try:
  348. if ser is None or not ser.is_open:
  349. return jsonify({"success": False, "error": "Serial connection not established"}), 400
  350. coordinates = [(0, 0)] # Center position
  351. send_coordinate_batch(ser, coordinates)
  352. return jsonify({"success": True})
  353. except Exception as e:
  354. return jsonify({"success": False, "error": str(e)}), 500
  355. @app.route('/move_to_perimeter', methods=['POST'])
  356. def move_to_perimeter():
  357. """Move the sand table to the perimeter position."""
  358. try:
  359. if ser is None or not ser.is_open:
  360. return jsonify({"success": False, "error": "Serial connection not established"}), 400
  361. MAX_RHO = 1
  362. coordinates = [(0, MAX_RHO)] # Perimeter position
  363. send_coordinate_batch(ser, coordinates)
  364. return jsonify({"success": True})
  365. except Exception as e:
  366. return jsonify({"success": False, "error": str(e)}), 500
  367. @app.route('/preview_thr', methods=['POST'])
  368. def preview_thr():
  369. file_name = request.json.get('file_name')
  370. if not file_name:
  371. return jsonify({'error': 'No file name provided'}), 400
  372. file_path = os.path.join(THETA_RHO_DIR, file_name)
  373. if not os.path.exists(file_path):
  374. return jsonify({'error': 'File not found'}), 404
  375. try:
  376. # Parse the .thr file with transformations
  377. coordinates = parse_theta_rho_file(file_path)
  378. return jsonify({'success': True, 'coordinates': coordinates})
  379. except Exception as e:
  380. return jsonify({'error': str(e)}), 500
  381. @app.route('/send_coordinate', methods=['POST'])
  382. def send_coordinate():
  383. """Send a single (theta, rho) coordinate to the Arduino."""
  384. global ser
  385. if ser is None or not ser.is_open:
  386. return jsonify({"success": False, "error": "Serial connection not established"}), 400
  387. try:
  388. data = request.json
  389. theta = data.get('theta')
  390. rho = data.get('rho')
  391. if theta is None or rho is None:
  392. return jsonify({"success": False, "error": "Theta and Rho are required"}), 400
  393. # Send the coordinate to the Arduino
  394. send_coordinate_batch(ser, [(theta, rho)])
  395. reset_theta()
  396. return jsonify({"success": True})
  397. except Exception as e:
  398. return jsonify({"success": False, "error": str(e)}), 500
  399. # Expose files for download if needed
  400. @app.route('/download/<filename>', methods=['GET'])
  401. def download_file(filename):
  402. """Download a file from the theta-rho directory."""
  403. return send_from_directory(THETA_RHO_DIR, filename)
  404. @app.route('/serial_status', methods=['GET'])
  405. def serial_status():
  406. global ser, ser_port
  407. return jsonify({
  408. 'connected': ser.is_open if ser else False,
  409. 'port': ser_port # Include the port name
  410. })
  411. if not os.path.exists(PLAYLISTS_FILE):
  412. with open(PLAYLISTS_FILE, "w") as f:
  413. json.dump({}, f, indent=2)
  414. def load_playlists():
  415. """
  416. Load the entire playlists dictionary from the JSON file.
  417. Returns something like: {
  418. "My Playlist": ["file1.thr", "file2.thr"],
  419. "Another": ["x.thr"]
  420. }
  421. """
  422. with open(PLAYLISTS_FILE, "r") as f:
  423. return json.load(f)
  424. def save_playlists(playlists_dict):
  425. """
  426. Save the entire playlists dictionary back to the JSON file.
  427. """
  428. with open(PLAYLISTS_FILE, "w") as f:
  429. json.dump(playlists_dict, f, indent=2)
  430. @app.route("/list_all_playlists", methods=["GET"])
  431. def list_all_playlists():
  432. """
  433. Returns a list of all playlist names.
  434. Example return: ["My Playlist", "Another Playlist"]
  435. """
  436. playlists_dict = load_playlists()
  437. playlist_names = list(playlists_dict.keys())
  438. return jsonify(playlist_names)
  439. @app.route("/get_playlist", methods=["GET"])
  440. def get_playlist():
  441. """
  442. GET /get_playlist?name=My%20Playlist
  443. Returns: { "name": "My Playlist", "files": [... ] }
  444. """
  445. playlist_name = request.args.get("name", "")
  446. if not playlist_name:
  447. return jsonify({"error": "Missing playlist 'name' parameter"}), 400
  448. playlists_dict = load_playlists()
  449. if playlist_name not in playlists_dict:
  450. return jsonify({"error": f"Playlist '{playlist_name}' not found"}), 404
  451. files = playlists_dict[playlist_name] # e.g. ["file1.thr", "file2.thr"]
  452. return jsonify({
  453. "name": playlist_name,
  454. "files": files
  455. })
  456. @app.route("/create_playlist", methods=["POST"])
  457. def create_playlist():
  458. """
  459. POST /create_playlist
  460. Body: { "name": "My Playlist", "files": ["file1.thr", "file2.thr"] }
  461. Creates or overwrites a playlist with the given name.
  462. """
  463. data = request.get_json()
  464. if not data or "name" not in data or "files" not in data:
  465. return jsonify({"success": False, "error": "Playlist 'name' and 'files' are required"}), 400
  466. playlist_name = data["name"]
  467. files = data["files"]
  468. # Load all playlists
  469. playlists_dict = load_playlists()
  470. # Overwrite or create new
  471. playlists_dict[playlist_name] = files
  472. # Save changes
  473. save_playlists(playlists_dict)
  474. return jsonify({
  475. "success": True,
  476. "message": f"Playlist '{playlist_name}' created/updated"
  477. })
  478. @app.route("/modify_playlist", methods=["POST"])
  479. def modify_playlist():
  480. """
  481. POST /modify_playlist
  482. Body: { "name": "My Playlist", "files": ["file1.thr", "file2.thr"] }
  483. Updates (or creates) the existing playlist with a new file list.
  484. You can 404 if you only want to allow modifications to existing playlists.
  485. """
  486. data = request.get_json()
  487. if not data or "name" not in data or "files" not in data:
  488. return jsonify({"success": False, "error": "Playlist 'name' and 'files' are required"}), 400
  489. playlist_name = data["name"]
  490. files = data["files"]
  491. # Load all playlists
  492. playlists_dict = load_playlists()
  493. # Optional: If you want to disallow creating a new playlist here:
  494. # if playlist_name not in playlists_dict:
  495. # return jsonify({"success": False, "error": f"Playlist '{playlist_name}' not found"}), 404
  496. # Overwrite or create new
  497. playlists_dict[playlist_name] = files
  498. # Save
  499. save_playlists(playlists_dict)
  500. return jsonify({"success": True, "message": f"Playlist '{playlist_name}' updated"})
  501. @app.route("/delete_playlist", methods=["DELETE"])
  502. def delete_playlist():
  503. """
  504. DELETE /delete_playlist
  505. Body: { "name": "My Playlist" }
  506. Removes the playlist from the single JSON file.
  507. """
  508. data = request.get_json()
  509. if not data or "name" not in data:
  510. return jsonify({"success": False, "error": "Missing 'name' field"}), 400
  511. playlist_name = data["name"]
  512. playlists_dict = load_playlists()
  513. if playlist_name not in playlists_dict:
  514. return jsonify({"success": False, "error": f"Playlist '{playlist_name}' not found"}), 404
  515. # Remove from dict
  516. del playlists_dict[playlist_name]
  517. save_playlists(playlists_dict)
  518. return jsonify({
  519. "success": True,
  520. "message": f"Playlist '{playlist_name}' deleted"
  521. })
  522. @app.route("/run_playlist", methods=["POST"])
  523. def run_playlist():
  524. """
  525. POST /run_playlist
  526. Body (JSON):
  527. {
  528. "playlist_name": "My Playlist",
  529. "pause_time": 1.0, # Optional: seconds to pause between patterns
  530. "clear_pattern": "random", # Optional: "clear_in", "clear_out", "clear_sideway", or "random"
  531. "run_mode": "single", # 'single' or 'indefinite'
  532. "shuffle": True # true or false
  533. }
  534. """
  535. data = request.get_json()
  536. # Validate input
  537. if not data or "playlist_name" not in data:
  538. return jsonify({"success": False, "error": "Missing 'playlist_name' field"}), 400
  539. playlist_name = data["playlist_name"]
  540. pause_time = data.get("pause_time", 0)
  541. clear_pattern = data.get("clear_pattern", None)
  542. run_mode = data.get("run_mode", "single") # Default to 'single' run
  543. shuffle = data.get("shuffle", False) # Default to no shuffle
  544. # Validate pause_time
  545. if not isinstance(pause_time, (int, float)) or pause_time < 0:
  546. return jsonify({"success": False, "error": "'pause_time' must be a non-negative number"}), 400
  547. # Validate clear_pattern
  548. valid_patterns = ["clear_in", "clear_out", "clear_sideway", "random"]
  549. if clear_pattern not in valid_patterns:
  550. clear_pattern = None
  551. # Validate run_mode
  552. if run_mode not in ["single", "indefinite"]:
  553. return jsonify({"success": False, "error": "'run_mode' must be 'single' or 'indefinite'"}), 400
  554. # Validate shuffle
  555. if not isinstance(shuffle, bool):
  556. return jsonify({"success": False, "error": "'shuffle' must be a boolean value"}), 400
  557. # Load playlists
  558. playlists = load_playlists()
  559. if playlist_name not in playlists:
  560. return jsonify({"success": False, "error": f"Playlist '{playlist_name}' not found"}), 404
  561. file_paths = playlists[playlist_name]
  562. file_paths = [os.path.join(THETA_RHO_DIR, file) for file in file_paths]
  563. if not file_paths:
  564. return jsonify({"success": False, "error": f"Playlist '{playlist_name}' is empty"}), 400
  565. # Start the playlist execution in a separate thread
  566. try:
  567. threading.Thread(
  568. target=run_theta_rho_files,
  569. args=(file_paths,),
  570. kwargs={
  571. 'pause_time': pause_time,
  572. 'clear_pattern': clear_pattern,
  573. 'run_mode': run_mode,
  574. 'shuffle': shuffle
  575. },
  576. daemon=True # Daemonize thread to exit with the main program
  577. ).start()
  578. return jsonify({"success": True, "message": f"Playlist '{playlist_name}' is now running."})
  579. except Exception as e:
  580. return jsonify({"success": False, "error": str(e)}), 500
  581. if __name__ == '__main__':
  582. app.run(debug=True, host='0.0.0.0', port=8080)