pattern_manager.py 53 KB

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