app.py 30 KB

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