1
0

pattern_manager.py 26 KB

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