app.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  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. 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('/add_to_playlist', methods=['POST'])
  533. def add_to_playlist():
  534. data = request.json
  535. playlist_name = data.get('playlist_name')
  536. pattern = data.get('pattern')
  537. # Load existing playlists
  538. with open('playlists.json', 'r') as f:
  539. playlists = json.load(f)
  540. # Add pattern to the selected playlist
  541. if playlist_name in playlists:
  542. playlists[playlist_name].append(pattern)
  543. with open('playlists.json', 'w') as f:
  544. json.dump(playlists, f)
  545. return jsonify(success=True)
  546. else:
  547. return jsonify(success=False, error='Playlist not found'), 404
  548. @app.route("/run_playlist", methods=["POST"])
  549. def run_playlist():
  550. """
  551. POST /run_playlist
  552. Body (JSON):
  553. {
  554. "playlist_name": "My Playlist",
  555. "pause_time": 1.0, # Optional: seconds to pause between patterns
  556. "clear_pattern": "random", # Optional: "clear_in", "clear_out", "clear_sideway", or "random"
  557. "run_mode": "single", # 'single' or 'indefinite'
  558. "shuffle": True # true or false
  559. }
  560. """
  561. data = request.get_json()
  562. # Validate input
  563. if not data or "playlist_name" not in data:
  564. return jsonify({"success": False, "error": "Missing 'playlist_name' field"}), 400
  565. playlist_name = data["playlist_name"]
  566. pause_time = data.get("pause_time", 0)
  567. clear_pattern = data.get("clear_pattern", None)
  568. run_mode = data.get("run_mode", "single") # Default to 'single' run
  569. shuffle = data.get("shuffle", False) # Default to no shuffle
  570. # Validate pause_time
  571. if not isinstance(pause_time, (int, float)) or pause_time < 0:
  572. return jsonify({"success": False, "error": "'pause_time' must be a non-negative number"}), 400
  573. # Validate clear_pattern
  574. valid_patterns = ["clear_in", "clear_out", "clear_sideway", "random"]
  575. if clear_pattern not in valid_patterns:
  576. clear_pattern = None
  577. # Validate run_mode
  578. if run_mode not in ["single", "indefinite"]:
  579. return jsonify({"success": False, "error": "'run_mode' must be 'single' or 'indefinite'"}), 400
  580. # Validate shuffle
  581. if not isinstance(shuffle, bool):
  582. return jsonify({"success": False, "error": "'shuffle' must be a boolean value"}), 400
  583. # Load playlists
  584. playlists = load_playlists()
  585. if playlist_name not in playlists:
  586. return jsonify({"success": False, "error": f"Playlist '{playlist_name}' not found"}), 404
  587. file_paths = playlists[playlist_name]
  588. file_paths = [os.path.join(THETA_RHO_DIR, file) for file in file_paths]
  589. if not file_paths:
  590. return jsonify({"success": False, "error": f"Playlist '{playlist_name}' is empty"}), 400
  591. # Start the playlist execution in a separate thread
  592. try:
  593. threading.Thread(
  594. target=run_theta_rho_files,
  595. args=(file_paths,),
  596. kwargs={
  597. 'pause_time': pause_time,
  598. 'clear_pattern': clear_pattern,
  599. 'run_mode': run_mode,
  600. 'shuffle': shuffle
  601. },
  602. daemon=True # Daemonize thread to exit with the main program
  603. ).start()
  604. return jsonify({"success": True, "message": f"Playlist '{playlist_name}' is now running."})
  605. except Exception as e:
  606. return jsonify({"success": False, "error": str(e)}), 500
  607. @app.route('/set_speed', methods=['POST'])
  608. def set_speed():
  609. """Set the speed for the Arduino."""
  610. global ser
  611. if ser is None or not ser.is_open:
  612. return jsonify({"success": False, "error": "Serial connection not established"}), 400
  613. try:
  614. # Parse the speed value from the request
  615. data = request.json
  616. speed = data.get('speed')
  617. if speed is None:
  618. return jsonify({"success": False, "error": "Speed is required"}), 400
  619. if not isinstance(speed, (int, float)) or speed <= 0:
  620. return jsonify({"success": False, "error": "Invalid speed value"}), 400
  621. # Send the SET_SPEED command to the Arduino
  622. command = f"SET_SPEED {speed}"
  623. send_command(command)
  624. return jsonify({"success": True, "speed": speed})
  625. except Exception as e:
  626. return jsonify({"success": False, "error": str(e)}), 500
  627. if __name__ == '__main__':
  628. # Auto-connect to serial
  629. connect_to_serial()
  630. app.run(debug=True, host='0.0.0.0', port=8080)