1
0

pattern_manager.py 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236
  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. # Signal stop to allow any running pattern to exit gracefully
  336. state.stop_requested = True
  337. # Stop motion control thread
  338. motion_controller.stop()
  339. # Cancel progress update task if running
  340. if progress_update_task and not progress_update_task.done():
  341. try:
  342. progress_update_task.cancel()
  343. # Wait for task to actually cancel
  344. try:
  345. await progress_update_task
  346. except asyncio.CancelledError:
  347. pass
  348. except Exception as e:
  349. logger.error(f"Error cancelling progress update task: {e}")
  350. # Clean up pattern lock - wait for it to be released naturally, don't force release
  351. # Force releasing an asyncio.Lock can corrupt internal state if held by another coroutine
  352. if pattern_lock and pattern_lock.locked():
  353. logger.info("Pattern lock is held, waiting for release (max 5s)...")
  354. try:
  355. # Wait with timeout for the lock to become available
  356. async with asyncio.timeout(5.0):
  357. async with pattern_lock:
  358. pass # Lock acquired means previous holder released it
  359. logger.info("Pattern lock released normally")
  360. except asyncio.TimeoutError:
  361. logger.warning("Timed out waiting for pattern lock - creating fresh lock")
  362. except Exception as e:
  363. logger.error(f"Error waiting for pattern lock: {e}")
  364. # Clean up pause event - wake up any waiting tasks, then create fresh event
  365. if pause_event:
  366. try:
  367. pause_event.set() # Wake up any waiting tasks
  368. except Exception as e:
  369. logger.error(f"Error setting pause event: {e}")
  370. # Clean up pause condition from state
  371. if state.pause_condition:
  372. try:
  373. with state.pause_condition:
  374. state.pause_condition.notify_all()
  375. state.pause_condition = threading.Condition()
  376. except Exception as e:
  377. logger.error(f"Error cleaning up pause condition: {e}")
  378. # Clear all state variables
  379. state.current_playing_file = None
  380. state.execution_progress = 0
  381. state.is_running = False
  382. state.pause_requested = False
  383. state.stop_requested = True
  384. state.is_clearing = False
  385. # Reset machine position
  386. await connection_manager.update_machine_position()
  387. logger.info("Pattern manager resources cleaned up")
  388. except Exception as e:
  389. logger.error(f"Error during pattern manager cleanup: {e}")
  390. finally:
  391. # Reset to fresh instances instead of None to allow continued operation
  392. progress_update_task = None
  393. pattern_lock = asyncio.Lock() # Fresh lock instead of None
  394. pause_event = asyncio.Event() # Fresh event instead of None
  395. pause_event.set() # Initially not paused
  396. def list_theta_rho_files():
  397. files = []
  398. for root, dirs, filenames in os.walk(THETA_RHO_DIR):
  399. # Skip cached_images directories to avoid scanning thousands of WebP files
  400. if 'cached_images' in dirs:
  401. dirs.remove('cached_images')
  402. # Filter .thr files during traversal for better performance
  403. thr_files = [f for f in filenames if f.endswith('.thr')]
  404. for file in thr_files:
  405. relative_path = os.path.relpath(os.path.join(root, file), THETA_RHO_DIR)
  406. # Normalize path separators to always use forward slashes for consistency across platforms
  407. relative_path = relative_path.replace(os.sep, '/')
  408. files.append(relative_path)
  409. logger.debug(f"Found {len(files)} theta-rho files")
  410. return files
  411. def parse_theta_rho_file(file_path):
  412. """Parse a theta-rho file and return a list of (theta, rho) pairs."""
  413. coordinates = []
  414. try:
  415. logger.debug(f"Parsing theta-rho file: {file_path}")
  416. with open(file_path, 'r', encoding='utf-8') as file:
  417. for line in file:
  418. line = line.strip()
  419. if not line or line.startswith("#"):
  420. continue
  421. try:
  422. theta, rho = map(float, line.split())
  423. coordinates.append((theta, rho))
  424. except ValueError:
  425. logger.warning(f"Skipping invalid line: {line}")
  426. continue
  427. except Exception as e:
  428. logger.error(f"Error reading file: {e}")
  429. return coordinates
  430. logger.debug(f"Parsed {len(coordinates)} coordinates from {file_path}")
  431. return coordinates
  432. def get_first_rho_from_cache(file_path, cache_data=None):
  433. """Get the first rho value from cached metadata, falling back to file parsing if needed.
  434. Args:
  435. file_path: Path to the pattern file
  436. cache_data: Optional pre-loaded cache data dict to avoid repeated disk I/O
  437. """
  438. try:
  439. # Import cache_manager locally to avoid circular import
  440. from modules.core import cache_manager
  441. # Try to get from metadata cache first
  442. # Use relative path from THETA_RHO_DIR to match cache keys (which include subdirectories)
  443. file_name = os.path.relpath(file_path, THETA_RHO_DIR)
  444. # Use provided cache_data if available, otherwise load from disk
  445. if cache_data is not None:
  446. # Extract metadata directly from provided cache
  447. data_section = cache_data.get('data', {})
  448. if file_name in data_section:
  449. cached_entry = data_section[file_name]
  450. metadata = cached_entry.get('metadata')
  451. # When cache_data is provided, trust it without checking mtime
  452. # This significantly speeds up bulk operations (playlists with 1000+ patterns)
  453. # by avoiding 1000+ os.path.getmtime() calls on slow storage (e.g., Pi SD cards)
  454. if metadata and 'first_coordinate' in metadata:
  455. return metadata['first_coordinate']['y']
  456. else:
  457. # Fall back to loading cache from disk (original behavior)
  458. metadata = cache_manager.get_pattern_metadata(file_name)
  459. if metadata and 'first_coordinate' in metadata:
  460. # In the cache, 'x' is theta and 'y' is rho
  461. return metadata['first_coordinate']['y']
  462. # Fallback to parsing the file if not in cache
  463. logger.debug(f"Metadata not cached for {file_name}, parsing file")
  464. coordinates = parse_theta_rho_file(file_path)
  465. if coordinates:
  466. return coordinates[0][1] # Return rho value
  467. return None
  468. except Exception as e:
  469. logger.warning(f"Error getting first rho from cache for {file_path}: {str(e)}")
  470. return None
  471. def get_clear_pattern_file(clear_pattern_mode, path=None, cache_data=None):
  472. """Return a .thr file path based on pattern_name and table type.
  473. Args:
  474. clear_pattern_mode: The clear pattern mode to use
  475. path: Optional path to the pattern file for adaptive mode
  476. cache_data: Optional pre-loaded cache data dict to avoid repeated disk I/O
  477. """
  478. if not clear_pattern_mode or clear_pattern_mode == 'none':
  479. return
  480. # Define patterns for each table type
  481. clear_patterns = {
  482. 'dune_weaver': {
  483. 'clear_from_out': './patterns/clear_from_out.thr',
  484. 'clear_from_in': './patterns/clear_from_in.thr',
  485. 'clear_sideway': './patterns/clear_sideway.thr'
  486. },
  487. 'dune_weaver_mini': {
  488. 'clear_from_out': './patterns/clear_from_out_mini.thr',
  489. 'clear_from_in': './patterns/clear_from_in_mini.thr',
  490. 'clear_sideway': './patterns/clear_sideway_mini.thr'
  491. },
  492. 'dune_weaver_mini_pro': {
  493. 'clear_from_out': './patterns/clear_from_out_mini.thr',
  494. 'clear_from_in': './patterns/clear_from_in_mini.thr',
  495. 'clear_sideway': './patterns/clear_sideway_mini.thr'
  496. },
  497. 'dune_weaver_pro': {
  498. 'clear_from_out': './patterns/clear_from_out_pro.thr',
  499. 'clear_from_out_Ultra': './patterns/clear_from_out_Ultra.thr',
  500. 'clear_from_in': './patterns/clear_from_in_pro.thr',
  501. 'clear_from_in_Ultra': './patterns/clear_from_in_Ultra.thr',
  502. 'clear_sideway': './patterns/clear_sideway_pro.thr'
  503. }
  504. }
  505. # Get patterns for current table type, fallback to standard patterns if type not found
  506. table_patterns = clear_patterns.get(state.table_type, clear_patterns['dune_weaver'])
  507. # Check for custom patterns first
  508. if state.custom_clear_from_out and clear_pattern_mode in ['clear_from_out', 'adaptive']:
  509. if clear_pattern_mode == 'adaptive':
  510. # For adaptive mode, use cached metadata to check first rho
  511. if path:
  512. first_rho = get_first_rho_from_cache(path, cache_data)
  513. if first_rho is not None and first_rho < 0.5:
  514. # Use custom clear_from_out if set
  515. custom_path = os.path.join('./patterns', state.custom_clear_from_out)
  516. if os.path.exists(custom_path):
  517. logger.debug(f"Using custom clear_from_out: {custom_path}")
  518. return custom_path
  519. elif clear_pattern_mode == 'clear_from_out':
  520. custom_path = os.path.join('./patterns', state.custom_clear_from_out)
  521. if os.path.exists(custom_path):
  522. logger.debug(f"Using custom clear_from_out: {custom_path}")
  523. return custom_path
  524. if state.custom_clear_from_in and clear_pattern_mode in ['clear_from_in', 'adaptive']:
  525. if clear_pattern_mode == 'adaptive':
  526. # For adaptive mode, use cached metadata to check first rho
  527. if path:
  528. first_rho = get_first_rho_from_cache(path, cache_data)
  529. if first_rho is not None and first_rho >= 0.5:
  530. # Use custom clear_from_in if set
  531. custom_path = os.path.join('./patterns', state.custom_clear_from_in)
  532. if os.path.exists(custom_path):
  533. logger.debug(f"Using custom clear_from_in: {custom_path}")
  534. return custom_path
  535. elif clear_pattern_mode == 'clear_from_in':
  536. custom_path = os.path.join('./patterns', state.custom_clear_from_in)
  537. if os.path.exists(custom_path):
  538. logger.debug(f"Using custom clear_from_in: {custom_path}")
  539. return custom_path
  540. logger.debug(f"Clear pattern mode: {clear_pattern_mode} for table type: {state.table_type}")
  541. if clear_pattern_mode == "random":
  542. return random.choice(list(table_patterns.values()))
  543. if clear_pattern_mode == 'adaptive':
  544. if not path:
  545. logger.warning("No path provided for adaptive clear pattern")
  546. return random.choice(list(table_patterns.values()))
  547. # Use cached metadata to get first rho value
  548. first_rho = get_first_rho_from_cache(path, cache_data)
  549. if first_rho is None:
  550. logger.warning("Could not determine first rho value for adaptive clear pattern")
  551. return random.choice(list(table_patterns.values()))
  552. if first_rho < 0.5:
  553. return table_patterns['clear_from_out']
  554. else:
  555. return table_patterns['clear_from_in']
  556. else:
  557. if clear_pattern_mode not in table_patterns:
  558. return False
  559. return table_patterns[clear_pattern_mode]
  560. def is_clear_pattern(file_path):
  561. """Check if a file path is a clear pattern file."""
  562. # Get all possible clear pattern files for all table types
  563. clear_patterns = []
  564. for table_type in ['dune_weaver', 'dune_weaver_mini', 'dune_weaver_pro']:
  565. clear_patterns.extend([
  566. f'./patterns/clear_from_out{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr',
  567. f'./patterns/clear_from_in{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr',
  568. f'./patterns/clear_sideway{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr'
  569. ])
  570. # Normalize paths for comparison
  571. normalized_path = os.path.normpath(file_path)
  572. normalized_clear_patterns = [os.path.normpath(p) for p in clear_patterns]
  573. # Check if the file path matches any clear pattern path
  574. return normalized_path in normalized_clear_patterns
  575. async def run_theta_rho_file(file_path, is_playlist=False):
  576. """Run a theta-rho file by sending data in optimized batches with tqdm ETA tracking."""
  577. if pattern_lock.locked():
  578. logger.warning("Another pattern is already running. Cannot start a new one.")
  579. return
  580. async with pattern_lock: # This ensures only one pattern can run at a time
  581. # Start progress update task only if not part of a playlist
  582. global progress_update_task
  583. if not is_playlist and not progress_update_task:
  584. progress_update_task = asyncio.create_task(broadcast_progress())
  585. coordinates = parse_theta_rho_file(file_path)
  586. total_coordinates = len(coordinates)
  587. if total_coordinates < 2:
  588. logger.warning("Not enough coordinates for interpolation")
  589. if not is_playlist:
  590. state.current_playing_file = None
  591. state.execution_progress = None
  592. return
  593. # Determine if this is a clearing pattern
  594. is_clear_file = is_clear_pattern(file_path)
  595. if is_clear_file:
  596. initial_speed = state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  597. logger.info(f"Running clearing pattern at initial speed {initial_speed}")
  598. else:
  599. logger.info(f"Running normal pattern at initial speed {state.speed}")
  600. state.execution_progress = (0, total_coordinates, None, 0)
  601. # stop actions without resetting the playlist, and don't wait for lock (we already have it)
  602. await stop_actions(clear_playlist=False, wait_for_lock=False)
  603. state.current_playing_file = file_path
  604. state.stop_requested = False
  605. # Reset LED idle timeout activity time when pattern starts
  606. import time as time_module
  607. state.dw_led_last_activity_time = time_module.time()
  608. logger.info(f"Starting pattern execution: {file_path}")
  609. logger.info(f"t: {state.current_theta}, r: {state.current_rho}")
  610. await reset_theta()
  611. start_time = time.time()
  612. total_pause_time = 0 # Track total time spent paused (manual + scheduled)
  613. if state.led_controller:
  614. logger.info(f"Setting LED to playing effect: {state.dw_led_playing_effect}")
  615. await state.led_controller.effect_playing_async(state.dw_led_playing_effect)
  616. # Cancel idle timeout when playing starts
  617. idle_timeout_manager.cancel_timeout()
  618. with tqdm(
  619. total=total_coordinates,
  620. unit="coords",
  621. desc=f"Executing Pattern {file_path}",
  622. dynamic_ncols=True,
  623. disable=False,
  624. mininterval=1.0
  625. ) as pbar:
  626. for i, coordinate in enumerate(coordinates):
  627. theta, rho = coordinate
  628. if state.stop_requested:
  629. logger.info("Execution stopped by user")
  630. if state.led_controller:
  631. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  632. start_idle_led_timeout()
  633. break
  634. if state.skip_requested:
  635. logger.info("Skipping pattern...")
  636. await connection_manager.check_idle_async()
  637. if state.led_controller:
  638. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  639. start_idle_led_timeout()
  640. break
  641. # Wait for resume if paused (manual or scheduled)
  642. manual_pause = state.pause_requested
  643. # Only check scheduled pause during pattern if "finish pattern first" is NOT enabled
  644. scheduled_pause = is_in_scheduled_pause_period() if not state.scheduled_pause_finish_pattern else False
  645. if manual_pause or scheduled_pause:
  646. pause_start = time.time() # Track when pause started
  647. if manual_pause and scheduled_pause:
  648. logger.info("Execution paused (manual + scheduled pause active)...")
  649. elif manual_pause:
  650. logger.info("Execution paused (manual)...")
  651. else:
  652. logger.info("Execution paused (scheduled pause period)...")
  653. # Turn off LED controller if scheduled pause and control_wled is enabled
  654. if state.scheduled_pause_control_wled and state.led_controller:
  655. logger.info("Turning off LED lights during Still Sands period")
  656. await state.led_controller.set_power_async(0)
  657. # Only show idle effect if NOT in scheduled pause with LED control
  658. # (manual pause always shows idle effect)
  659. if state.led_controller and not (scheduled_pause and state.scheduled_pause_control_wled):
  660. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  661. start_idle_led_timeout()
  662. # Remember if we turned off LED controller for scheduled pause
  663. wled_was_off_for_scheduled = scheduled_pause and state.scheduled_pause_control_wled and not manual_pause
  664. # Wait until both manual pause is released AND we're outside scheduled pause period
  665. while state.pause_requested or is_in_scheduled_pause_period():
  666. if state.pause_requested:
  667. # For manual pause, wait directly on the event for immediate response
  668. # The while loop re-checks state after wake to handle rapid pause/resume
  669. await pause_event.wait()
  670. else:
  671. # For scheduled pause only, check periodically
  672. await asyncio.sleep(1)
  673. total_pause_time += time.time() - pause_start # Add pause duration
  674. logger.info("Execution resumed...")
  675. if state.led_controller:
  676. # Turn LED controller back on if it was turned off for scheduled pause
  677. if wled_was_off_for_scheduled:
  678. logger.info("Turning LED lights back on as Still Sands period ended")
  679. await state.led_controller.set_power_async(1)
  680. # CRITICAL: Give LED controller time to fully power on before sending more commands
  681. # Without this delay, rapid-fire requests can crash controllers on resource-constrained Pis
  682. await asyncio.sleep(0.5)
  683. await state.led_controller.effect_playing_async(state.dw_led_playing_effect)
  684. # Cancel idle timeout when resuming from pause
  685. idle_timeout_manager.cancel_timeout()
  686. # Dynamically determine the speed for each movement
  687. # Use clear_pattern_speed if it's set and this is a clear file, otherwise use state.speed
  688. if is_clear_file and state.clear_pattern_speed is not None:
  689. current_speed = state.clear_pattern_speed
  690. else:
  691. current_speed = state.speed
  692. await move_polar(theta, rho, current_speed)
  693. # Update progress for all coordinates including the first one
  694. pbar.update(1)
  695. elapsed_time = time.time() - start_time
  696. estimated_remaining_time = (total_coordinates - (i + 1)) / pbar.format_dict['rate'] if pbar.format_dict['rate'] and total_coordinates else 0
  697. state.execution_progress = (i + 1, total_coordinates, estimated_remaining_time, elapsed_time)
  698. # Add a small delay to allow other async operations
  699. await asyncio.sleep(0.001)
  700. # Update progress one last time to show 100%
  701. elapsed_time = time.time() - start_time
  702. actual_execution_time = elapsed_time - total_pause_time
  703. state.execution_progress = (total_coordinates, total_coordinates, 0, elapsed_time)
  704. # Give WebSocket a chance to send the final update
  705. await asyncio.sleep(0.1)
  706. # Log execution time (only for completed patterns, not stopped/skipped)
  707. was_completed = not state.stop_requested and not state.skip_requested
  708. pattern_name = os.path.basename(file_path)
  709. effective_speed = state.clear_pattern_speed if (is_clear_file and state.clear_pattern_speed is not None) else state.speed
  710. log_execution_time(
  711. pattern_name=pattern_name,
  712. table_type=state.table_type,
  713. speed=effective_speed,
  714. actual_time=actual_execution_time,
  715. total_coordinates=total_coordinates,
  716. was_completed=was_completed
  717. )
  718. if not state.conn:
  719. logger.error("Device is not connected. Stopping pattern execution.")
  720. return
  721. await connection_manager.check_idle_async()
  722. # Set LED back to idle when pattern completes normally (not stopped early)
  723. if state.led_controller and not state.stop_requested:
  724. logger.info(f"Setting LED to idle effect: {state.dw_led_idle_effect}")
  725. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  726. start_idle_led_timeout()
  727. logger.debug("LED effect set to idle after pattern completion")
  728. # Only clear state if not part of a playlist
  729. if not is_playlist:
  730. state.current_playing_file = None
  731. state.execution_progress = None
  732. logger.info("Pattern execution completed and state cleared")
  733. else:
  734. logger.info("Pattern execution completed, maintaining state for playlist")
  735. # Only cancel progress update task if not part of a playlist
  736. if not is_playlist and progress_update_task:
  737. progress_update_task.cancel()
  738. try:
  739. await progress_update_task
  740. except asyncio.CancelledError:
  741. pass
  742. progress_update_task = None
  743. async def run_theta_rho_files(file_paths, pause_time=0, clear_pattern=None, run_mode="single", shuffle=False):
  744. """Run multiple .thr files in sequence with options."""
  745. state.stop_requested = False
  746. # Reset LED idle timeout activity time when playlist starts
  747. import time as time_module
  748. state.dw_led_last_activity_time = time_module.time()
  749. # Set initial playlist state
  750. state.playlist_mode = run_mode
  751. state.current_playlist_index = 0
  752. # Start progress update task for the playlist
  753. global progress_update_task
  754. if not progress_update_task:
  755. progress_update_task = asyncio.create_task(broadcast_progress())
  756. if shuffle:
  757. random.shuffle(file_paths)
  758. logger.info("Playlist shuffled")
  759. try:
  760. while True:
  761. # Load metadata cache once for all patterns (significant performance improvement)
  762. # This avoids reading the cache file from disk for every pattern
  763. cache_data = None
  764. if clear_pattern and clear_pattern in ['adaptive', 'clear_from_in', 'clear_from_out']:
  765. from modules.core import cache_manager
  766. cache_data = cache_manager.load_metadata_cache()
  767. logger.info(f"Loaded metadata cache for {len(cache_data.get('data', {}))} patterns")
  768. # Construct the complete pattern sequence
  769. pattern_sequence = []
  770. for path in file_paths:
  771. # Add clear pattern if specified
  772. if clear_pattern and clear_pattern != 'none':
  773. clear_file_path = get_clear_pattern_file(clear_pattern, path, cache_data)
  774. if clear_file_path:
  775. pattern_sequence.append(clear_file_path)
  776. # Add main pattern
  777. pattern_sequence.append(path)
  778. # Shuffle if requested
  779. if shuffle:
  780. # Get pairs of patterns (clear + main) to keep them together
  781. pairs = [pattern_sequence[i:i+2] for i in range(0, len(pattern_sequence), 2)]
  782. random.shuffle(pairs)
  783. # Flatten the pairs back into a single list
  784. pattern_sequence = [pattern for pair in pairs for pattern in pair]
  785. logger.info("Playlist shuffled")
  786. # Set the playlist to the first pattern
  787. state.current_playlist = pattern_sequence
  788. # Reset pattern counter at the start of the playlist
  789. state.patterns_since_last_home = 0
  790. # Execute the pattern sequence
  791. for idx, file_path in enumerate(pattern_sequence):
  792. state.current_playlist_index = idx
  793. if state.stop_requested:
  794. logger.info("Execution stopped")
  795. return
  796. current_is_clear = is_clear_pattern(file_path)
  797. # Check if we need to auto-home before this clear pattern
  798. # Auto-home happens after pause, before the clear pattern runs
  799. if current_is_clear and state.auto_home_enabled:
  800. # Check if we've reached the pattern threshold
  801. if state.patterns_since_last_home >= state.auto_home_after_patterns:
  802. logger.info(f"Auto-homing triggered after {state.patterns_since_last_home} patterns")
  803. try:
  804. # Perform homing using connection_manager
  805. success = await asyncio.to_thread(connection_manager.home)
  806. if success:
  807. logger.info("Auto-homing completed successfully")
  808. state.patterns_since_last_home = 0
  809. else:
  810. logger.warning("Auto-homing failed, continuing with playlist")
  811. except Exception as e:
  812. logger.error(f"Error during auto-homing: {e}")
  813. # Update state for main patterns only
  814. logger.info(f"Running pattern {file_path}")
  815. # Execute the pattern
  816. await run_theta_rho_file(file_path, is_playlist=True)
  817. # Increment pattern counter only for non-clear patterns
  818. if not current_is_clear:
  819. state.patterns_since_last_home += 1
  820. logger.debug(f"Patterns since last home: {state.patterns_since_last_home}")
  821. # Check for scheduled pause after pattern completes (when "finish pattern first" is enabled)
  822. if state.scheduled_pause_finish_pattern and is_in_scheduled_pause_period() and not state.stop_requested:
  823. logger.info("Pattern completed. Entering Still Sands period (finish pattern first mode)...")
  824. # Turn off LED controller if control_wled is enabled
  825. wled_was_off_for_scheduled = False
  826. if state.scheduled_pause_control_wled and state.led_controller:
  827. logger.info("Turning off LED lights during Still Sands period")
  828. await state.led_controller.set_power_async(0)
  829. wled_was_off_for_scheduled = True
  830. elif state.led_controller:
  831. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  832. start_idle_led_timeout()
  833. # Wait until we're outside the scheduled pause period
  834. while is_in_scheduled_pause_period() and not state.stop_requested:
  835. await asyncio.sleep(1)
  836. if not state.stop_requested:
  837. logger.info("Still Sands period ended. Resuming playlist...")
  838. if state.led_controller:
  839. if wled_was_off_for_scheduled:
  840. logger.info("Turning LED lights back on as Still Sands period ended")
  841. await state.led_controller.set_power_async(1)
  842. await asyncio.sleep(0.5) # Critical delay for LED controller
  843. await state.led_controller.effect_playing_async(state.dw_led_playing_effect)
  844. idle_timeout_manager.cancel_timeout()
  845. # Handle pause between patterns
  846. if idx < len(pattern_sequence) - 1 and not state.stop_requested and pause_time > 0 and not state.skip_requested:
  847. # Check if current pattern is a clear pattern
  848. if current_is_clear:
  849. logger.info("Skipping pause after clear pattern")
  850. else:
  851. logger.info(f"Pausing for {pause_time} seconds")
  852. state.original_pause_time = pause_time
  853. pause_start = time.time()
  854. while time.time() - pause_start < pause_time:
  855. state.pause_time_remaining = pause_start + pause_time - time.time()
  856. if state.skip_requested:
  857. logger.info("Pause interrupted by stop/skip request")
  858. break
  859. await asyncio.sleep(1)
  860. state.pause_time_remaining = 0
  861. state.skip_requested = False
  862. if run_mode == "indefinite":
  863. logger.info("Playlist completed. Restarting as per 'indefinite' run mode")
  864. if pause_time > 0:
  865. logger.debug(f"Pausing for {pause_time} seconds before restarting")
  866. pause_start = time.time()
  867. while time.time() - pause_start < pause_time:
  868. state.pause_time_remaining = pause_start + pause_time - time.time()
  869. if state.skip_requested:
  870. logger.info("Pause interrupted by stop/skip request")
  871. break
  872. await asyncio.sleep(1)
  873. state.pause_time_remaining = 0
  874. continue
  875. else:
  876. logger.info("Playlist completed")
  877. break
  878. finally:
  879. # Clean up progress update task
  880. if progress_update_task:
  881. progress_update_task.cancel()
  882. try:
  883. await progress_update_task
  884. except asyncio.CancelledError:
  885. pass
  886. progress_update_task = None
  887. # Clear all state variables
  888. state.current_playing_file = None
  889. state.execution_progress = None
  890. state.current_playlist = None
  891. state.current_playlist_index = None
  892. state.playlist_mode = None
  893. state.pause_time_remaining = 0
  894. if state.led_controller:
  895. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  896. start_idle_led_timeout()
  897. logger.info("All requested patterns completed (or stopped) and state cleared")
  898. async def stop_actions(clear_playlist = True, wait_for_lock = True):
  899. """Stop all current actions and wait for pattern to fully release.
  900. Args:
  901. clear_playlist: Whether to clear playlist state
  902. wait_for_lock: Whether to wait for pattern_lock to be released. Set to False when
  903. called from within pattern execution to avoid deadlock.
  904. """
  905. try:
  906. with state.pause_condition:
  907. state.pause_requested = False
  908. state.stop_requested = True
  909. state.current_playing_file = None
  910. state.execution_progress = None
  911. state.is_clearing = False
  912. if clear_playlist:
  913. # Clear playlist state
  914. state.current_playlist = None
  915. state.current_playlist_index = None
  916. state.playlist_mode = None
  917. state.pause_time_remaining = 0
  918. # Cancel progress update task if we're clearing the playlist
  919. global progress_update_task
  920. if progress_update_task and not progress_update_task.done():
  921. progress_update_task.cancel()
  922. state.pause_condition.notify_all()
  923. # Wait for the pattern lock to be released before continuing
  924. # This ensures that when stop_actions completes, the pattern has fully stopped
  925. # Skip this if called from within pattern execution to avoid deadlock
  926. if wait_for_lock and pattern_lock.locked():
  927. logger.info("Waiting for pattern to fully stop...")
  928. # Acquire and immediately release the lock to ensure the pattern has exited
  929. async with pattern_lock:
  930. logger.info("Pattern lock acquired - pattern has fully stopped")
  931. # Call async function directly since we're in async context
  932. await connection_manager.update_machine_position()
  933. except Exception as e:
  934. logger.error(f"Error during stop_actions: {e}")
  935. # Ensure we still update machine position even if there's an error
  936. try:
  937. await connection_manager.update_machine_position()
  938. except Exception as update_err:
  939. logger.error(f"Error updating machine position on error: {update_err}")
  940. async def move_polar(theta, rho, speed=None):
  941. """
  942. Queue a motion command to be executed in the dedicated motion control thread.
  943. This makes motion control non-blocking for API endpoints.
  944. Args:
  945. theta (float): Target theta coordinate
  946. rho (float): Target rho coordinate
  947. speed (int, optional): Speed override. If None, uses state.speed
  948. """
  949. # Ensure motion control thread is running
  950. if not motion_controller.running:
  951. motion_controller.start()
  952. # Create future for async/await pattern
  953. loop = asyncio.get_event_loop()
  954. future = loop.create_future()
  955. # Create and queue motion command
  956. command = MotionCommand(
  957. command_type='move',
  958. theta=theta,
  959. rho=rho,
  960. speed=speed,
  961. future=future
  962. )
  963. motion_controller.command_queue.put(command)
  964. logger.debug(f"Queued motion command: theta={theta}, rho={rho}, speed={speed}")
  965. # Wait for command completion
  966. await future
  967. def pause_execution():
  968. """Pause pattern execution using asyncio Event."""
  969. logger.info("Pausing pattern execution")
  970. state.pause_requested = True
  971. pause_event.clear() # Clear the event to pause execution
  972. return True
  973. def resume_execution():
  974. """Resume pattern execution using asyncio Event."""
  975. logger.info("Resuming pattern execution")
  976. state.pause_requested = False
  977. pause_event.set() # Set the event to resume execution
  978. return True
  979. async def reset_theta():
  980. logger.info('Resetting Theta')
  981. state.current_theta = state.current_theta % (2 * pi)
  982. # Call async function directly since we're in async context
  983. await connection_manager.update_machine_position()
  984. def set_speed(new_speed):
  985. state.speed = new_speed
  986. logger.info(f'Set new state.speed {new_speed}')
  987. def get_status():
  988. """Get the current status of pattern execution."""
  989. status = {
  990. "current_file": state.current_playing_file,
  991. "is_paused": state.pause_requested or is_in_scheduled_pause_period(),
  992. "manual_pause": state.pause_requested,
  993. "scheduled_pause": is_in_scheduled_pause_period(),
  994. "is_running": bool(state.current_playing_file and not state.stop_requested),
  995. "progress": None,
  996. "playlist": None,
  997. "speed": state.speed,
  998. "pause_time_remaining": state.pause_time_remaining,
  999. "original_pause_time": getattr(state, 'original_pause_time', None),
  1000. "connection_status": state.conn.is_connected() if state.conn else False,
  1001. "current_theta": state.current_theta,
  1002. "current_rho": state.current_rho
  1003. }
  1004. # Add playlist information if available
  1005. if state.current_playlist and state.current_playlist_index is not None:
  1006. next_index = state.current_playlist_index + 1
  1007. status["playlist"] = {
  1008. "current_index": state.current_playlist_index,
  1009. "total_files": len(state.current_playlist),
  1010. "mode": state.playlist_mode,
  1011. "next_file": state.current_playlist[next_index] if next_index < len(state.current_playlist) else None
  1012. }
  1013. if state.execution_progress:
  1014. current, total, remaining_time, elapsed_time = state.execution_progress
  1015. status["progress"] = {
  1016. "current": current,
  1017. "total": total,
  1018. "remaining_time": remaining_time,
  1019. "elapsed_time": elapsed_time,
  1020. "percentage": (current / total * 100) if total > 0 else 0
  1021. }
  1022. return status
  1023. async def broadcast_progress():
  1024. """Background task to broadcast progress updates."""
  1025. from main import broadcast_status_update
  1026. while True:
  1027. # Send status updates regardless of pattern_lock state
  1028. status = get_status()
  1029. # Use the existing broadcast function from main.py
  1030. await broadcast_status_update(status)
  1031. # Check if we should stop broadcasting
  1032. if not state.current_playlist:
  1033. # If no playlist, only stop if no pattern is being executed
  1034. if not pattern_lock.locked():
  1035. logger.info("No playlist or pattern running, stopping broadcast")
  1036. break
  1037. # Wait before next update
  1038. await asyncio.sleep(1)