pattern_manager.py 53 KB

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