pattern_manager.py 53 KB

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