1
0

pattern_manager.py 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  1. import os
  2. from zoneinfo import ZoneInfo
  3. import threading
  4. import time
  5. import random
  6. import logging
  7. from datetime import datetime, time as datetime_time
  8. from tqdm import tqdm
  9. from modules.connection import connection_manager
  10. from modules.core.state import state
  11. from math import pi
  12. import asyncio
  13. import json
  14. # Import for legacy support, but we'll use LED interface through state
  15. from modules.led.led_controller import effect_playing, effect_idle
  16. from modules.led.idle_timeout_manager import idle_timeout_manager
  17. import queue
  18. from dataclasses import dataclass
  19. from typing import Optional, Callable
  20. # Configure logging
  21. logger = logging.getLogger(__name__)
  22. # Global state
  23. THETA_RHO_DIR = './patterns'
  24. os.makedirs(THETA_RHO_DIR, exist_ok=True)
  25. # Execution time log file (JSON Lines format - one JSON object per line)
  26. EXECUTION_LOG_FILE = './execution_times.jsonl'
  27. def log_execution_time(pattern_name: str, table_type: str, speed: int, actual_time: float,
  28. total_coordinates: int, was_completed: bool):
  29. """Log pattern execution time to JSON Lines file for analysis.
  30. Args:
  31. pattern_name: Name of the pattern file
  32. table_type: Type of table (e.g., 'dune_weaver', 'dune_weaver_mini')
  33. speed: Speed setting used (0-255)
  34. actual_time: Actual execution time in seconds (excluding pauses)
  35. total_coordinates: Total number of coordinates in the pattern
  36. was_completed: Whether the pattern completed normally (not stopped/skipped)
  37. """
  38. # Format time as HH:MM:SS
  39. hours, remainder = divmod(int(actual_time), 3600)
  40. minutes, seconds = divmod(remainder, 60)
  41. time_formatted = f"{hours:02d}:{minutes:02d}:{seconds:02d}"
  42. log_entry = {
  43. "timestamp": datetime.now().isoformat(),
  44. "pattern_name": pattern_name,
  45. "table_type": table_type or "unknown",
  46. "speed": speed,
  47. "actual_time_seconds": round(actual_time, 2),
  48. "actual_time_formatted": time_formatted,
  49. "total_coordinates": total_coordinates,
  50. "completed": was_completed
  51. }
  52. try:
  53. with open(EXECUTION_LOG_FILE, 'a') as f:
  54. f.write(json.dumps(log_entry) + '\n')
  55. logger.info(f"Execution time logged: {pattern_name} - {time_formatted} (speed: {speed}, table: {table_type})")
  56. except Exception as e:
  57. logger.error(f"Failed to log execution time: {e}")
  58. # Create an asyncio Event for pause/resume
  59. pause_event = asyncio.Event()
  60. pause_event.set() # Initially not paused
  61. # Create an asyncio Lock for pattern execution
  62. pattern_lock = asyncio.Lock()
  63. # Progress update task
  64. progress_update_task = None
  65. # Cache timezone at module level - read once per session (cleared when user changes timezone)
  66. _cached_timezone = None
  67. _cached_zoneinfo = None
  68. def _get_timezone():
  69. """Get and cache the timezone for Still Sands. Uses user-selected timezone if set, otherwise system timezone."""
  70. global _cached_timezone, _cached_zoneinfo
  71. if _cached_timezone is not None:
  72. return _cached_zoneinfo
  73. user_tz = 'UTC' # Default fallback
  74. # First, check if user has selected a specific timezone in settings
  75. if state.scheduled_pause_timezone:
  76. user_tz = state.scheduled_pause_timezone
  77. logger.info(f"Still Sands using timezone: {user_tz} (user-selected)")
  78. else:
  79. # Fall back to system timezone detection
  80. try:
  81. if os.path.exists('/etc/host-timezone'):
  82. with open('/etc/host-timezone', 'r') as f:
  83. user_tz = f.read().strip()
  84. logger.info(f"Still Sands using timezone: {user_tz} (from host system)")
  85. # Fallback to /etc/timezone if host-timezone doesn't exist
  86. elif os.path.exists('/etc/timezone'):
  87. with open('/etc/timezone', 'r') as f:
  88. user_tz = f.read().strip()
  89. logger.info(f"Still Sands using timezone: {user_tz} (from container)")
  90. # Fallback to TZ environment variable
  91. elif os.environ.get('TZ'):
  92. user_tz = os.environ.get('TZ')
  93. logger.info(f"Still Sands using timezone: {user_tz} (from environment)")
  94. else:
  95. logger.info("Still Sands using timezone: UTC (system default)")
  96. except Exception as e:
  97. logger.debug(f"Could not read timezone: {e}")
  98. # Cache the timezone
  99. _cached_timezone = user_tz
  100. try:
  101. _cached_zoneinfo = ZoneInfo(user_tz)
  102. except Exception as e:
  103. logger.warning(f"Invalid timezone '{user_tz}', falling back to system time: {e}")
  104. _cached_zoneinfo = None
  105. return _cached_zoneinfo
  106. def is_in_scheduled_pause_period():
  107. """Check if current time falls within any scheduled pause period."""
  108. if not state.scheduled_pause_enabled or not state.scheduled_pause_time_slots:
  109. return False
  110. # Get cached timezone (user-selected or system default)
  111. tz_info = _get_timezone()
  112. try:
  113. # Get current time in user's timezone
  114. if tz_info:
  115. now = datetime.now(tz_info)
  116. else:
  117. now = datetime.now()
  118. except Exception as e:
  119. logger.warning(f"Error getting current time: {e}")
  120. now = datetime.now()
  121. current_time = now.time()
  122. current_weekday = now.strftime("%A").lower() # monday, tuesday, etc.
  123. for slot in state.scheduled_pause_time_slots:
  124. # Parse start and end times
  125. try:
  126. start_time = datetime_time.fromisoformat(slot['start_time'])
  127. end_time = datetime_time.fromisoformat(slot['end_time'])
  128. except (ValueError, KeyError):
  129. logger.warning(f"Invalid time format in scheduled pause slot: {slot}")
  130. continue
  131. # Check if this slot applies to today
  132. slot_applies_today = False
  133. days_setting = slot.get('days', 'daily')
  134. if days_setting == 'daily':
  135. slot_applies_today = True
  136. elif days_setting == 'weekdays':
  137. slot_applies_today = current_weekday in ['monday', 'tuesday', 'wednesday', 'thursday', 'friday']
  138. elif days_setting == 'weekends':
  139. slot_applies_today = current_weekday in ['saturday', 'sunday']
  140. elif days_setting == 'custom':
  141. custom_days = slot.get('custom_days', [])
  142. slot_applies_today = current_weekday in custom_days
  143. if not slot_applies_today:
  144. continue
  145. # Check if current time is within the pause period
  146. if start_time <= end_time:
  147. # Normal case: start and end are on the same day
  148. if start_time <= current_time <= end_time:
  149. return True
  150. else:
  151. # Time spans midnight: start is before midnight, end is after midnight
  152. if current_time >= start_time or current_time <= end_time:
  153. return True
  154. return False
  155. async def check_table_is_idle() -> bool:
  156. """
  157. Check if the table is currently idle by querying actual machine status.
  158. Returns True if idle, False if playing/moving.
  159. This checks the real machine state rather than relying on state variables,
  160. making it more reliable for detecting when table is truly idle.
  161. """
  162. # Use the connection_manager's is_machine_idle() function
  163. # Run it in a thread since it's a synchronous function
  164. return await asyncio.to_thread(connection_manager.is_machine_idle)
  165. def start_idle_led_timeout():
  166. """
  167. Start the idle LED timeout if enabled.
  168. Should be called whenever the idle effect is activated.
  169. """
  170. if not state.dw_led_idle_timeout_enabled:
  171. logger.debug("Idle LED timeout not enabled")
  172. return
  173. timeout_minutes = state.dw_led_idle_timeout_minutes
  174. if timeout_minutes <= 0:
  175. logger.debug("Idle LED timeout not configured (timeout <= 0)")
  176. return
  177. logger.debug(f"Starting idle LED timeout: {timeout_minutes} minutes")
  178. idle_timeout_manager.start_idle_timeout(
  179. timeout_minutes=timeout_minutes,
  180. state=state,
  181. check_idle_callback=check_table_is_idle
  182. )
  183. # Motion Control Thread Infrastructure
  184. @dataclass
  185. class MotionCommand:
  186. """Represents a motion command for the motion control thread."""
  187. command_type: str # 'move', 'stop', 'pause', 'resume', 'shutdown'
  188. theta: Optional[float] = None
  189. rho: Optional[float] = None
  190. speed: Optional[float] = None
  191. callback: Optional[Callable] = None
  192. future: Optional[asyncio.Future] = None
  193. class MotionControlThread:
  194. """Dedicated thread for hardware motion control operations."""
  195. def __init__(self):
  196. self.command_queue = queue.Queue()
  197. self.thread = None
  198. self.running = False
  199. self.paused = False
  200. def start(self):
  201. """Start the motion control thread."""
  202. if self.thread and self.thread.is_alive():
  203. return
  204. self.running = True
  205. self.thread = threading.Thread(target=self._motion_loop, daemon=True)
  206. self.thread.start()
  207. logger.info("Motion control thread started")
  208. def stop(self):
  209. """Stop the motion control thread."""
  210. if not self.running:
  211. return
  212. self.running = False
  213. # Send shutdown command
  214. self.command_queue.put(MotionCommand('shutdown'))
  215. if self.thread and self.thread.is_alive():
  216. self.thread.join(timeout=5.0)
  217. logger.info("Motion control thread stopped")
  218. def _motion_loop(self):
  219. """Main loop for the motion control thread."""
  220. logger.info("Motion control thread loop started")
  221. while self.running:
  222. try:
  223. # Get command with timeout to allow periodic checks
  224. command = self.command_queue.get(timeout=1.0)
  225. if command.command_type == 'shutdown':
  226. break
  227. elif command.command_type == 'move':
  228. self._execute_move(command)
  229. elif command.command_type == 'pause':
  230. self.paused = True
  231. elif command.command_type == 'resume':
  232. self.paused = False
  233. elif command.command_type == 'stop':
  234. # Clear any pending commands
  235. while not self.command_queue.empty():
  236. try:
  237. self.command_queue.get_nowait()
  238. except queue.Empty:
  239. break
  240. self.command_queue.task_done()
  241. except queue.Empty:
  242. # Timeout - continue loop for shutdown check
  243. continue
  244. except Exception as e:
  245. logger.error(f"Error in motion control thread: {e}")
  246. logger.info("Motion control thread loop ended")
  247. def _execute_move(self, command: MotionCommand):
  248. """Execute a move command in the motion thread."""
  249. try:
  250. # Wait if paused
  251. while self.paused and self.running:
  252. time.sleep(0.1)
  253. if not self.running:
  254. return
  255. # Execute the actual motion using sync version
  256. self._move_polar_sync(command.theta, command.rho, command.speed)
  257. # Signal completion if future provided
  258. if command.future and not command.future.done():
  259. command.future.get_loop().call_soon_threadsafe(
  260. command.future.set_result, None
  261. )
  262. except Exception as e:
  263. logger.error(f"Error executing move command: {e}")
  264. if command.future and not command.future.done():
  265. command.future.get_loop().call_soon_threadsafe(
  266. command.future.set_exception, e
  267. )
  268. def _move_polar_sync(self, theta: float, rho: float, speed: Optional[float] = None):
  269. """Synchronous version of move_polar for use in motion thread."""
  270. # This is the original sync logic but running in dedicated thread
  271. if state.table_type == 'dune_weaver_mini':
  272. x_scaling_factor = 2
  273. y_scaling_factor = 3.7
  274. else:
  275. x_scaling_factor = 2
  276. y_scaling_factor = 5
  277. delta_theta = theta - state.current_theta
  278. delta_rho = rho - state.current_rho
  279. x_increment = delta_theta * 100 / (2 * pi * x_scaling_factor)
  280. y_increment = delta_rho * 100 / y_scaling_factor
  281. x_total_steps = state.x_steps_per_mm * (100/x_scaling_factor)
  282. y_total_steps = state.y_steps_per_mm * (100/y_scaling_factor)
  283. offset = x_increment * (x_total_steps * x_scaling_factor / (state.gear_ratio * y_total_steps * y_scaling_factor))
  284. if state.table_type == 'dune_weaver_mini' or state.y_steps_per_mm == 546:
  285. y_increment -= offset
  286. else:
  287. y_increment += offset
  288. new_x_abs = state.machine_x + x_increment
  289. new_y_abs = state.machine_y + y_increment
  290. # Use provided speed or fall back to state.speed
  291. actual_speed = speed if speed is not None else state.speed
  292. # Call sync version of send_grbl_coordinates in this thread
  293. self._send_grbl_coordinates_sync(round(new_x_abs, 3), round(new_y_abs, 3), actual_speed)
  294. # Update state
  295. state.current_theta = theta
  296. state.current_rho = rho
  297. state.machine_x = new_x_abs
  298. state.machine_y = new_y_abs
  299. def _send_grbl_coordinates_sync(self, x: float, y: float, speed: int = 600, timeout: int = 2, home: bool = False):
  300. """Synchronous version of send_grbl_coordinates for motion thread."""
  301. logger.debug(f"Motion thread sending G-code: X{x} Y{y} at F{speed}")
  302. # Track overall attempt time
  303. overall_start_time = time.time()
  304. while True:
  305. try:
  306. gcode = f"$J=G91 G21 Y{y} F{speed}" if home else f"G1 X{x} Y{y} F{speed}"
  307. state.conn.send(gcode + "\n")
  308. logger.debug(f"Motion thread sent command: {gcode}")
  309. start_time = time.time()
  310. while True:
  311. response = state.conn.readline()
  312. logger.debug(f"Motion thread response: {response}")
  313. if response.lower() == "ok":
  314. logger.debug("Motion thread: Command execution confirmed.")
  315. return
  316. except Exception as e:
  317. error_str = str(e)
  318. logger.warning(f"Motion thread error sending command: {error_str}")
  319. # Immediately return for device not configured errors
  320. if "Device not configured" in error_str or "Errno 6" in error_str:
  321. logger.error(f"Motion thread: Device configuration error detected: {error_str}")
  322. state.stop_requested = True
  323. state.conn = None
  324. state.is_connected = False
  325. logger.info("Connection marked as disconnected due to device error")
  326. return False
  327. logger.warning(f"Motion thread: No 'ok' received for X{x} Y{y}, speed {speed}. Retrying...")
  328. time.sleep(0.1)
  329. # Global motion control thread instance
  330. motion_controller = MotionControlThread()
  331. async def cleanup_pattern_manager():
  332. """Clean up pattern manager resources"""
  333. global progress_update_task, pattern_lock, pause_event
  334. try:
  335. # Stop motion control thread
  336. motion_controller.stop()
  337. # Cancel progress update task if running
  338. if progress_update_task and not progress_update_task.done():
  339. try:
  340. progress_update_task.cancel()
  341. # Wait for task to actually cancel
  342. try:
  343. await progress_update_task
  344. except asyncio.CancelledError:
  345. pass
  346. except Exception as e:
  347. logger.error(f"Error cancelling progress update task: {e}")
  348. # Clean up pattern lock
  349. if pattern_lock:
  350. try:
  351. if pattern_lock.locked():
  352. pattern_lock.release()
  353. pattern_lock = None
  354. except Exception as e:
  355. logger.error(f"Error cleaning up pattern lock: {e}")
  356. # Clean up pause event
  357. if pause_event:
  358. try:
  359. pause_event.set() # Wake up any waiting tasks
  360. pause_event = None
  361. except Exception as e:
  362. logger.error(f"Error cleaning up pause event: {e}")
  363. # Clean up pause condition from state
  364. if state.pause_condition:
  365. try:
  366. with state.pause_condition:
  367. state.pause_condition.notify_all()
  368. state.pause_condition = threading.Condition()
  369. except Exception as e:
  370. logger.error(f"Error cleaning up pause condition: {e}")
  371. # Clear all state variables
  372. state.current_playing_file = None
  373. state.execution_progress = 0
  374. state.is_running = False
  375. state.pause_requested = False
  376. state.stop_requested = True
  377. state.is_clearing = False
  378. # Reset machine position
  379. await connection_manager.update_machine_position()
  380. logger.info("Pattern manager resources cleaned up")
  381. except Exception as e:
  382. logger.error(f"Error during pattern manager cleanup: {e}")
  383. finally:
  384. # Ensure we always reset these
  385. progress_update_task = None
  386. pattern_lock = None
  387. pause_event = None
  388. def list_theta_rho_files():
  389. files = []
  390. for root, dirs, filenames in os.walk(THETA_RHO_DIR):
  391. # Skip cached_images directories to avoid scanning thousands of WebP files
  392. if 'cached_images' in dirs:
  393. dirs.remove('cached_images')
  394. # Filter .thr files during traversal for better performance
  395. thr_files = [f for f in filenames if f.endswith('.thr')]
  396. for file in thr_files:
  397. relative_path = os.path.relpath(os.path.join(root, file), THETA_RHO_DIR)
  398. # Normalize path separators to always use forward slashes for consistency across platforms
  399. relative_path = relative_path.replace(os.sep, '/')
  400. files.append(relative_path)
  401. logger.debug(f"Found {len(files)} theta-rho files")
  402. return files
  403. def parse_theta_rho_file(file_path):
  404. """Parse a theta-rho file and return a list of (theta, rho) pairs."""
  405. coordinates = []
  406. try:
  407. logger.debug(f"Parsing theta-rho file: {file_path}")
  408. with open(file_path, 'r', encoding='utf-8') as file:
  409. for line in file:
  410. line = line.strip()
  411. if not line or line.startswith("#"):
  412. continue
  413. try:
  414. theta, rho = map(float, line.split())
  415. coordinates.append((theta, rho))
  416. except ValueError:
  417. logger.warning(f"Skipping invalid line: {line}")
  418. continue
  419. except Exception as e:
  420. logger.error(f"Error reading file: {e}")
  421. return coordinates
  422. logger.debug(f"Parsed {len(coordinates)} coordinates from {file_path}")
  423. return coordinates
  424. def get_first_rho_from_cache(file_path, cache_data=None):
  425. """Get the first rho value from cached metadata, falling back to file parsing if needed.
  426. Args:
  427. file_path: Path to the pattern file
  428. cache_data: Optional pre-loaded cache data dict to avoid repeated disk I/O
  429. """
  430. try:
  431. # Import cache_manager locally to avoid circular import
  432. from modules.core import cache_manager
  433. # Try to get from metadata cache first
  434. # Use relative path from THETA_RHO_DIR to match cache keys (which include subdirectories)
  435. file_name = os.path.relpath(file_path, THETA_RHO_DIR)
  436. # Use provided cache_data if available, otherwise load from disk
  437. if cache_data is not None:
  438. # Extract metadata directly from provided cache
  439. data_section = cache_data.get('data', {})
  440. if file_name in data_section:
  441. cached_entry = data_section[file_name]
  442. metadata = cached_entry.get('metadata')
  443. # When cache_data is provided, trust it without checking mtime
  444. # This significantly speeds up bulk operations (playlists with 1000+ patterns)
  445. # by avoiding 1000+ os.path.getmtime() calls on slow storage (e.g., Pi SD cards)
  446. if metadata and 'first_coordinate' in metadata:
  447. return metadata['first_coordinate']['y']
  448. else:
  449. # Fall back to loading cache from disk (original behavior)
  450. metadata = cache_manager.get_pattern_metadata(file_name)
  451. if metadata and 'first_coordinate' in metadata:
  452. # In the cache, 'x' is theta and 'y' is rho
  453. return metadata['first_coordinate']['y']
  454. # Fallback to parsing the file if not in cache
  455. logger.debug(f"Metadata not cached for {file_name}, parsing file")
  456. coordinates = parse_theta_rho_file(file_path)
  457. if coordinates:
  458. return coordinates[0][1] # Return rho value
  459. return None
  460. except Exception as e:
  461. logger.warning(f"Error getting first rho from cache for {file_path}: {str(e)}")
  462. return None
  463. def get_clear_pattern_file(clear_pattern_mode, path=None, cache_data=None):
  464. """Return a .thr file path based on pattern_name and table type.
  465. Args:
  466. clear_pattern_mode: The clear pattern mode to use
  467. path: Optional path to the pattern file for adaptive mode
  468. cache_data: Optional pre-loaded cache data dict to avoid repeated disk I/O
  469. """
  470. if not clear_pattern_mode or clear_pattern_mode == 'none':
  471. return
  472. # Define patterns for each table type
  473. clear_patterns = {
  474. 'dune_weaver': {
  475. 'clear_from_out': './patterns/clear_from_out.thr',
  476. 'clear_from_in': './patterns/clear_from_in.thr',
  477. 'clear_sideway': './patterns/clear_sideway.thr'
  478. },
  479. 'dune_weaver_mini': {
  480. 'clear_from_out': './patterns/clear_from_out_mini.thr',
  481. 'clear_from_in': './patterns/clear_from_in_mini.thr',
  482. 'clear_sideway': './patterns/clear_sideway_mini.thr'
  483. },
  484. 'dune_weaver_mini_pro': {
  485. 'clear_from_out': './patterns/clear_from_out_mini.thr',
  486. 'clear_from_in': './patterns/clear_from_in_mini.thr',
  487. 'clear_sideway': './patterns/clear_sideway_mini.thr'
  488. },
  489. 'dune_weaver_pro': {
  490. 'clear_from_out': './patterns/clear_from_out_pro.thr',
  491. 'clear_from_out_Ultra': './patterns/clear_from_out_Ultra.thr',
  492. 'clear_from_in': './patterns/clear_from_in_pro.thr',
  493. 'clear_from_in_Ultra': './patterns/clear_from_in_Ultra.thr',
  494. 'clear_sideway': './patterns/clear_sideway_pro.thr'
  495. }
  496. }
  497. # Get patterns for current table type, fallback to standard patterns if type not found
  498. table_patterns = clear_patterns.get(state.table_type, clear_patterns['dune_weaver'])
  499. # Check for custom patterns first
  500. if state.custom_clear_from_out and clear_pattern_mode in ['clear_from_out', 'adaptive']:
  501. if clear_pattern_mode == 'adaptive':
  502. # For adaptive mode, use cached metadata to check first rho
  503. if path:
  504. first_rho = get_first_rho_from_cache(path, cache_data)
  505. if first_rho is not None and first_rho < 0.5:
  506. # Use custom clear_from_out if set
  507. custom_path = os.path.join('./patterns', state.custom_clear_from_out)
  508. if os.path.exists(custom_path):
  509. logger.debug(f"Using custom clear_from_out: {custom_path}")
  510. return custom_path
  511. elif clear_pattern_mode == 'clear_from_out':
  512. custom_path = os.path.join('./patterns', state.custom_clear_from_out)
  513. if os.path.exists(custom_path):
  514. logger.debug(f"Using custom clear_from_out: {custom_path}")
  515. return custom_path
  516. if state.custom_clear_from_in and clear_pattern_mode in ['clear_from_in', 'adaptive']:
  517. if clear_pattern_mode == 'adaptive':
  518. # For adaptive mode, use cached metadata to check first rho
  519. if path:
  520. first_rho = get_first_rho_from_cache(path, cache_data)
  521. if first_rho is not None and first_rho >= 0.5:
  522. # Use custom clear_from_in if set
  523. custom_path = os.path.join('./patterns', state.custom_clear_from_in)
  524. if os.path.exists(custom_path):
  525. logger.debug(f"Using custom clear_from_in: {custom_path}")
  526. return custom_path
  527. elif clear_pattern_mode == 'clear_from_in':
  528. custom_path = os.path.join('./patterns', state.custom_clear_from_in)
  529. if os.path.exists(custom_path):
  530. logger.debug(f"Using custom clear_from_in: {custom_path}")
  531. return custom_path
  532. logger.debug(f"Clear pattern mode: {clear_pattern_mode} for table type: {state.table_type}")
  533. if clear_pattern_mode == "random":
  534. return random.choice(list(table_patterns.values()))
  535. if clear_pattern_mode == 'adaptive':
  536. if not path:
  537. logger.warning("No path provided for adaptive clear pattern")
  538. return random.choice(list(table_patterns.values()))
  539. # Use cached metadata to get first rho value
  540. first_rho = get_first_rho_from_cache(path, cache_data)
  541. if first_rho is None:
  542. logger.warning("Could not determine first rho value for adaptive clear pattern")
  543. return random.choice(list(table_patterns.values()))
  544. if first_rho < 0.5:
  545. return table_patterns['clear_from_out']
  546. else:
  547. return table_patterns['clear_from_in']
  548. else:
  549. if clear_pattern_mode not in table_patterns:
  550. return False
  551. return table_patterns[clear_pattern_mode]
  552. def is_clear_pattern(file_path):
  553. """Check if a file path is a clear pattern file."""
  554. # Get all possible clear pattern files for all table types
  555. clear_patterns = []
  556. for table_type in ['dune_weaver', 'dune_weaver_mini', 'dune_weaver_pro']:
  557. clear_patterns.extend([
  558. f'./patterns/clear_from_out{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr',
  559. f'./patterns/clear_from_in{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr',
  560. f'./patterns/clear_sideway{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr'
  561. ])
  562. # Normalize paths for comparison
  563. normalized_path = os.path.normpath(file_path)
  564. normalized_clear_patterns = [os.path.normpath(p) for p in clear_patterns]
  565. # Check if the file path matches any clear pattern path
  566. return normalized_path in normalized_clear_patterns
  567. async def run_theta_rho_file(file_path, is_playlist=False):
  568. """Run a theta-rho file by sending data in optimized batches with tqdm ETA tracking."""
  569. if pattern_lock.locked():
  570. logger.warning("Another pattern is already running. Cannot start a new one.")
  571. return
  572. async with pattern_lock: # This ensures only one pattern can run at a time
  573. # Start progress update task only if not part of a playlist
  574. global progress_update_task
  575. if not is_playlist and not progress_update_task:
  576. progress_update_task = asyncio.create_task(broadcast_progress())
  577. coordinates = parse_theta_rho_file(file_path)
  578. total_coordinates = len(coordinates)
  579. if total_coordinates < 2:
  580. logger.warning("Not enough coordinates for interpolation")
  581. if not is_playlist:
  582. state.current_playing_file = None
  583. state.execution_progress = None
  584. return
  585. # Determine if this is a clearing pattern
  586. is_clear_file = is_clear_pattern(file_path)
  587. if is_clear_file:
  588. initial_speed = state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  589. logger.info(f"Running clearing pattern at initial speed {initial_speed}")
  590. else:
  591. logger.info(f"Running normal pattern at initial speed {state.speed}")
  592. state.execution_progress = (0, total_coordinates, None, 0)
  593. # stop actions without resetting the playlist, and don't wait for lock (we already have it)
  594. await stop_actions(clear_playlist=False, wait_for_lock=False)
  595. state.current_playing_file = file_path
  596. state.stop_requested = False
  597. # Reset LED idle timeout activity time when pattern starts
  598. import time as time_module
  599. state.dw_led_last_activity_time = time_module.time()
  600. logger.info(f"Starting pattern execution: {file_path}")
  601. logger.info(f"t: {state.current_theta}, r: {state.current_rho}")
  602. await reset_theta()
  603. start_time = time.time()
  604. total_pause_time = 0 # Track total time spent paused (manual + scheduled)
  605. if state.led_controller:
  606. logger.info(f"Setting LED to playing effect: {state.dw_led_playing_effect}")
  607. await state.led_controller.effect_playing_async(state.dw_led_playing_effect)
  608. # Cancel idle timeout when playing starts
  609. idle_timeout_manager.cancel_timeout()
  610. with tqdm(
  611. total=total_coordinates,
  612. unit="coords",
  613. desc=f"Executing Pattern {file_path}",
  614. dynamic_ncols=True,
  615. disable=False,
  616. mininterval=1.0
  617. ) as pbar:
  618. for i, coordinate in enumerate(coordinates):
  619. theta, rho = coordinate
  620. if state.stop_requested:
  621. logger.info("Execution stopped by user")
  622. if state.led_controller:
  623. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  624. start_idle_led_timeout()
  625. break
  626. if state.skip_requested:
  627. logger.info("Skipping pattern...")
  628. await connection_manager.check_idle_async()
  629. if state.led_controller:
  630. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  631. start_idle_led_timeout()
  632. break
  633. # Wait for resume if paused (manual or scheduled)
  634. manual_pause = state.pause_requested
  635. # Only check scheduled pause during pattern if "finish pattern first" is NOT enabled
  636. scheduled_pause = is_in_scheduled_pause_period() if not state.scheduled_pause_finish_pattern else False
  637. if manual_pause or scheduled_pause:
  638. pause_start = time.time() # Track when pause started
  639. if manual_pause and scheduled_pause:
  640. logger.info("Execution paused (manual + scheduled pause active)...")
  641. elif manual_pause:
  642. logger.info("Execution paused (manual)...")
  643. else:
  644. logger.info("Execution paused (scheduled pause period)...")
  645. # Turn off LED controller if scheduled pause and control_wled is enabled
  646. if state.scheduled_pause_control_wled and state.led_controller:
  647. logger.info("Turning off LED lights during Still Sands period")
  648. await state.led_controller.set_power_async(0)
  649. # Only show idle effect if NOT in scheduled pause with LED control
  650. # (manual pause always shows idle effect)
  651. if state.led_controller and not (scheduled_pause and state.scheduled_pause_control_wled):
  652. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  653. start_idle_led_timeout()
  654. # Remember if we turned off LED controller for scheduled pause
  655. wled_was_off_for_scheduled = scheduled_pause and state.scheduled_pause_control_wled and not manual_pause
  656. # Wait until both manual pause is released AND we're outside scheduled pause period
  657. while state.pause_requested or is_in_scheduled_pause_period():
  658. await asyncio.sleep(1) # Check every second
  659. # Also wait for the pause event in case of manual pause
  660. if state.pause_requested:
  661. await pause_event.wait()
  662. total_pause_time += time.time() - pause_start # Add pause duration
  663. logger.info("Execution resumed...")
  664. if state.led_controller:
  665. # Turn LED controller back on if it was turned off for scheduled pause
  666. if wled_was_off_for_scheduled:
  667. logger.info("Turning LED lights back on as Still Sands period ended")
  668. await state.led_controller.set_power_async(1)
  669. # CRITICAL: Give LED controller time to fully power on before sending more commands
  670. # Without this delay, rapid-fire requests can crash controllers on resource-constrained Pis
  671. await asyncio.sleep(0.5)
  672. await state.led_controller.effect_playing_async(state.dw_led_playing_effect)
  673. # Cancel idle timeout when resuming from pause
  674. idle_timeout_manager.cancel_timeout()
  675. # Dynamically determine the speed for each movement
  676. # Use clear_pattern_speed if it's set and this is a clear file, otherwise use state.speed
  677. if is_clear_file and state.clear_pattern_speed is not None:
  678. current_speed = state.clear_pattern_speed
  679. else:
  680. current_speed = state.speed
  681. await move_polar(theta, rho, current_speed)
  682. # Update progress for all coordinates including the first one
  683. pbar.update(1)
  684. elapsed_time = time.time() - start_time
  685. estimated_remaining_time = (total_coordinates - (i + 1)) / pbar.format_dict['rate'] if pbar.format_dict['rate'] and total_coordinates else 0
  686. state.execution_progress = (i + 1, total_coordinates, estimated_remaining_time, elapsed_time)
  687. # Add a small delay to allow other async operations
  688. await asyncio.sleep(0.001)
  689. # Update progress one last time to show 100%
  690. elapsed_time = time.time() - start_time
  691. actual_execution_time = elapsed_time - total_pause_time
  692. state.execution_progress = (total_coordinates, total_coordinates, 0, elapsed_time)
  693. # Give WebSocket a chance to send the final update
  694. await asyncio.sleep(0.1)
  695. # Log execution time (only for completed patterns, not stopped/skipped)
  696. was_completed = not state.stop_requested and not state.skip_requested
  697. pattern_name = os.path.basename(file_path)
  698. effective_speed = state.clear_pattern_speed if (is_clear_file and state.clear_pattern_speed is not None) else state.speed
  699. log_execution_time(
  700. pattern_name=pattern_name,
  701. table_type=state.table_type,
  702. speed=effective_speed,
  703. actual_time=actual_execution_time,
  704. total_coordinates=total_coordinates,
  705. was_completed=was_completed
  706. )
  707. if not state.conn:
  708. logger.error("Device is not connected. Stopping pattern execution.")
  709. return
  710. await connection_manager.check_idle_async()
  711. # Set LED back to idle when pattern completes normally (not stopped early)
  712. if state.led_controller and not state.stop_requested:
  713. logger.info(f"Setting LED to idle effect: {state.dw_led_idle_effect}")
  714. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  715. start_idle_led_timeout()
  716. logger.debug("LED effect set to idle after pattern completion")
  717. # Only clear state if not part of a playlist
  718. if not is_playlist:
  719. state.current_playing_file = None
  720. state.execution_progress = None
  721. logger.info("Pattern execution completed and state cleared")
  722. else:
  723. logger.info("Pattern execution completed, maintaining state for playlist")
  724. # Only cancel progress update task if not part of a playlist
  725. if not is_playlist and progress_update_task:
  726. progress_update_task.cancel()
  727. try:
  728. await progress_update_task
  729. except asyncio.CancelledError:
  730. pass
  731. progress_update_task = None
  732. async def run_theta_rho_files(file_paths, pause_time=0, clear_pattern=None, run_mode="single", shuffle=False):
  733. """Run multiple .thr files in sequence with options."""
  734. state.stop_requested = False
  735. # Reset LED idle timeout activity time when playlist starts
  736. import time as time_module
  737. state.dw_led_last_activity_time = time_module.time()
  738. # Set initial playlist state
  739. state.playlist_mode = run_mode
  740. state.current_playlist_index = 0
  741. # Start progress update task for the playlist
  742. global progress_update_task
  743. if not progress_update_task:
  744. progress_update_task = asyncio.create_task(broadcast_progress())
  745. if shuffle:
  746. random.shuffle(file_paths)
  747. logger.info("Playlist shuffled")
  748. try:
  749. while True:
  750. # Load metadata cache once for all patterns (significant performance improvement)
  751. # This avoids reading the cache file from disk for every pattern
  752. cache_data = None
  753. if clear_pattern and clear_pattern in ['adaptive', 'clear_from_in', 'clear_from_out']:
  754. from modules.core import cache_manager
  755. cache_data = cache_manager.load_metadata_cache()
  756. logger.info(f"Loaded metadata cache for {len(cache_data.get('data', {}))} patterns")
  757. # Construct the complete pattern sequence
  758. pattern_sequence = []
  759. for path in file_paths:
  760. # Add clear pattern if specified
  761. if clear_pattern and clear_pattern != 'none':
  762. clear_file_path = get_clear_pattern_file(clear_pattern, path, cache_data)
  763. if clear_file_path:
  764. pattern_sequence.append(clear_file_path)
  765. # Add main pattern
  766. pattern_sequence.append(path)
  767. # Shuffle if requested
  768. if shuffle:
  769. # Get pairs of patterns (clear + main) to keep them together
  770. pairs = [pattern_sequence[i:i+2] for i in range(0, len(pattern_sequence), 2)]
  771. random.shuffle(pairs)
  772. # Flatten the pairs back into a single list
  773. pattern_sequence = [pattern for pair in pairs for pattern in pair]
  774. logger.info("Playlist shuffled")
  775. # Set the playlist to the first pattern
  776. state.current_playlist = pattern_sequence
  777. # Reset pattern counter at the start of the playlist
  778. state.patterns_since_last_home = 0
  779. # Execute the pattern sequence
  780. for idx, file_path in enumerate(pattern_sequence):
  781. state.current_playlist_index = idx
  782. if state.stop_requested:
  783. logger.info("Execution stopped")
  784. return
  785. current_is_clear = is_clear_pattern(file_path)
  786. # Check if we need to auto-home before this clear pattern
  787. # Auto-home happens after pause, before the clear pattern runs
  788. if current_is_clear and state.auto_home_enabled:
  789. # Check if we've reached the pattern threshold
  790. if state.patterns_since_last_home >= state.auto_home_after_patterns:
  791. logger.info(f"Auto-homing triggered after {state.patterns_since_last_home} patterns")
  792. try:
  793. # Perform homing using connection_manager
  794. success = await asyncio.to_thread(connection_manager.home)
  795. if success:
  796. logger.info("Auto-homing completed successfully")
  797. state.patterns_since_last_home = 0
  798. else:
  799. logger.warning("Auto-homing failed, continuing with playlist")
  800. except Exception as e:
  801. logger.error(f"Error during auto-homing: {e}")
  802. # Update state for main patterns only
  803. logger.info(f"Running pattern {file_path}")
  804. # Execute the pattern
  805. await run_theta_rho_file(file_path, is_playlist=True)
  806. # Increment pattern counter only for non-clear patterns
  807. if not current_is_clear:
  808. state.patterns_since_last_home += 1
  809. logger.debug(f"Patterns since last home: {state.patterns_since_last_home}")
  810. # Check for scheduled pause after pattern completes (when "finish pattern first" is enabled)
  811. if state.scheduled_pause_finish_pattern and is_in_scheduled_pause_period() and not state.stop_requested:
  812. logger.info("Pattern completed. Entering Still Sands period (finish pattern first mode)...")
  813. # Turn off LED controller if control_wled is enabled
  814. wled_was_off_for_scheduled = False
  815. if state.scheduled_pause_control_wled and state.led_controller:
  816. logger.info("Turning off LED lights during Still Sands period")
  817. await state.led_controller.set_power_async(0)
  818. wled_was_off_for_scheduled = True
  819. elif state.led_controller:
  820. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  821. start_idle_led_timeout()
  822. # Wait until we're outside the scheduled pause period
  823. while is_in_scheduled_pause_period() and not state.stop_requested:
  824. await asyncio.sleep(1)
  825. if not state.stop_requested:
  826. logger.info("Still Sands period ended. Resuming playlist...")
  827. if state.led_controller:
  828. if wled_was_off_for_scheduled:
  829. logger.info("Turning LED lights back on as Still Sands period ended")
  830. await state.led_controller.set_power_async(1)
  831. await asyncio.sleep(0.5) # Critical delay for LED controller
  832. await state.led_controller.effect_playing_async(state.dw_led_playing_effect)
  833. idle_timeout_manager.cancel_timeout()
  834. # Handle pause between patterns
  835. if idx < len(pattern_sequence) - 1 and not state.stop_requested and pause_time > 0 and not state.skip_requested:
  836. # Check if current pattern is a clear pattern
  837. if current_is_clear:
  838. logger.info("Skipping pause after clear pattern")
  839. else:
  840. logger.info(f"Pausing for {pause_time} seconds")
  841. state.original_pause_time = pause_time
  842. pause_start = time.time()
  843. while time.time() - pause_start < pause_time:
  844. state.pause_time_remaining = pause_start + pause_time - time.time()
  845. if state.skip_requested:
  846. logger.info("Pause interrupted by stop/skip request")
  847. break
  848. await asyncio.sleep(1)
  849. state.pause_time_remaining = 0
  850. state.skip_requested = False
  851. if run_mode == "indefinite":
  852. logger.info("Playlist completed. Restarting as per 'indefinite' run mode")
  853. if pause_time > 0:
  854. logger.debug(f"Pausing for {pause_time} seconds before restarting")
  855. pause_start = time.time()
  856. while time.time() - pause_start < pause_time:
  857. state.pause_time_remaining = pause_start + pause_time - time.time()
  858. if state.skip_requested:
  859. logger.info("Pause interrupted by stop/skip request")
  860. break
  861. await asyncio.sleep(1)
  862. state.pause_time_remaining = 0
  863. continue
  864. else:
  865. logger.info("Playlist completed")
  866. break
  867. finally:
  868. # Clean up progress update task
  869. if progress_update_task:
  870. progress_update_task.cancel()
  871. try:
  872. await progress_update_task
  873. except asyncio.CancelledError:
  874. pass
  875. progress_update_task = None
  876. # Clear all state variables
  877. state.current_playing_file = None
  878. state.execution_progress = None
  879. state.current_playlist = None
  880. state.current_playlist_index = None
  881. state.playlist_mode = None
  882. state.pause_time_remaining = 0
  883. if state.led_controller:
  884. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  885. start_idle_led_timeout()
  886. logger.info("All requested patterns completed (or stopped) and state cleared")
  887. async def stop_actions(clear_playlist = True, wait_for_lock = True):
  888. """Stop all current actions and wait for pattern to fully release.
  889. Args:
  890. clear_playlist: Whether to clear playlist state
  891. wait_for_lock: Whether to wait for pattern_lock to be released. Set to False when
  892. called from within pattern execution to avoid deadlock.
  893. """
  894. try:
  895. with state.pause_condition:
  896. state.pause_requested = False
  897. state.stop_requested = True
  898. state.current_playing_file = None
  899. state.execution_progress = None
  900. state.is_clearing = False
  901. if clear_playlist:
  902. # Clear playlist state
  903. state.current_playlist = None
  904. state.current_playlist_index = None
  905. state.playlist_mode = None
  906. state.pause_time_remaining = 0
  907. # Cancel progress update task if we're clearing the playlist
  908. global progress_update_task
  909. if progress_update_task and not progress_update_task.done():
  910. progress_update_task.cancel()
  911. state.pause_condition.notify_all()
  912. # Wait for the pattern lock to be released before continuing
  913. # This ensures that when stop_actions completes, the pattern has fully stopped
  914. # Skip this if called from within pattern execution to avoid deadlock
  915. if wait_for_lock and pattern_lock.locked():
  916. logger.info("Waiting for pattern to fully stop...")
  917. # Acquire and immediately release the lock to ensure the pattern has exited
  918. async with pattern_lock:
  919. logger.info("Pattern lock acquired - pattern has fully stopped")
  920. # Call async function directly since we're in async context
  921. await connection_manager.update_machine_position()
  922. except Exception as e:
  923. logger.error(f"Error during stop_actions: {e}")
  924. # Ensure we still update machine position even if there's an error
  925. try:
  926. await connection_manager.update_machine_position()
  927. except Exception as update_err:
  928. logger.error(f"Error updating machine position on error: {update_err}")
  929. async def move_polar(theta, rho, speed=None):
  930. """
  931. Queue a motion command to be executed in the dedicated motion control thread.
  932. This makes motion control non-blocking for API endpoints.
  933. Args:
  934. theta (float): Target theta coordinate
  935. rho (float): Target rho coordinate
  936. speed (int, optional): Speed override. If None, uses state.speed
  937. """
  938. # Ensure motion control thread is running
  939. if not motion_controller.running:
  940. motion_controller.start()
  941. # Create future for async/await pattern
  942. loop = asyncio.get_event_loop()
  943. future = loop.create_future()
  944. # Create and queue motion command
  945. command = MotionCommand(
  946. command_type='move',
  947. theta=theta,
  948. rho=rho,
  949. speed=speed,
  950. future=future
  951. )
  952. motion_controller.command_queue.put(command)
  953. logger.debug(f"Queued motion command: theta={theta}, rho={rho}, speed={speed}")
  954. # Wait for command completion
  955. await future
  956. def pause_execution():
  957. """Pause pattern execution using asyncio Event."""
  958. logger.info("Pausing pattern execution")
  959. state.pause_requested = True
  960. pause_event.clear() # Clear the event to pause execution
  961. return True
  962. def resume_execution():
  963. """Resume pattern execution using asyncio Event."""
  964. logger.info("Resuming pattern execution")
  965. state.pause_requested = False
  966. pause_event.set() # Set the event to resume execution
  967. return True
  968. async def reset_theta():
  969. logger.info('Resetting Theta')
  970. state.current_theta = state.current_theta % (2 * pi)
  971. # Call async function directly since we're in async context
  972. await connection_manager.update_machine_position()
  973. def set_speed(new_speed):
  974. state.speed = new_speed
  975. logger.info(f'Set new state.speed {new_speed}')
  976. def get_status():
  977. """Get the current status of pattern execution."""
  978. status = {
  979. "current_file": state.current_playing_file,
  980. "is_paused": state.pause_requested or is_in_scheduled_pause_period(),
  981. "manual_pause": state.pause_requested,
  982. "scheduled_pause": is_in_scheduled_pause_period(),
  983. "is_running": bool(state.current_playing_file and not state.stop_requested),
  984. "progress": None,
  985. "playlist": None,
  986. "speed": state.speed,
  987. "pause_time_remaining": state.pause_time_remaining,
  988. "original_pause_time": getattr(state, 'original_pause_time', None),
  989. "connection_status": state.conn.is_connected() if state.conn else False,
  990. "current_theta": state.current_theta,
  991. "current_rho": state.current_rho
  992. }
  993. # Add playlist information if available
  994. if state.current_playlist and state.current_playlist_index is not None:
  995. next_index = state.current_playlist_index + 1
  996. status["playlist"] = {
  997. "current_index": state.current_playlist_index,
  998. "total_files": len(state.current_playlist),
  999. "mode": state.playlist_mode,
  1000. "next_file": state.current_playlist[next_index] if next_index < len(state.current_playlist) else None
  1001. }
  1002. if state.execution_progress:
  1003. current, total, remaining_time, elapsed_time = state.execution_progress
  1004. status["progress"] = {
  1005. "current": current,
  1006. "total": total,
  1007. "remaining_time": remaining_time,
  1008. "elapsed_time": elapsed_time,
  1009. "percentage": (current / total * 100) if total > 0 else 0
  1010. }
  1011. return status
  1012. async def broadcast_progress():
  1013. """Background task to broadcast progress updates."""
  1014. from main import broadcast_status_update
  1015. while True:
  1016. # Send status updates regardless of pattern_lock state
  1017. status = get_status()
  1018. # Use the existing broadcast function from main.py
  1019. await broadcast_status_update(status)
  1020. # Check if we should stop broadcasting
  1021. if not state.current_playlist:
  1022. # If no playlist, only stop if no pattern is being executed
  1023. if not pattern_lock.locked():
  1024. logger.info("No playlist or pattern running, stopping broadcast")
  1025. break
  1026. # Wait before next update
  1027. await asyncio.sleep(1)