pattern_manager.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. import os
  2. import threading
  3. import time
  4. import random
  5. import logging
  6. from datetime import datetime
  7. from tqdm import tqdm
  8. from modules.connection import connection_manager
  9. from modules.core.state import state
  10. from math import pi
  11. import asyncio
  12. import json
  13. from modules.led.led_controller import effect_playing, effect_idle
  14. # Configure logging
  15. logger = logging.getLogger(__name__)
  16. # Global state
  17. THETA_RHO_DIR = './patterns'
  18. os.makedirs(THETA_RHO_DIR, exist_ok=True)
  19. # Create an asyncio Event for pause/resume
  20. pause_event = asyncio.Event()
  21. pause_event.set() # Initially not paused
  22. # Create an asyncio Lock for pattern execution
  23. pattern_lock = asyncio.Lock()
  24. # Progress update task
  25. progress_update_task = None
  26. async def cleanup_pattern_manager():
  27. """Clean up pattern manager resources"""
  28. global progress_update_task, pattern_lock, pause_event
  29. try:
  30. # Cancel progress update task if running
  31. if progress_update_task and not progress_update_task.done():
  32. try:
  33. progress_update_task.cancel()
  34. # Wait for task to actually cancel
  35. try:
  36. await progress_update_task
  37. except asyncio.CancelledError:
  38. pass
  39. except Exception as e:
  40. logger.error(f"Error cancelling progress update task: {e}")
  41. # Clean up pattern lock
  42. if pattern_lock:
  43. try:
  44. if pattern_lock.locked():
  45. pattern_lock.release()
  46. pattern_lock = None
  47. except Exception as e:
  48. logger.error(f"Error cleaning up pattern lock: {e}")
  49. # Clean up pause event
  50. if pause_event:
  51. try:
  52. pause_event.set() # Wake up any waiting tasks
  53. pause_event = None
  54. except Exception as e:
  55. logger.error(f"Error cleaning up pause event: {e}")
  56. # Clean up pause condition from state
  57. if state.pause_condition:
  58. try:
  59. with state.pause_condition:
  60. state.pause_condition.notify_all()
  61. state.pause_condition = threading.Condition()
  62. except Exception as e:
  63. logger.error(f"Error cleaning up pause condition: {e}")
  64. # Clear all state variables
  65. state.current_playing_file = None
  66. state.execution_progress = 0
  67. state.is_running = False
  68. state.pause_requested = False
  69. state.stop_requested = True
  70. state.is_clearing = False
  71. # Reset machine position
  72. await connection_manager.update_machine_position()
  73. logger.info("Pattern manager resources cleaned up")
  74. except Exception as e:
  75. logger.error(f"Error during pattern manager cleanup: {e}")
  76. finally:
  77. # Ensure we always reset these
  78. progress_update_task = None
  79. pattern_lock = None
  80. pause_event = None
  81. def list_theta_rho_files():
  82. files = []
  83. for root, _, filenames in os.walk(THETA_RHO_DIR):
  84. for file in filenames:
  85. relative_path = os.path.relpath(os.path.join(root, file), THETA_RHO_DIR)
  86. # Normalize path separators to always use forward slashes for consistency across platforms
  87. relative_path = relative_path.replace(os.sep, '/')
  88. files.append(relative_path)
  89. logger.debug(f"Found {len(files)} theta-rho files")
  90. return [file for file in files if file.endswith('.thr')]
  91. def parse_theta_rho_file(file_path):
  92. """Parse a theta-rho file and return a list of (theta, rho) pairs."""
  93. coordinates = []
  94. try:
  95. logger.debug(f"Parsing theta-rho file: {file_path}")
  96. with open(file_path, 'r', encoding='utf-8') as file:
  97. for line in file:
  98. line = line.strip()
  99. if not line or line.startswith("#"):
  100. continue
  101. try:
  102. theta, rho = map(float, line.split())
  103. coordinates.append((theta, rho))
  104. except ValueError:
  105. logger.warning(f"Skipping invalid line: {line}")
  106. continue
  107. except Exception as e:
  108. logger.error(f"Error reading file: {e}")
  109. return coordinates
  110. logger.debug(f"Parsed {len(coordinates)} coordinates from {file_path}")
  111. return coordinates
  112. def get_first_rho_from_cache(file_path):
  113. """Get the first rho value from cached metadata, falling back to file parsing if needed."""
  114. try:
  115. # Import cache_manager locally to avoid circular import
  116. from modules.core import cache_manager
  117. # Try to get from metadata cache first
  118. file_name = os.path.basename(file_path)
  119. metadata = cache_manager.get_pattern_metadata(file_name)
  120. if metadata and 'first_coordinate' in metadata:
  121. # In the cache, 'x' is theta and 'y' is rho
  122. return metadata['first_coordinate']['y']
  123. # Fallback to parsing the file if not in cache
  124. logger.debug(f"Metadata not cached for {file_name}, parsing file")
  125. coordinates = parse_theta_rho_file(file_path)
  126. if coordinates:
  127. return coordinates[0][1] # Return rho value
  128. return None
  129. except Exception as e:
  130. logger.warning(f"Error getting first rho from cache for {file_path}: {str(e)}")
  131. return None
  132. def get_clear_pattern_file(clear_pattern_mode, path=None):
  133. """Return a .thr file path based on pattern_name and table type."""
  134. if not clear_pattern_mode or clear_pattern_mode == 'none':
  135. return
  136. # Define patterns for each table type
  137. clear_patterns = {
  138. 'dune_weaver': {
  139. 'clear_from_out': './patterns/clear_from_out.thr',
  140. 'clear_from_in': './patterns/clear_from_in.thr',
  141. 'clear_sideway': './patterns/clear_sideway.thr'
  142. },
  143. 'dune_weaver_mini': {
  144. 'clear_from_out': './patterns/clear_from_out_mini.thr',
  145. 'clear_from_in': './patterns/clear_from_in_mini.thr',
  146. 'clear_sideway': './patterns/clear_sideway_mini.thr'
  147. },
  148. 'dune_weaver_pro': {
  149. 'clear_from_out': './patterns/clear_from_out_pro.thr',
  150. 'clear_from_out_Ultra': './patterns/clear_from_out_Ultra.thr',
  151. 'clear_from_in': './patterns/clear_from_in_pro.thr',
  152. 'clear_from_in_Ultra': './patterns/clear_from_in_Ultra.thr',
  153. 'clear_sideway': './patterns/clear_sideway_pro.thr'
  154. }
  155. }
  156. # Get patterns for current table type, fallback to standard patterns if type not found
  157. table_patterns = clear_patterns.get(state.table_type, clear_patterns['dune_weaver'])
  158. # Check for custom patterns first
  159. if state.custom_clear_from_out and clear_pattern_mode in ['clear_from_out', 'adaptive']:
  160. if clear_pattern_mode == 'adaptive':
  161. # For adaptive mode, use cached metadata to check first rho
  162. if path:
  163. first_rho = get_first_rho_from_cache(path)
  164. if first_rho is not None and first_rho < 0.5:
  165. # Use custom clear_from_out if set
  166. custom_path = os.path.join('./patterns', state.custom_clear_from_out)
  167. if os.path.exists(custom_path):
  168. logger.debug(f"Using custom clear_from_out: {custom_path}")
  169. return custom_path
  170. elif clear_pattern_mode == 'clear_from_out':
  171. custom_path = os.path.join('./patterns', state.custom_clear_from_out)
  172. if os.path.exists(custom_path):
  173. logger.debug(f"Using custom clear_from_out: {custom_path}")
  174. return custom_path
  175. if state.custom_clear_from_in and clear_pattern_mode in ['clear_from_in', 'adaptive']:
  176. if clear_pattern_mode == 'adaptive':
  177. # For adaptive mode, use cached metadata to check first rho
  178. if path:
  179. first_rho = get_first_rho_from_cache(path)
  180. if first_rho is not None and first_rho >= 0.5:
  181. # Use custom clear_from_in if set
  182. custom_path = os.path.join('./patterns', state.custom_clear_from_in)
  183. if os.path.exists(custom_path):
  184. logger.debug(f"Using custom clear_from_in: {custom_path}")
  185. return custom_path
  186. elif clear_pattern_mode == 'clear_from_in':
  187. custom_path = os.path.join('./patterns', state.custom_clear_from_in)
  188. if os.path.exists(custom_path):
  189. logger.debug(f"Using custom clear_from_in: {custom_path}")
  190. return custom_path
  191. logger.debug(f"Clear pattern mode: {clear_pattern_mode} for table type: {state.table_type}")
  192. if clear_pattern_mode == "random":
  193. return random.choice(list(table_patterns.values()))
  194. if clear_pattern_mode == 'adaptive':
  195. if not path:
  196. logger.warning("No path provided for adaptive clear pattern")
  197. return random.choice(list(table_patterns.values()))
  198. # Use cached metadata to get first rho value
  199. first_rho = get_first_rho_from_cache(path)
  200. if first_rho is None:
  201. logger.warning("Could not determine first rho value for adaptive clear pattern")
  202. return random.choice(list(table_patterns.values()))
  203. if first_rho < 0.5:
  204. return table_patterns['clear_from_out']
  205. else:
  206. return table_patterns['clear_from_in']
  207. else:
  208. if clear_pattern_mode not in table_patterns:
  209. return False
  210. return table_patterns[clear_pattern_mode]
  211. def is_clear_pattern(file_path):
  212. """Check if a file path is a clear pattern file."""
  213. # Get all possible clear pattern files for all table types
  214. clear_patterns = []
  215. for table_type in ['dune_weaver', 'dune_weaver_mini', 'dune_weaver_pro']:
  216. clear_patterns.extend([
  217. f'./patterns/clear_from_out{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr',
  218. f'./patterns/clear_from_in{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr',
  219. f'./patterns/clear_sideway{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr'
  220. ])
  221. # Normalize paths for comparison
  222. normalized_path = os.path.normpath(file_path)
  223. normalized_clear_patterns = [os.path.normpath(p) for p in clear_patterns]
  224. # Check if the file path matches any clear pattern path
  225. return normalized_path in normalized_clear_patterns
  226. async def run_theta_rho_file(file_path, is_playlist=False):
  227. """Run a theta-rho file by sending data in optimized batches with tqdm ETA tracking."""
  228. if pattern_lock.locked():
  229. logger.warning("Another pattern is already running. Cannot start a new one.")
  230. return
  231. async with pattern_lock: # This ensures only one pattern can run at a time
  232. # Start progress update task only if not part of a playlist
  233. global progress_update_task
  234. if not is_playlist and not progress_update_task:
  235. progress_update_task = asyncio.create_task(broadcast_progress())
  236. coordinates = parse_theta_rho_file(file_path)
  237. total_coordinates = len(coordinates)
  238. if total_coordinates < 2:
  239. logger.warning("Not enough coordinates for interpolation")
  240. if not is_playlist:
  241. state.current_playing_file = None
  242. state.execution_progress = None
  243. return
  244. # Determine if this is a clearing pattern and set appropriate speed
  245. is_clear_file = is_clear_pattern(file_path)
  246. # Use clear_pattern_speed if it's set and this is a clear file, otherwise use state.speed
  247. if is_clear_file and state.clear_pattern_speed is not None:
  248. pattern_speed = state.clear_pattern_speed
  249. else:
  250. pattern_speed = state.speed
  251. if is_clear_file:
  252. logger.info(f"Running clearing pattern at speed {pattern_speed}")
  253. else:
  254. logger.info(f"Running normal pattern at speed {pattern_speed}")
  255. state.execution_progress = (0, total_coordinates, None, 0)
  256. # stop actions without resetting the playlist
  257. stop_actions(clear_playlist=False)
  258. state.current_playing_file = file_path
  259. state.stop_requested = False
  260. logger.info(f"Starting pattern execution: {file_path}")
  261. logger.info(f"t: {state.current_theta}, r: {state.current_rho}")
  262. reset_theta()
  263. start_time = time.time()
  264. if state.led_controller:
  265. effect_playing(state.led_controller)
  266. with tqdm(
  267. total=total_coordinates,
  268. unit="coords",
  269. desc=f"Executing Pattern {file_path}",
  270. dynamic_ncols=True,
  271. disable=False,
  272. mininterval=1.0
  273. ) as pbar:
  274. for i, coordinate in enumerate(coordinates):
  275. theta, rho = coordinate
  276. if state.stop_requested:
  277. logger.info("Execution stopped by user")
  278. if state.led_controller:
  279. effect_idle(state.led_controller)
  280. break
  281. if state.skip_requested:
  282. logger.info("Skipping pattern...")
  283. connection_manager.check_idle()
  284. if state.led_controller:
  285. effect_idle(state.led_controller)
  286. break
  287. # Wait for resume if paused
  288. if state.pause_requested:
  289. logger.info("Execution paused...")
  290. if state.led_controller:
  291. effect_idle(state.led_controller)
  292. await pause_event.wait()
  293. logger.info("Execution resumed...")
  294. if state.led_controller:
  295. effect_playing(state.led_controller)
  296. move_polar(theta, rho, pattern_speed)
  297. # Update progress for all coordinates including the first one
  298. pbar.update(1)
  299. elapsed_time = time.time() - start_time
  300. estimated_remaining_time = (total_coordinates - (i + 1)) / pbar.format_dict['rate'] if pbar.format_dict['rate'] and total_coordinates else 0
  301. state.execution_progress = (i + 1, total_coordinates, estimated_remaining_time, elapsed_time)
  302. # Add a small delay to allow other async operations
  303. await asyncio.sleep(0.001)
  304. # Update progress one last time to show 100%
  305. elapsed_time = time.time() - start_time
  306. state.execution_progress = (total_coordinates, total_coordinates, 0, elapsed_time)
  307. # Give WebSocket a chance to send the final update
  308. await asyncio.sleep(0.1)
  309. if not state.conn:
  310. logger.error("Device is not connected. Stopping pattern execution.")
  311. return
  312. connection_manager.check_idle()
  313. # Set LED back to idle when pattern completes normally (not stopped early)
  314. if state.led_controller and not state.stop_requested:
  315. effect_idle(state.led_controller)
  316. logger.debug("LED effect set to idle after pattern completion")
  317. # Only clear state if not part of a playlist
  318. if not is_playlist:
  319. state.current_playing_file = None
  320. state.execution_progress = None
  321. logger.info("Pattern execution completed and state cleared")
  322. else:
  323. logger.info("Pattern execution completed, maintaining state for playlist")
  324. # Only cancel progress update task if not part of a playlist
  325. if not is_playlist and progress_update_task:
  326. progress_update_task.cancel()
  327. try:
  328. await progress_update_task
  329. except asyncio.CancelledError:
  330. pass
  331. progress_update_task = None
  332. async def run_theta_rho_files(file_paths, pause_time=0, clear_pattern=None, run_mode="single", shuffle=False):
  333. """Run multiple .thr files in sequence with options."""
  334. state.stop_requested = False
  335. # Set initial playlist state
  336. state.playlist_mode = run_mode
  337. state.current_playlist_index = 0
  338. # Start progress update task for the playlist
  339. global progress_update_task
  340. if not progress_update_task:
  341. progress_update_task = asyncio.create_task(broadcast_progress())
  342. if shuffle:
  343. random.shuffle(file_paths)
  344. logger.info("Playlist shuffled")
  345. if shuffle:
  346. random.shuffle(file_paths)
  347. logger.info("Playlist shuffled")
  348. try:
  349. while True:
  350. # Construct the complete pattern sequence
  351. pattern_sequence = []
  352. for path in file_paths:
  353. # Add clear pattern if specified
  354. if clear_pattern and clear_pattern != 'none':
  355. clear_file_path = get_clear_pattern_file(clear_pattern, path)
  356. if clear_file_path:
  357. pattern_sequence.append(clear_file_path)
  358. # Add main pattern
  359. pattern_sequence.append(path)
  360. # Shuffle if requested
  361. if shuffle:
  362. # Get pairs of patterns (clear + main) to keep them together
  363. pairs = [pattern_sequence[i:i+2] for i in range(0, len(pattern_sequence), 2)]
  364. random.shuffle(pairs)
  365. # Flatten the pairs back into a single list
  366. pattern_sequence = [pattern for pair in pairs for pattern in pair]
  367. logger.info("Playlist shuffled")
  368. # Set the playlist to the first pattern
  369. state.current_playlist = pattern_sequence
  370. # Execute the pattern sequence
  371. for idx, file_path in enumerate(pattern_sequence):
  372. state.current_playlist_index = idx
  373. if state.stop_requested:
  374. logger.info("Execution stopped")
  375. return
  376. # Update state for main patterns only
  377. logger.info(f"Running pattern {file_path}")
  378. # Execute the pattern
  379. await run_theta_rho_file(file_path, is_playlist=True)
  380. # Handle pause between patterns
  381. if idx < len(pattern_sequence) - 1 and not state.stop_requested and pause_time > 0 and not state.skip_requested:
  382. # Check if current pattern is a clear pattern
  383. if is_clear_pattern(file_path):
  384. logger.info("Skipping pause after clear pattern")
  385. else:
  386. logger.info(f"Pausing for {pause_time} seconds")
  387. state.original_pause_time = pause_time
  388. pause_start = time.time()
  389. while time.time() - pause_start < pause_time:
  390. state.pause_time_remaining = pause_start + pause_time - time.time()
  391. if state.skip_requested:
  392. logger.info("Pause interrupted by stop/skip request")
  393. break
  394. await asyncio.sleep(1)
  395. state.pause_time_remaining = 0
  396. state.skip_requested = False
  397. if run_mode == "indefinite":
  398. logger.info("Playlist completed. Restarting as per 'indefinite' run mode")
  399. if pause_time > 0:
  400. logger.debug(f"Pausing for {pause_time} seconds before restarting")
  401. pause_start = time.time()
  402. while time.time() - pause_start < pause_time:
  403. state.pause_time_remaining = pause_start + pause_time - time.time()
  404. if state.skip_requested:
  405. logger.info("Pause interrupted by stop/skip request")
  406. break
  407. await asyncio.sleep(1)
  408. state.pause_time_remaining = 0
  409. continue
  410. else:
  411. logger.info("Playlist completed")
  412. break
  413. finally:
  414. # Clean up progress update task
  415. if progress_update_task:
  416. progress_update_task.cancel()
  417. try:
  418. await progress_update_task
  419. except asyncio.CancelledError:
  420. pass
  421. progress_update_task = None
  422. # Clear all state variables
  423. state.current_playing_file = None
  424. state.execution_progress = None
  425. state.current_playlist = None
  426. state.current_playlist_index = None
  427. state.playlist_mode = None
  428. if state.led_controller:
  429. effect_idle(state.led_controller)
  430. logger.info("All requested patterns completed (or stopped) and state cleared")
  431. def stop_actions(clear_playlist = True):
  432. """Stop all current actions."""
  433. try:
  434. with state.pause_condition:
  435. state.pause_requested = False
  436. state.stop_requested = True
  437. state.current_playing_file = None
  438. state.execution_progress = None
  439. state.is_clearing = False
  440. if clear_playlist:
  441. # Clear playlist state
  442. state.current_playlist = None
  443. state.current_playlist_index = None
  444. state.playlist_mode = None
  445. # Cancel progress update task if we're clearing the playlist
  446. global progress_update_task
  447. if progress_update_task and not progress_update_task.done():
  448. progress_update_task.cancel()
  449. state.pause_condition.notify_all()
  450. connection_manager.update_machine_position()
  451. except Exception as e:
  452. logger.error(f"Error during stop_actions: {e}")
  453. # Ensure we still update machine position even if there's an error
  454. connection_manager.update_machine_position()
  455. def move_polar(theta, rho, speed=None):
  456. """
  457. This functions take in a pair of theta rho coordinate, compute the distance to travel based on current theta, rho,
  458. and translate the motion to gcode jog command and sent to grbl.
  459. Since having similar steps_per_mm will make x and y axis moves at around the same speed, we have to scale the
  460. x_steps_per_mm and y_steps_per_mm so that they are roughly the same. Here's the range of motion:
  461. X axis (angular): 50mm = 1 revolution
  462. Y axis (radial): 0 => 20mm = theta 0 (center) => 1 (perimeter)
  463. Args:
  464. theta (_type_): _description_
  465. rho (_type_): _description_
  466. speed (int, optional): Speed override. If None, uses state.speed
  467. """
  468. # Adding soft limit to reduce hardware sound
  469. # soft_limit_inner = 0.01
  470. # if rho < soft_limit_inner:
  471. # rho = soft_limit_inner
  472. # soft_limit_outter = 0.015
  473. # if rho > (1-soft_limit_outter):
  474. # rho = (1-soft_limit_outter)
  475. if state.table_type == 'dune_weaver_mini':
  476. x_scaling_factor = 2
  477. y_scaling_factor = 3.7
  478. else:
  479. x_scaling_factor = 2
  480. y_scaling_factor = 5
  481. delta_theta = theta - state.current_theta
  482. delta_rho = rho - state.current_rho
  483. x_increment = delta_theta * 100 / (2 * pi * x_scaling_factor) # Added -1 to reverse direction
  484. y_increment = delta_rho * 100 / y_scaling_factor
  485. x_total_steps = state.x_steps_per_mm * (100/x_scaling_factor)
  486. y_total_steps = state.y_steps_per_mm * (100/y_scaling_factor)
  487. offset = x_increment * (x_total_steps * x_scaling_factor / (state.gear_ratio * y_total_steps * y_scaling_factor))
  488. if state.table_type == 'dune_weaver_mini':
  489. y_increment -= offset
  490. else:
  491. y_increment += offset
  492. new_x_abs = state.machine_x + x_increment
  493. new_y_abs = state.machine_y + y_increment
  494. # Use provided speed or fall back to state.speed
  495. actual_speed = speed if speed is not None else state.speed
  496. # dynamic_speed = compute_dynamic_speed(rho, max_speed=actual_speed)
  497. connection_manager.send_grbl_coordinates(round(new_x_abs, 3), round(new_y_abs,3), actual_speed)
  498. state.current_theta = theta
  499. state.current_rho = rho
  500. state.machine_x = new_x_abs
  501. state.machine_y = new_y_abs
  502. def pause_execution():
  503. """Pause pattern execution using asyncio Event."""
  504. logger.info("Pausing pattern execution")
  505. state.pause_requested = True
  506. pause_event.clear() # Clear the event to pause execution
  507. return True
  508. def resume_execution():
  509. """Resume pattern execution using asyncio Event."""
  510. logger.info("Resuming pattern execution")
  511. state.pause_requested = False
  512. pause_event.set() # Set the event to resume execution
  513. return True
  514. def reset_theta():
  515. logger.info('Resetting Theta')
  516. state.current_theta = state.current_theta % (2 * pi)
  517. connection_manager.update_machine_position()
  518. def set_speed(new_speed):
  519. state.speed = new_speed
  520. logger.info(f'Set new state.speed {new_speed}')
  521. def get_status():
  522. """Get the current status of pattern execution."""
  523. status = {
  524. "current_file": state.current_playing_file,
  525. "is_paused": state.pause_requested,
  526. "is_running": bool(state.current_playing_file and not state.stop_requested),
  527. "progress": None,
  528. "playlist": None,
  529. "speed": state.speed,
  530. "pause_time_remaining": state.pause_time_remaining,
  531. "original_pause_time": getattr(state, 'original_pause_time', None),
  532. "connection_status": state.conn.is_connected() if state.conn else False,
  533. "current_theta": state.current_theta,
  534. "current_rho": state.current_rho
  535. }
  536. # Add playlist information if available
  537. if state.current_playlist and state.current_playlist_index is not None:
  538. next_index = state.current_playlist_index + 1
  539. status["playlist"] = {
  540. "current_index": state.current_playlist_index,
  541. "total_files": len(state.current_playlist),
  542. "mode": state.playlist_mode,
  543. "next_file": state.current_playlist[next_index] if next_index < len(state.current_playlist) else None
  544. }
  545. if state.execution_progress:
  546. current, total, remaining_time, elapsed_time = state.execution_progress
  547. status["progress"] = {
  548. "current": current,
  549. "total": total,
  550. "remaining_time": remaining_time,
  551. "elapsed_time": elapsed_time,
  552. "percentage": (current / total * 100) if total > 0 else 0
  553. }
  554. return status
  555. async def broadcast_progress():
  556. """Background task to broadcast progress updates."""
  557. from main import broadcast_status_update
  558. while True:
  559. # Send status updates regardless of pattern_lock state
  560. status = get_status()
  561. # Use the existing broadcast function from main.py
  562. await broadcast_status_update(status)
  563. # Check if we should stop broadcasting
  564. if not state.current_playlist:
  565. # If no playlist, only stop if no pattern is being executed
  566. if not pattern_lock.locked():
  567. logger.info("No playlist or pattern running, stopping broadcast")
  568. break
  569. # Wait before next update
  570. await asyncio.sleep(1)