app.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  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. from datetime import datetime
  11. app = Flask(__name__)
  12. # Configuration
  13. THETA_RHO_DIR = './patterns'
  14. IGNORE_PORTS = ['/dev/cu.debug-console', '/dev/cu.Bluetooth-Incoming-Port']
  15. CLEAR_PATTERNS = {
  16. "clear_from_in": "./patterns/clear_from_in.thr",
  17. "clear_from_out": "./patterns/clear_from_out.thr",
  18. "clear_sideway": "./patterns/clear_sideway.thr"
  19. }
  20. os.makedirs(THETA_RHO_DIR, exist_ok=True)
  21. # Serial connection (First available will be selected by default)
  22. ser = None
  23. ser_port = None # Global variable to store the serial port name
  24. stop_requested = False
  25. pause_requested = False
  26. current_playing_file = None
  27. execution_progress = None
  28. pause_condition = threading.Condition()
  29. # Global variables to store device information
  30. arduino_table_name = None
  31. arduino_driver_type = None
  32. serial_lock = threading.Lock()
  33. PLAYLISTS_FILE = os.path.join(os.getcwd(), "playlists.json")
  34. # Ensure the file exists and contains at least an empty JSON object
  35. if not os.path.exists(PLAYLISTS_FILE):
  36. with open(PLAYLISTS_FILE, "w") as f:
  37. json.dump({}, f, indent=2)
  38. def list_serial_ports():
  39. """Return a list of available serial ports."""
  40. ports = serial.tools.list_ports.comports()
  41. return [port.device for port in ports if port.device not in IGNORE_PORTS]
  42. def connect_to_serial(port=None, baudrate=115200):
  43. """Automatically connect to the first available serial port or a specified port."""
  44. global ser, ser_port, arduino_table_name, arduino_driver_type
  45. try:
  46. if port is None:
  47. ports = list_serial_ports()
  48. if not ports:
  49. print("No serial port connected")
  50. return False
  51. port = ports[0] # Auto-select the first available port
  52. with serial_lock:
  53. if ser and ser.is_open:
  54. ser.close()
  55. ser = serial.Serial(port, baudrate, timeout=2) # Set timeout to avoid infinite waits
  56. ser_port = port # Store the connected port globally
  57. print(f"Connected to serial port: {port}")
  58. time.sleep(2) # Allow time for the connection to establish
  59. # Read initial startup messages from Arduino
  60. arduino_table_name = None
  61. arduino_driver_type = None
  62. while ser.in_waiting > 0:
  63. line = ser.readline().decode().strip()
  64. print(f"Arduino: {line}") # Print the received message
  65. # Store the device details based on the expected messages
  66. if "Table:" in line:
  67. arduino_table_name = line.replace("Table: ", "").strip()
  68. elif "Drivers:" in line:
  69. arduino_driver_type = line.replace("Drivers: ", "").strip()
  70. # Display stored values
  71. print(f"Detected Table: {arduino_table_name or 'Unknown'}")
  72. print(f"Detected Drivers: {arduino_driver_type or 'Unknown'}")
  73. return True # Successfully connected
  74. except serial.SerialException as e:
  75. print(f"Failed to connect to serial port {port}: {e}")
  76. port = None # Reset the port to try the next available one
  77. print("Max retries reached. Could not connect to a serial port.")
  78. return False
  79. def disconnect_serial():
  80. """Disconnect the current serial connection."""
  81. global ser, ser_port
  82. if ser and ser.is_open:
  83. ser.close()
  84. ser = None
  85. ser_port = None # Reset the port name
  86. def restart_serial(port, baudrate=115200):
  87. """Restart the serial connection."""
  88. disconnect_serial()
  89. connect_to_serial(port, baudrate)
  90. def parse_theta_rho_file(file_path):
  91. """
  92. Parse a theta-rho file and return a list of (theta, rho) pairs.
  93. Normalizes the list so the first theta is always 0.
  94. """
  95. coordinates = []
  96. try:
  97. with open(file_path, 'r') as file:
  98. for line in file:
  99. line = line.strip()
  100. # Skip header or comment lines (starting with '#' or empty lines)
  101. if not line or line.startswith("#"):
  102. continue
  103. # Parse lines with theta and rho separated by spaces
  104. try:
  105. theta, rho = map(float, line.split())
  106. coordinates.append((theta, rho))
  107. except ValueError:
  108. print(f"Skipping invalid line: {line}")
  109. continue
  110. except Exception as e:
  111. print(f"Error reading file: {e}")
  112. return coordinates
  113. # ---- Normalization Step ----
  114. if coordinates:
  115. # Take the first coordinate's theta
  116. first_theta = coordinates[0][0]
  117. # Shift all thetas so the first coordinate has theta=0
  118. normalized = []
  119. for (theta, rho) in coordinates:
  120. normalized.append((theta - first_theta, rho))
  121. # Replace original list with normalized data
  122. coordinates = normalized
  123. return coordinates
  124. def send_coordinate_batch(ser, coordinates):
  125. """Send a batch of theta-rho pairs to the Arduino."""
  126. # print("Sending batch:", coordinates)
  127. batch_str = ";".join(f"{theta:.5f},{rho:.5f}" for theta, rho in coordinates) + ";\n"
  128. ser.write(batch_str.encode())
  129. def send_command(command):
  130. """Send a single command to the Arduino."""
  131. ser.write(f"{command}\n".encode())
  132. print(f"Sent: {command}")
  133. # Wait for "R" acknowledgment from Arduino
  134. while True:
  135. with serial_lock:
  136. if ser.in_waiting > 0:
  137. response = ser.readline().decode().strip()
  138. print(f"Arduino response: {response}")
  139. if response == "R":
  140. print("Command execution completed.")
  141. break
  142. def wait_for_start_time(schedule_hours):
  143. """
  144. Keep checking every 30 seconds if the time is within the schedule to resume execution.
  145. """
  146. global pause_requested
  147. start_time, end_time = schedule_hours
  148. while pause_requested:
  149. now = datetime.now().time()
  150. if start_time <= now < end_time:
  151. print("Resuming execution: Within schedule.")
  152. pause_requested = False
  153. with pause_condition:
  154. pause_condition.notify_all()
  155. break # Exit the loop once resumed
  156. else:
  157. time.sleep(30) # Wait for 30 seconds before checking again
  158. # Function to check schedule based on start and end time
  159. def schedule_checker(schedule_hours):
  160. """
  161. Pauses/resumes execution based on a given time range.
  162. Parameters:
  163. - schedule_hours (tuple): (start_time, end_time) as `datetime.time` objects.
  164. """
  165. global pause_requested
  166. if not schedule_hours:
  167. return # No scheduling restriction
  168. start_time, end_time = schedule_hours
  169. now = datetime.now().time() # Get the current time as `datetime.time`
  170. # Check if we are currently within the scheduled time
  171. if start_time <= now < end_time:
  172. if pause_requested:
  173. print("Starting execution: Within schedule.")
  174. pause_requested = False # Resume execution
  175. with pause_condition:
  176. pause_condition.notify_all()
  177. else:
  178. if not pause_requested:
  179. print("Pausing execution: Outside schedule.")
  180. pause_requested = True # Pause execution
  181. # Start a background thread to periodically check for start time
  182. threading.Thread(target=wait_for_start_time, args=(schedule_hours,), daemon=True).start()
  183. def run_theta_rho_file(file_path, schedule_hours=None):
  184. """Run a theta-rho file by sending data in optimized batches."""
  185. global stop_requested, current_playing_file, execution_progress
  186. stop_requested = False
  187. current_playing_file = file_path # Track current playing file
  188. execution_progress = (0, 0) # Reset progress
  189. coordinates = parse_theta_rho_file(file_path)
  190. total_coordinates = len(coordinates)
  191. if total_coordinates < 2:
  192. print("Not enough coordinates for interpolation.")
  193. current_playing_file = None # Clear tracking if failed
  194. execution_progress = None
  195. return
  196. execution_progress = (0, total_coordinates) # Update total coordinates
  197. batch_size = 10 # Smaller batches may smooth movement further
  198. for i in range(0, total_coordinates, batch_size):
  199. if stop_requested:
  200. print("Execution stopped by user after completing the current batch.")
  201. break
  202. with pause_condition:
  203. while pause_requested:
  204. print("Execution paused...")
  205. pause_condition.wait() # This will block execution until notified
  206. batch = coordinates[i:i + batch_size]
  207. if i == 0:
  208. send_coordinate_batch(ser, batch)
  209. execution_progress = (i + batch_size, total_coordinates) # Update progress
  210. continue
  211. while True:
  212. schedule_checker(schedule_hours) # Check if within schedule
  213. with serial_lock:
  214. if ser.in_waiting > 0:
  215. response = ser.readline().decode().strip()
  216. if response == "R":
  217. send_coordinate_batch(ser, batch)
  218. execution_progress = (i + batch_size, total_coordinates) # Update progress
  219. break
  220. else:
  221. print(f"Arduino response: {response}")
  222. reset_theta()
  223. ser.write("FINISHED\n".encode())
  224. # Clear tracking variables when done
  225. current_playing_file = None
  226. execution_progress = None
  227. print("Pattern execution completed.")
  228. def get_clear_pattern_file(pattern_name):
  229. """Return a .thr file path based on pattern_name."""
  230. if pattern_name == "random":
  231. # Randomly pick one of the three known patterns
  232. return random.choice(list(CLEAR_PATTERNS.values()))
  233. # If pattern_name is invalid or absent, default to 'clear_from_in'
  234. return CLEAR_PATTERNS.get(pattern_name, CLEAR_PATTERNS["clear_from_in"])
  235. def run_theta_rho_files(
  236. file_paths,
  237. pause_time=0,
  238. clear_pattern=None,
  239. run_mode="single",
  240. shuffle=False,
  241. schedule_hours=None
  242. ):
  243. """
  244. Runs multiple .thr files in sequence with options for pausing, clearing, shuffling, and looping.
  245. Parameters:
  246. - file_paths (list): List of file paths to run.
  247. - pause_time (float): Seconds to pause between patterns.
  248. - clear_pattern (str): Specific clear pattern to run ("clear_in", "clear_out", "clear_sideway", or "random").
  249. - run_mode (str): "single" for one-time run or "indefinite" for looping.
  250. - shuffle (bool): Whether to shuffle the playlist before running.
  251. """
  252. global stop_requested
  253. stop_requested = False # Reset stop flag at the start
  254. if shuffle:
  255. random.shuffle(file_paths)
  256. print("Playlist shuffled.")
  257. while True:
  258. for idx, path in enumerate(file_paths):
  259. schedule_checker(schedule_hours)
  260. if stop_requested:
  261. print("Execution stopped before starting next pattern.")
  262. return
  263. if clear_pattern:
  264. if stop_requested:
  265. print("Execution stopped before running the next clear pattern.")
  266. return
  267. # Determine the clear pattern to run
  268. clear_file_path = get_clear_pattern_file(clear_pattern)
  269. print(f"Running clear pattern: {clear_file_path}")
  270. run_theta_rho_file(clear_file_path, schedule_hours)
  271. if not stop_requested:
  272. # Run the main pattern
  273. print(f"Running pattern {idx + 1} of {len(file_paths)}: {path}")
  274. run_theta_rho_file(path, schedule_hours)
  275. if idx < len(file_paths) -1:
  276. if stop_requested:
  277. print("Execution stopped before running the next clear pattern.")
  278. return
  279. # Pause after each pattern if requested
  280. if pause_time > 0:
  281. print(f"Pausing for {pause_time} seconds...")
  282. time.sleep(pause_time)
  283. # After completing the playlist
  284. if run_mode == "indefinite":
  285. print("Playlist completed. Restarting as per 'indefinite' run mode.")
  286. if pause_time > 0:
  287. print(f"Pausing for {pause_time} seconds before restarting...")
  288. time.sleep(pause_time)
  289. if shuffle:
  290. random.shuffle(file_paths)
  291. print("Playlist reshuffled for the next loop.")
  292. continue
  293. else:
  294. print("Playlist completed.")
  295. break
  296. # Reset theta after execution or stopping
  297. reset_theta()
  298. ser.write("FINISHED\n".encode())
  299. print("All requested patterns completed (or stopped).")
  300. def reset_theta():
  301. """Reset theta on the Arduino."""
  302. ser.write("RESET_THETA\n".encode())
  303. while True:
  304. with serial_lock:
  305. if ser.in_waiting > 0:
  306. response = ser.readline().decode().strip()
  307. print(f"Arduino response: {response}")
  308. if response == "THETA_RESET":
  309. print("Theta successfully reset.")
  310. break
  311. time.sleep(0.5) # Small delay to avoid busy waiting
  312. # Flask API Endpoints
  313. @app.route('/')
  314. def index():
  315. return render_template('index.html')
  316. @app.route('/list_serial_ports', methods=['GET'])
  317. def list_ports():
  318. return jsonify(list_serial_ports())
  319. @app.route('/connect_serial', methods=['POST'])
  320. def connect_serial():
  321. port = request.json.get('port')
  322. if not port:
  323. return jsonify({'error': 'No port provided'}), 400
  324. try:
  325. connect_to_serial(port)
  326. return jsonify({'success': True})
  327. except Exception as e:
  328. return jsonify({'error': str(e)}), 500
  329. @app.route('/disconnect_serial', methods=['POST'])
  330. def disconnect():
  331. try:
  332. disconnect_serial()
  333. return jsonify({'success': True})
  334. except Exception as e:
  335. return jsonify({'error': str(e)}), 500
  336. @app.route('/restart_serial', methods=['POST'])
  337. def restart():
  338. port = request.json.get('port')
  339. if not port:
  340. return jsonify({'error': 'No port provided'}), 400
  341. try:
  342. restart_serial(port)
  343. return jsonify({'success': True})
  344. except Exception as e:
  345. return jsonify({'error': str(e)}), 500
  346. @app.route('/list_theta_rho_files', methods=['GET'])
  347. def list_theta_rho_files():
  348. files = []
  349. for root, _, filenames in os.walk(THETA_RHO_DIR):
  350. for file in filenames:
  351. # Construct the relative file path
  352. relative_path = os.path.relpath(os.path.join(root, file), THETA_RHO_DIR)
  353. files.append(relative_path)
  354. return jsonify(sorted(files))
  355. @app.route('/upload_theta_rho', methods=['POST'])
  356. def upload_theta_rho():
  357. custom_patterns_dir = os.path.join(THETA_RHO_DIR, 'custom_patterns')
  358. os.makedirs(custom_patterns_dir, exist_ok=True) # Ensure the directory exists
  359. file = request.files['file']
  360. if file:
  361. file.save(os.path.join(custom_patterns_dir, file.filename))
  362. return jsonify({'success': True})
  363. return jsonify({'success': False})
  364. @app.route('/run_theta_rho', methods=['POST'])
  365. def run_theta_rho():
  366. file_name = request.json.get('file_name')
  367. pre_execution = request.json.get('pre_execution') # 'clear_in', 'clear_out', 'clear_sideway', or 'none'
  368. if not file_name:
  369. return jsonify({'error': 'No file name provided'}), 400
  370. file_path = os.path.join(THETA_RHO_DIR, file_name)
  371. if not os.path.exists(file_path):
  372. return jsonify({'error': 'File not found'}), 404
  373. try:
  374. # Build a list of files to run in sequence
  375. files_to_run = []
  376. if pre_execution == 'clear_in':
  377. files_to_run.append('./patterns/clear_from_in.thr')
  378. elif pre_execution == 'clear_out':
  379. files_to_run.append('./patterns/clear_from_out.thr')
  380. elif pre_execution == 'clear_sideway':
  381. files_to_run.append('./patterns/clear_sideway.thr')
  382. elif pre_execution == 'none':
  383. pass # No pre-execution action required
  384. # Finally, add the main file
  385. files_to_run.append(file_path)
  386. # Run them in one shot using run_theta_rho_files (blocking call)
  387. threading.Thread(
  388. target=run_theta_rho_files,
  389. args=(files_to_run,),
  390. kwargs={
  391. 'pause_time': 0,
  392. 'clear_pattern': None
  393. }
  394. ).start()
  395. return jsonify({'success': True})
  396. except Exception as e:
  397. return jsonify({'error': str(e)}), 500
  398. @app.route('/stop_execution', methods=['POST'])
  399. def stop_execution():
  400. global stop_requested
  401. stop_requested = True
  402. return jsonify({'success': True})
  403. @app.route('/send_home', methods=['POST'])
  404. def send_home():
  405. """Send the HOME command to the Arduino."""
  406. try:
  407. send_command("HOME")
  408. return jsonify({'success': True})
  409. except Exception as e:
  410. return jsonify({'error': str(e)}), 500
  411. @app.route('/run_theta_rho_file/<file_name>', methods=['POST'])
  412. def run_specific_theta_rho_file(file_name):
  413. """Run a specific theta-rho file."""
  414. file_path = os.path.join(THETA_RHO_DIR, file_name)
  415. if not os.path.exists(file_path):
  416. return jsonify({'error': 'File not found'}), 404
  417. threading.Thread(target=run_theta_rho_file, args=(file_path,)).start()
  418. return jsonify({'success': True})
  419. @app.route('/delete_theta_rho_file', methods=['POST'])
  420. def delete_theta_rho_file():
  421. data = request.json
  422. file_name = data.get('file_name')
  423. if not file_name:
  424. return jsonify({"success": False, "error": "No file name provided"}), 400
  425. file_path = os.path.join(THETA_RHO_DIR, file_name)
  426. if not os.path.exists(file_path):
  427. return jsonify({"success": False, "error": "File not found"}), 404
  428. try:
  429. os.remove(file_path)
  430. return jsonify({"success": True})
  431. except Exception as e:
  432. return jsonify({"success": False, "error": str(e)}), 500
  433. @app.route('/move_to_center', methods=['POST'])
  434. def move_to_center():
  435. """Move the sand table to the center position."""
  436. try:
  437. if ser is None or not ser.is_open:
  438. return jsonify({"success": False, "error": "Serial connection not established"}), 400
  439. coordinates = [(0, 0)] # Center position
  440. send_coordinate_batch(ser, coordinates)
  441. return jsonify({"success": True})
  442. except Exception as e:
  443. return jsonify({"success": False, "error": str(e)}), 500
  444. @app.route('/move_to_perimeter', methods=['POST'])
  445. def move_to_perimeter():
  446. """Move the sand table to the perimeter position."""
  447. try:
  448. if ser is None or not ser.is_open:
  449. return jsonify({"success": False, "error": "Serial connection not established"}), 400
  450. MAX_RHO = 1
  451. coordinates = [(0, MAX_RHO)] # Perimeter position
  452. send_coordinate_batch(ser, coordinates)
  453. return jsonify({"success": True})
  454. except Exception as e:
  455. return jsonify({"success": False, "error": str(e)}), 500
  456. @app.route('/preview_thr', methods=['POST'])
  457. def preview_thr():
  458. file_name = request.json.get('file_name')
  459. if not file_name:
  460. return jsonify({'error': 'No file name provided'}), 400
  461. file_path = os.path.join(THETA_RHO_DIR, file_name)
  462. if not os.path.exists(file_path):
  463. return jsonify({'error': 'File not found'}), 404
  464. try:
  465. # Parse the .thr file with transformations
  466. coordinates = parse_theta_rho_file(file_path)
  467. return jsonify({'success': True, 'coordinates': coordinates})
  468. except Exception as e:
  469. return jsonify({'error': str(e)}), 500
  470. @app.route('/send_coordinate', methods=['POST'])
  471. def send_coordinate():
  472. """Send a single (theta, rho) coordinate to the Arduino."""
  473. global ser
  474. if ser is None or not ser.is_open:
  475. return jsonify({"success": False, "error": "Serial connection not established"}), 400
  476. try:
  477. data = request.json
  478. theta = data.get('theta')
  479. rho = data.get('rho')
  480. if theta is None or rho is None:
  481. return jsonify({"success": False, "error": "Theta and Rho are required"}), 400
  482. # Send the coordinate to the Arduino
  483. send_coordinate_batch(ser, [(theta, rho)])
  484. return jsonify({"success": True})
  485. except Exception as e:
  486. return jsonify({"success": False, "error": str(e)}), 500
  487. # Expose files for download if needed
  488. @app.route('/download/<filename>', methods=['GET'])
  489. def download_file(filename):
  490. """Download a file from the theta-rho directory."""
  491. return send_from_directory(THETA_RHO_DIR, filename)
  492. @app.route('/serial_status', methods=['GET'])
  493. def serial_status():
  494. global ser, ser_port
  495. return jsonify({
  496. 'connected': ser.is_open if ser else False,
  497. 'port': ser_port # Include the port name
  498. })
  499. @app.route('/pause_execution', methods=['POST'])
  500. def pause_execution():
  501. """Pause the current execution."""
  502. global pause_requested
  503. with pause_condition:
  504. pause_requested = True
  505. return jsonify({'success': True, 'message': 'Execution paused'})
  506. @app.route('/status', methods=['GET'])
  507. def get_status():
  508. """Returns the current status of the sand table."""
  509. return jsonify({
  510. "ser_port": ser_port,
  511. "stop_requested": stop_requested,
  512. "pause_requested": pause_requested,
  513. "current_playing_file": current_playing_file,
  514. "execution_progress": execution_progress,
  515. "arduino_table_name": arduino_table_name,
  516. "arduino_driver_type": arduino_driver_type
  517. })
  518. @app.route('/resume_execution', methods=['POST'])
  519. def resume_execution():
  520. """Resume execution after pausing."""
  521. global pause_requested
  522. with pause_condition:
  523. pause_requested = False
  524. pause_condition.notify_all() # Unblock the waiting thread
  525. return jsonify({'success': True, 'message': 'Execution resumed'})
  526. def load_playlists():
  527. """
  528. Load the entire playlists dictionary from the JSON file.
  529. Returns something like: {
  530. "My Playlist": ["file1.thr", "file2.thr"],
  531. "Another": ["x.thr"]
  532. }
  533. """
  534. with open(PLAYLISTS_FILE, "r") as f:
  535. return json.load(f)
  536. def save_playlists(playlists_dict):
  537. """
  538. Save the entire playlists dictionary back to the JSON file.
  539. """
  540. with open(PLAYLISTS_FILE, "w") as f:
  541. json.dump(playlists_dict, f, indent=2)
  542. @app.route("/list_all_playlists", methods=["GET"])
  543. def list_all_playlists():
  544. """
  545. Returns a list of all playlist names.
  546. Example return: ["My Playlist", "Another Playlist"]
  547. """
  548. playlists_dict = load_playlists()
  549. playlist_names = list(playlists_dict.keys())
  550. return jsonify(playlist_names)
  551. @app.route("/get_playlist", methods=["GET"])
  552. def get_playlist():
  553. """
  554. GET /get_playlist?name=My%20Playlist
  555. Returns: { "name": "My Playlist", "files": [... ] }
  556. """
  557. playlist_name = request.args.get("name", "")
  558. if not playlist_name:
  559. return jsonify({"error": "Missing playlist 'name' parameter"}), 400
  560. playlists_dict = load_playlists()
  561. if playlist_name not in playlists_dict:
  562. return jsonify({"error": f"Playlist '{playlist_name}' not found"}), 404
  563. files = playlists_dict[playlist_name] # e.g. ["file1.thr", "file2.thr"]
  564. return jsonify({
  565. "name": playlist_name,
  566. "files": files
  567. })
  568. @app.route("/create_playlist", methods=["POST"])
  569. def create_playlist():
  570. """
  571. POST /create_playlist
  572. Body: { "name": "My Playlist", "files": ["file1.thr", "file2.thr"] }
  573. Creates or overwrites a playlist with the given name.
  574. """
  575. data = request.get_json()
  576. if not data or "name" not in data or "files" not in data:
  577. return jsonify({"success": False, "error": "Playlist 'name' and 'files' are required"}), 400
  578. playlist_name = data["name"]
  579. files = data["files"]
  580. # Load all playlists
  581. playlists_dict = load_playlists()
  582. # Overwrite or create new
  583. playlists_dict[playlist_name] = files
  584. # Save changes
  585. save_playlists(playlists_dict)
  586. return jsonify({
  587. "success": True,
  588. "message": f"Playlist '{playlist_name}' created/updated"
  589. })
  590. @app.route("/modify_playlist", methods=["POST"])
  591. def modify_playlist():
  592. """
  593. POST /modify_playlist
  594. Body: { "name": "My Playlist", "files": ["file1.thr", "file2.thr"] }
  595. Updates (or creates) the existing playlist with a new file list.
  596. You can 404 if you only want to allow modifications to existing playlists.
  597. """
  598. data = request.get_json()
  599. if not data or "name" not in data or "files" not in data:
  600. return jsonify({"success": False, "error": "Playlist 'name' and 'files' are required"}), 400
  601. playlist_name = data["name"]
  602. files = data["files"]
  603. # Load all playlists
  604. playlists_dict = load_playlists()
  605. # Optional: If you want to disallow creating a new playlist here:
  606. # if playlist_name not in playlists_dict:
  607. # return jsonify({"success": False, "error": f"Playlist '{playlist_name}' not found"}), 404
  608. # Overwrite or create new
  609. playlists_dict[playlist_name] = files
  610. # Save
  611. save_playlists(playlists_dict)
  612. return jsonify({"success": True, "message": f"Playlist '{playlist_name}' updated"})
  613. @app.route("/delete_playlist", methods=["DELETE"])
  614. def delete_playlist():
  615. """
  616. DELETE /delete_playlist
  617. Body: { "name": "My Playlist" }
  618. Removes the playlist from the single JSON file.
  619. """
  620. data = request.get_json()
  621. if not data or "name" not in data:
  622. return jsonify({"success": False, "error": "Missing 'name' field"}), 400
  623. playlist_name = data["name"]
  624. playlists_dict = load_playlists()
  625. if playlist_name not in playlists_dict:
  626. return jsonify({"success": False, "error": f"Playlist '{playlist_name}' not found"}), 404
  627. # Remove from dict
  628. del playlists_dict[playlist_name]
  629. save_playlists(playlists_dict)
  630. return jsonify({
  631. "success": True,
  632. "message": f"Playlist '{playlist_name}' deleted"
  633. })
  634. @app.route('/add_to_playlist', methods=['POST'])
  635. def add_to_playlist():
  636. data = request.json
  637. playlist_name = data.get('playlist_name')
  638. pattern = data.get('pattern')
  639. # Load existing playlists
  640. with open('playlists.json', 'r') as f:
  641. playlists = json.load(f)
  642. # Add pattern to the selected playlist
  643. if playlist_name in playlists:
  644. playlists[playlist_name].append(pattern)
  645. with open('playlists.json', 'w') as f:
  646. json.dump(playlists, f)
  647. return jsonify(success=True)
  648. else:
  649. return jsonify(success=False, error='Playlist not found'), 404
  650. @app.route("/run_playlist", methods=["POST"])
  651. def run_playlist():
  652. """
  653. POST /run_playlist
  654. Body (JSON):
  655. {
  656. "playlist_name": "My Playlist",
  657. "pause_time": 1.0, # Optional: seconds to pause between patterns
  658. "clear_pattern": "random", # Optional: "clear_in", "clear_out", "clear_sideway", or "random"
  659. "run_mode": "single", # 'single' or 'indefinite'
  660. "shuffle": True # true or false
  661. "start_time": ""
  662. "end_time": ""
  663. }
  664. """
  665. data = request.get_json()
  666. # Validate input
  667. if not data or "playlist_name" not in data:
  668. return jsonify({"success": False, "error": "Missing 'playlist_name' field"}), 400
  669. playlist_name = data["playlist_name"]
  670. pause_time = data.get("pause_time", 0)
  671. clear_pattern = data.get("clear_pattern", None)
  672. run_mode = data.get("run_mode", "single") # Default to 'single' run
  673. shuffle = data.get("shuffle", False) # Default to no shuffle
  674. start_time = data.get("start_time", None)
  675. end_time = data.get("end_time", None)
  676. # Validate pause_time
  677. if not isinstance(pause_time, (int, float)) or pause_time < 0:
  678. return jsonify({"success": False, "error": "'pause_time' must be a non-negative number"}), 400
  679. # Validate clear_pattern
  680. valid_patterns = ["clear_in", "clear_out", "clear_sideway", "random"]
  681. if clear_pattern not in valid_patterns:
  682. clear_pattern = None
  683. # Validate run_mode
  684. if run_mode not in ["single", "indefinite"]:
  685. return jsonify({"success": False, "error": "'run_mode' must be 'single' or 'indefinite'"}), 400
  686. # Validate shuffle
  687. if not isinstance(shuffle, bool):
  688. return jsonify({"success": False, "error": "'shuffle' must be a boolean value"}), 400
  689. schedule_hours = None
  690. if start_time and end_time:
  691. try:
  692. # Convert HH:MM to datetime.time objects
  693. start_time_obj = datetime.strptime(start_time, "%H:%M").time()
  694. end_time_obj = datetime.strptime(end_time, "%H:%M").time()
  695. # Ensure start_time is before end_time
  696. if start_time_obj >= end_time_obj:
  697. return jsonify({"success": False, "error": "'start_time' must be earlier than 'end_time'"}), 400
  698. # Create schedule tuple with full time
  699. schedule_hours = (start_time_obj, end_time_obj)
  700. except ValueError:
  701. return jsonify({"success": False, "error": "Invalid time format. Use HH:MM (e.g., '09:30')"}), 400
  702. # Load playlists
  703. playlists = load_playlists()
  704. if playlist_name not in playlists:
  705. return jsonify({"success": False, "error": f"Playlist '{playlist_name}' not found"}), 404
  706. file_paths = playlists[playlist_name]
  707. file_paths = [os.path.join(THETA_RHO_DIR, file) for file in file_paths]
  708. if not file_paths:
  709. return jsonify({"success": False, "error": f"Playlist '{playlist_name}' is empty"}), 400
  710. # Start the playlist execution in a separate thread
  711. try:
  712. threading.Thread(
  713. target=run_theta_rho_files,
  714. args=(file_paths,),
  715. kwargs={
  716. 'pause_time': pause_time,
  717. 'clear_pattern': clear_pattern,
  718. 'run_mode': run_mode,
  719. 'shuffle': shuffle,
  720. 'schedule_hours': schedule_hours
  721. },
  722. daemon=True # Daemonize thread to exit with the main program
  723. ).start()
  724. return jsonify({"success": True, "message": f"Playlist '{playlist_name}' is now running."})
  725. except Exception as e:
  726. return jsonify({"success": False, "error": str(e)}), 500
  727. @app.route('/set_speed', methods=['POST'])
  728. def set_speed():
  729. """Set the speed for the Arduino."""
  730. global ser
  731. if ser is None or not ser.is_open:
  732. return jsonify({"success": False, "error": "Serial connection not established"}), 400
  733. try:
  734. # Parse the speed value from the request
  735. data = request.json
  736. speed = data.get('speed')
  737. if speed is None:
  738. return jsonify({"success": False, "error": "Speed is required"}), 400
  739. if not isinstance(speed, (int, float)) or speed <= 0:
  740. return jsonify({"success": False, "error": "Invalid speed value"}), 400
  741. # Send the SET_SPEED command to the Arduino
  742. command = f"SET_SPEED {speed}"
  743. send_command(command)
  744. return jsonify({"success": True, "speed": speed})
  745. except Exception as e:
  746. return jsonify({"success": False, "error": str(e)}), 500
  747. if __name__ == '__main__':
  748. # Auto-connect to serial
  749. connect_to_serial()
  750. app.run(debug=True, host='0.0.0.0', port=8080)