1
0

app.py 25 KB

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