pattern_manager.py 53 KB

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