app.py 25 KB

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