1
0

pattern_manager.py 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250
  1. import os
  2. from zoneinfo import ZoneInfo
  3. import threading
  4. import time
  5. import random
  6. import logging
  7. from datetime import datetime, time as datetime_time
  8. from tqdm import tqdm
  9. from modules.connection import connection_manager
  10. from modules.core.state import state
  11. from math import pi
  12. import asyncio
  13. import json
  14. # Import for legacy support, but we'll use LED interface through state
  15. from modules.led.led_controller import effect_playing, effect_idle
  16. from modules.led.idle_timeout_manager import idle_timeout_manager
  17. import queue
  18. from dataclasses import dataclass
  19. from typing import Optional, Callable
  20. # Configure logging
  21. logger = logging.getLogger(__name__)
  22. # Global state
  23. THETA_RHO_DIR = './patterns'
  24. os.makedirs(THETA_RHO_DIR, exist_ok=True)
  25. # Execution time log file (JSON Lines format - one JSON object per line)
  26. EXECUTION_LOG_FILE = './execution_times.jsonl'
  27. def log_execution_time(pattern_name: str, table_type: str, speed: int, actual_time: float,
  28. total_coordinates: int, was_completed: bool):
  29. """Log pattern execution time to JSON Lines file for analysis.
  30. Args:
  31. pattern_name: Name of the pattern file
  32. table_type: Type of table (e.g., 'dune_weaver', 'dune_weaver_mini')
  33. speed: Speed setting used (0-255)
  34. actual_time: Actual execution time in seconds (excluding pauses)
  35. total_coordinates: Total number of coordinates in the pattern
  36. was_completed: Whether the pattern completed normally (not stopped/skipped)
  37. """
  38. # Format time as HH:MM:SS
  39. hours, remainder = divmod(int(actual_time), 3600)
  40. minutes, seconds = divmod(remainder, 60)
  41. time_formatted = f"{hours:02d}:{minutes:02d}:{seconds:02d}"
  42. log_entry = {
  43. "timestamp": datetime.now().isoformat(),
  44. "pattern_name": pattern_name,
  45. "table_type": table_type or "unknown",
  46. "speed": speed,
  47. "actual_time_seconds": round(actual_time, 2),
  48. "actual_time_formatted": time_formatted,
  49. "total_coordinates": total_coordinates,
  50. "completed": was_completed
  51. }
  52. try:
  53. with open(EXECUTION_LOG_FILE, 'a') as f:
  54. f.write(json.dumps(log_entry) + '\n')
  55. logger.info(f"Execution time logged: {pattern_name} - {time_formatted} (speed: {speed}, table: {table_type})")
  56. except Exception as e:
  57. logger.error(f"Failed to log execution time: {e}")
  58. # Asyncio primitives - initialized lazily to avoid event loop issues
  59. # These must be created in the context of the running event loop
  60. pause_event: Optional[asyncio.Event] = None
  61. pattern_lock: Optional[asyncio.Lock] = None
  62. progress_update_task = None
  63. def get_pause_event() -> asyncio.Event:
  64. """Get or create the pause event in the current event loop."""
  65. global pause_event
  66. if pause_event is None:
  67. pause_event = asyncio.Event()
  68. pause_event.set() # Initially not paused
  69. return pause_event
  70. def get_pattern_lock() -> asyncio.Lock:
  71. """Get or create the pattern lock in the current event loop."""
  72. global pattern_lock
  73. if pattern_lock is None:
  74. pattern_lock = asyncio.Lock()
  75. return pattern_lock
  76. # Cache timezone at module level - read once per session (cleared when user changes timezone)
  77. _cached_timezone = None
  78. _cached_zoneinfo = None
  79. def _get_timezone():
  80. """Get and cache the timezone for Still Sands. Uses user-selected timezone if set, otherwise system timezone."""
  81. global _cached_timezone, _cached_zoneinfo
  82. if _cached_timezone is not None:
  83. return _cached_zoneinfo
  84. user_tz = 'UTC' # Default fallback
  85. # First, check if user has selected a specific timezone in settings
  86. if state.scheduled_pause_timezone:
  87. user_tz = state.scheduled_pause_timezone
  88. logger.info(f"Still Sands using timezone: {user_tz} (user-selected)")
  89. else:
  90. # Fall back to system timezone detection
  91. try:
  92. if os.path.exists('/etc/host-timezone'):
  93. with open('/etc/host-timezone', 'r') as f:
  94. user_tz = f.read().strip()
  95. logger.info(f"Still Sands using timezone: {user_tz} (from host system)")
  96. # Fallback to /etc/timezone if host-timezone doesn't exist
  97. elif os.path.exists('/etc/timezone'):
  98. with open('/etc/timezone', 'r') as f:
  99. user_tz = f.read().strip()
  100. logger.info(f"Still Sands using timezone: {user_tz} (from container)")
  101. # Fallback to TZ environment variable
  102. elif os.environ.get('TZ'):
  103. user_tz = os.environ.get('TZ')
  104. logger.info(f"Still Sands using timezone: {user_tz} (from environment)")
  105. else:
  106. logger.info("Still Sands using timezone: UTC (system default)")
  107. except Exception as e:
  108. logger.debug(f"Could not read timezone: {e}")
  109. # Cache the timezone
  110. _cached_timezone = user_tz
  111. try:
  112. _cached_zoneinfo = ZoneInfo(user_tz)
  113. except Exception as e:
  114. logger.warning(f"Invalid timezone '{user_tz}', falling back to system time: {e}")
  115. _cached_zoneinfo = None
  116. return _cached_zoneinfo
  117. def is_in_scheduled_pause_period():
  118. """Check if current time falls within any scheduled pause period."""
  119. if not state.scheduled_pause_enabled or not state.scheduled_pause_time_slots:
  120. return False
  121. # Get cached timezone (user-selected or system default)
  122. tz_info = _get_timezone()
  123. try:
  124. # Get current time in user's timezone
  125. if tz_info:
  126. now = datetime.now(tz_info)
  127. else:
  128. now = datetime.now()
  129. except Exception as e:
  130. logger.warning(f"Error getting current time: {e}")
  131. now = datetime.now()
  132. current_time = now.time()
  133. current_weekday = now.strftime("%A").lower() # monday, tuesday, etc.
  134. for slot in state.scheduled_pause_time_slots:
  135. # Parse start and end times
  136. try:
  137. start_time = datetime_time.fromisoformat(slot['start_time'])
  138. end_time = datetime_time.fromisoformat(slot['end_time'])
  139. except (ValueError, KeyError):
  140. logger.warning(f"Invalid time format in scheduled pause slot: {slot}")
  141. continue
  142. # Check if this slot applies to today
  143. slot_applies_today = False
  144. days_setting = slot.get('days', 'daily')
  145. if days_setting == 'daily':
  146. slot_applies_today = True
  147. elif days_setting == 'weekdays':
  148. slot_applies_today = current_weekday in ['monday', 'tuesday', 'wednesday', 'thursday', 'friday']
  149. elif days_setting == 'weekends':
  150. slot_applies_today = current_weekday in ['saturday', 'sunday']
  151. elif days_setting == 'custom':
  152. custom_days = slot.get('custom_days', [])
  153. slot_applies_today = current_weekday in custom_days
  154. if not slot_applies_today:
  155. continue
  156. # Check if current time is within the pause period
  157. if start_time <= end_time:
  158. # Normal case: start and end are on the same day
  159. if start_time <= current_time <= end_time:
  160. return True
  161. else:
  162. # Time spans midnight: start is before midnight, end is after midnight
  163. if current_time >= start_time or current_time <= end_time:
  164. return True
  165. return False
  166. async def check_table_is_idle() -> bool:
  167. """
  168. Check if the table is currently idle by querying actual machine status.
  169. Returns True if idle, False if playing/moving.
  170. This checks the real machine state rather than relying on state variables,
  171. making it more reliable for detecting when table is truly idle.
  172. """
  173. # Use the connection_manager's is_machine_idle() function
  174. # Run it in a thread since it's a synchronous function
  175. return await asyncio.to_thread(connection_manager.is_machine_idle)
  176. def start_idle_led_timeout():
  177. """
  178. Start the idle LED timeout if enabled.
  179. Should be called whenever the idle effect is activated.
  180. """
  181. if not state.dw_led_idle_timeout_enabled:
  182. logger.debug("Idle LED timeout not enabled")
  183. return
  184. timeout_minutes = state.dw_led_idle_timeout_minutes
  185. if timeout_minutes <= 0:
  186. logger.debug("Idle LED timeout not configured (timeout <= 0)")
  187. return
  188. logger.debug(f"Starting idle LED timeout: {timeout_minutes} minutes")
  189. idle_timeout_manager.start_idle_timeout(
  190. timeout_minutes=timeout_minutes,
  191. state=state,
  192. check_idle_callback=check_table_is_idle
  193. )
  194. # Motion Control Thread Infrastructure
  195. @dataclass
  196. class MotionCommand:
  197. """Represents a motion command for the motion control thread."""
  198. command_type: str # 'move', 'stop', 'pause', 'resume', 'shutdown'
  199. theta: Optional[float] = None
  200. rho: Optional[float] = None
  201. speed: Optional[float] = None
  202. callback: Optional[Callable] = None
  203. future: Optional[asyncio.Future] = None
  204. class MotionControlThread:
  205. """Dedicated thread for hardware motion control operations."""
  206. def __init__(self):
  207. self.command_queue = queue.Queue()
  208. self.thread = None
  209. self.running = False
  210. self.paused = False
  211. def start(self):
  212. """Start the motion control thread."""
  213. if self.thread and self.thread.is_alive():
  214. return
  215. self.running = True
  216. self.thread = threading.Thread(target=self._motion_loop, daemon=True)
  217. self.thread.start()
  218. logger.info("Motion control thread started")
  219. def stop(self):
  220. """Stop the motion control thread."""
  221. if not self.running:
  222. return
  223. self.running = False
  224. # Send shutdown command
  225. self.command_queue.put(MotionCommand('shutdown'))
  226. if self.thread and self.thread.is_alive():
  227. self.thread.join(timeout=5.0)
  228. logger.info("Motion control thread stopped")
  229. def _motion_loop(self):
  230. """Main loop for the motion control thread."""
  231. logger.info("Motion control thread loop started")
  232. while self.running:
  233. try:
  234. # Get command with timeout to allow periodic checks
  235. command = self.command_queue.get(timeout=1.0)
  236. if command.command_type == 'shutdown':
  237. break
  238. elif command.command_type == 'move':
  239. self._execute_move(command)
  240. elif command.command_type == 'pause':
  241. self.paused = True
  242. elif command.command_type == 'resume':
  243. self.paused = False
  244. elif command.command_type == 'stop':
  245. # Clear any pending commands
  246. while not self.command_queue.empty():
  247. try:
  248. self.command_queue.get_nowait()
  249. except queue.Empty:
  250. break
  251. self.command_queue.task_done()
  252. except queue.Empty:
  253. # Timeout - continue loop for shutdown check
  254. continue
  255. except Exception as e:
  256. logger.error(f"Error in motion control thread: {e}")
  257. logger.info("Motion control thread loop ended")
  258. def _execute_move(self, command: MotionCommand):
  259. """Execute a move command in the motion thread."""
  260. try:
  261. # Wait if paused
  262. while self.paused and self.running:
  263. time.sleep(0.1)
  264. if not self.running:
  265. return
  266. # Execute the actual motion using sync version
  267. self._move_polar_sync(command.theta, command.rho, command.speed)
  268. # Signal completion if future provided
  269. if command.future and not command.future.done():
  270. command.future.get_loop().call_soon_threadsafe(
  271. command.future.set_result, None
  272. )
  273. except Exception as e:
  274. logger.error(f"Error executing move command: {e}")
  275. if command.future and not command.future.done():
  276. command.future.get_loop().call_soon_threadsafe(
  277. command.future.set_exception, e
  278. )
  279. def _move_polar_sync(self, theta: float, rho: float, speed: Optional[float] = None):
  280. """Synchronous version of move_polar for use in motion thread."""
  281. # This is the original sync logic but running in dedicated thread
  282. if state.table_type == 'dune_weaver_mini':
  283. x_scaling_factor = 2
  284. y_scaling_factor = 3.7
  285. else:
  286. x_scaling_factor = 2
  287. y_scaling_factor = 5
  288. delta_theta = theta - state.current_theta
  289. delta_rho = rho - state.current_rho
  290. x_increment = delta_theta * 100 / (2 * pi * x_scaling_factor)
  291. y_increment = delta_rho * 100 / y_scaling_factor
  292. x_total_steps = state.x_steps_per_mm * (100/x_scaling_factor)
  293. y_total_steps = state.y_steps_per_mm * (100/y_scaling_factor)
  294. offset = x_increment * (x_total_steps * x_scaling_factor / (state.gear_ratio * y_total_steps * y_scaling_factor))
  295. if state.table_type == 'dune_weaver_mini' or state.y_steps_per_mm == 546:
  296. y_increment -= offset
  297. else:
  298. y_increment += offset
  299. new_x_abs = state.machine_x + x_increment
  300. new_y_abs = state.machine_y + y_increment
  301. # Use provided speed or fall back to state.speed
  302. actual_speed = speed if speed is not None else state.speed
  303. # Call sync version of send_grbl_coordinates in this thread
  304. self._send_grbl_coordinates_sync(round(new_x_abs, 3), round(new_y_abs, 3), actual_speed)
  305. # Update state
  306. state.current_theta = theta
  307. state.current_rho = rho
  308. state.machine_x = new_x_abs
  309. state.machine_y = new_y_abs
  310. def _send_grbl_coordinates_sync(self, x: float, y: float, speed: int = 600, timeout: int = 2, home: bool = False):
  311. """Synchronous version of send_grbl_coordinates for motion thread."""
  312. logger.debug(f"Motion thread sending G-code: X{x} Y{y} at F{speed}")
  313. # Track overall attempt time
  314. overall_start_time = time.time()
  315. while True:
  316. try:
  317. gcode = f"$J=G91 G21 Y{y} F{speed}" if home else f"G1 G53 X{x} Y{y} F{speed}"
  318. state.conn.send(gcode + "\n")
  319. logger.debug(f"Motion thread sent command: {gcode}")
  320. start_time = time.time()
  321. while True:
  322. response = state.conn.readline()
  323. logger.debug(f"Motion thread response: {response}")
  324. if response.lower() == "ok":
  325. logger.debug("Motion thread: Command execution confirmed.")
  326. return
  327. except Exception as e:
  328. error_str = str(e)
  329. logger.warning(f"Motion thread error sending command: {error_str}")
  330. # Immediately return for device not configured errors
  331. if "Device not configured" in error_str or "Errno 6" in error_str:
  332. logger.error(f"Motion thread: Device configuration error detected: {error_str}")
  333. state.stop_requested = True
  334. state.conn = None
  335. state.is_connected = False
  336. logger.info("Connection marked as disconnected due to device error")
  337. return False
  338. logger.warning(f"Motion thread: No 'ok' received for X{x} Y{y}, speed {speed}. Retrying...")
  339. time.sleep(0.1)
  340. # Global motion control thread instance
  341. motion_controller = MotionControlThread()
  342. async def cleanup_pattern_manager():
  343. """Clean up pattern manager resources"""
  344. global progress_update_task, pattern_lock, pause_event
  345. try:
  346. # Signal stop to allow any running pattern to exit gracefully
  347. state.stop_requested = True
  348. # Stop motion control thread
  349. motion_controller.stop()
  350. # Cancel progress update task if running
  351. if progress_update_task and not progress_update_task.done():
  352. try:
  353. progress_update_task.cancel()
  354. # Wait for task to actually cancel
  355. try:
  356. await progress_update_task
  357. except asyncio.CancelledError:
  358. pass
  359. except Exception as e:
  360. logger.error(f"Error cancelling progress update task: {e}")
  361. # Clean up pattern lock - wait for it to be released naturally, don't force release
  362. # Force releasing an asyncio.Lock can corrupt internal state if held by another coroutine
  363. current_lock = pattern_lock
  364. if current_lock and current_lock.locked():
  365. logger.info("Pattern lock is held, waiting for release (max 5s)...")
  366. try:
  367. # Wait with timeout for the lock to become available
  368. async with asyncio.timeout(5.0):
  369. async with current_lock:
  370. pass # Lock acquired means previous holder released it
  371. logger.info("Pattern lock released normally")
  372. except asyncio.TimeoutError:
  373. logger.warning("Timed out waiting for pattern lock - creating fresh lock")
  374. except Exception as e:
  375. logger.error(f"Error waiting for pattern lock: {e}")
  376. # Clean up pause event - wake up any waiting tasks, then create fresh event
  377. current_event = pause_event
  378. if current_event:
  379. try:
  380. current_event.set() # Wake up any waiting tasks
  381. except Exception as e:
  382. logger.error(f"Error setting pause event: {e}")
  383. # Clean up pause condition from state
  384. if state.pause_condition:
  385. try:
  386. with state.pause_condition:
  387. state.pause_condition.notify_all()
  388. state.pause_condition = threading.Condition()
  389. except Exception as e:
  390. logger.error(f"Error cleaning up pause condition: {e}")
  391. # Clear all state variables
  392. state.current_playing_file = None
  393. state.execution_progress = 0
  394. state.is_running = False
  395. state.pause_requested = False
  396. state.stop_requested = True
  397. state.is_clearing = False
  398. # Reset machine position
  399. await connection_manager.update_machine_position()
  400. logger.info("Pattern manager resources cleaned up")
  401. except Exception as e:
  402. logger.error(f"Error during pattern manager cleanup: {e}")
  403. finally:
  404. # Reset to fresh instances instead of None to allow continued operation
  405. progress_update_task = None
  406. pattern_lock = asyncio.Lock() # Fresh lock instead of None
  407. pause_event = asyncio.Event() # Fresh event instead of None
  408. pause_event.set() # Initially not paused
  409. def list_theta_rho_files():
  410. files = []
  411. for root, dirs, filenames in os.walk(THETA_RHO_DIR):
  412. # Skip cached_images directories to avoid scanning thousands of WebP files
  413. if 'cached_images' in dirs:
  414. dirs.remove('cached_images')
  415. # Filter .thr files during traversal for better performance
  416. thr_files = [f for f in filenames if f.endswith('.thr')]
  417. for file in thr_files:
  418. relative_path = os.path.relpath(os.path.join(root, file), THETA_RHO_DIR)
  419. # Normalize path separators to always use forward slashes for consistency across platforms
  420. relative_path = relative_path.replace(os.sep, '/')
  421. files.append(relative_path)
  422. logger.debug(f"Found {len(files)} theta-rho files")
  423. return files
  424. def parse_theta_rho_file(file_path):
  425. """Parse a theta-rho file and return a list of (theta, rho) pairs."""
  426. coordinates = []
  427. try:
  428. logger.debug(f"Parsing theta-rho file: {file_path}")
  429. with open(file_path, 'r', encoding='utf-8') as file:
  430. for line in file:
  431. line = line.strip()
  432. if not line or line.startswith("#"):
  433. continue
  434. try:
  435. theta, rho = map(float, line.split())
  436. coordinates.append((theta, rho))
  437. except ValueError:
  438. logger.warning(f"Skipping invalid line: {line}")
  439. continue
  440. except Exception as e:
  441. logger.error(f"Error reading file: {e}")
  442. return coordinates
  443. logger.debug(f"Parsed {len(coordinates)} coordinates from {file_path}")
  444. return coordinates
  445. def get_first_rho_from_cache(file_path, cache_data=None):
  446. """Get the first rho value from cached metadata, falling back to file parsing if needed.
  447. Args:
  448. file_path: Path to the pattern file
  449. cache_data: Optional pre-loaded cache data dict to avoid repeated disk I/O
  450. """
  451. try:
  452. # Import cache_manager locally to avoid circular import
  453. from modules.core import cache_manager
  454. # Try to get from metadata cache first
  455. # Use relative path from THETA_RHO_DIR to match cache keys (which include subdirectories)
  456. file_name = os.path.relpath(file_path, THETA_RHO_DIR)
  457. # Use provided cache_data if available, otherwise load from disk
  458. if cache_data is not None:
  459. # Extract metadata directly from provided cache
  460. data_section = cache_data.get('data', {})
  461. if file_name in data_section:
  462. cached_entry = data_section[file_name]
  463. metadata = cached_entry.get('metadata')
  464. # When cache_data is provided, trust it without checking mtime
  465. # This significantly speeds up bulk operations (playlists with 1000+ patterns)
  466. # by avoiding 1000+ os.path.getmtime() calls on slow storage (e.g., Pi SD cards)
  467. if metadata and 'first_coordinate' in metadata:
  468. return metadata['first_coordinate']['y']
  469. else:
  470. # Fall back to loading cache from disk (original behavior)
  471. metadata = cache_manager.get_pattern_metadata(file_name)
  472. if metadata and 'first_coordinate' in metadata:
  473. # In the cache, 'x' is theta and 'y' is rho
  474. return metadata['first_coordinate']['y']
  475. # Fallback to parsing the file if not in cache
  476. logger.debug(f"Metadata not cached for {file_name}, parsing file")
  477. coordinates = parse_theta_rho_file(file_path)
  478. if coordinates:
  479. return coordinates[0][1] # Return rho value
  480. return None
  481. except Exception as e:
  482. logger.warning(f"Error getting first rho from cache for {file_path}: {str(e)}")
  483. return None
  484. def get_clear_pattern_file(clear_pattern_mode, path=None, cache_data=None):
  485. """Return a .thr file path based on pattern_name and table type.
  486. Args:
  487. clear_pattern_mode: The clear pattern mode to use
  488. path: Optional path to the pattern file for adaptive mode
  489. cache_data: Optional pre-loaded cache data dict to avoid repeated disk I/O
  490. """
  491. if not clear_pattern_mode or clear_pattern_mode == 'none':
  492. return
  493. # Define patterns for each table type
  494. clear_patterns = {
  495. 'dune_weaver': {
  496. 'clear_from_out': './patterns/clear_from_out.thr',
  497. 'clear_from_in': './patterns/clear_from_in.thr',
  498. 'clear_sideway': './patterns/clear_sideway.thr'
  499. },
  500. 'dune_weaver_mini': {
  501. 'clear_from_out': './patterns/clear_from_out_mini.thr',
  502. 'clear_from_in': './patterns/clear_from_in_mini.thr',
  503. 'clear_sideway': './patterns/clear_sideway_mini.thr'
  504. },
  505. 'dune_weaver_mini_pro': {
  506. 'clear_from_out': './patterns/clear_from_out_mini.thr',
  507. 'clear_from_in': './patterns/clear_from_in_mini.thr',
  508. 'clear_sideway': './patterns/clear_sideway_mini.thr'
  509. },
  510. 'dune_weaver_pro': {
  511. 'clear_from_out': './patterns/clear_from_out_pro.thr',
  512. 'clear_from_out_Ultra': './patterns/clear_from_out_Ultra.thr',
  513. 'clear_from_in': './patterns/clear_from_in_pro.thr',
  514. 'clear_from_in_Ultra': './patterns/clear_from_in_Ultra.thr',
  515. 'clear_sideway': './patterns/clear_sideway_pro.thr'
  516. }
  517. }
  518. # Get patterns for current table type, fallback to standard patterns if type not found
  519. table_patterns = clear_patterns.get(state.table_type, clear_patterns['dune_weaver'])
  520. # Check for custom patterns first
  521. if state.custom_clear_from_out and clear_pattern_mode in ['clear_from_out', 'adaptive']:
  522. if clear_pattern_mode == 'adaptive':
  523. # For adaptive mode, use cached metadata to check first rho
  524. if path:
  525. first_rho = get_first_rho_from_cache(path, cache_data)
  526. if first_rho is not None and first_rho < 0.5:
  527. # Use custom clear_from_out if set
  528. custom_path = os.path.join('./patterns', state.custom_clear_from_out)
  529. if os.path.exists(custom_path):
  530. logger.debug(f"Using custom clear_from_out: {custom_path}")
  531. return custom_path
  532. elif clear_pattern_mode == 'clear_from_out':
  533. custom_path = os.path.join('./patterns', state.custom_clear_from_out)
  534. if os.path.exists(custom_path):
  535. logger.debug(f"Using custom clear_from_out: {custom_path}")
  536. return custom_path
  537. if state.custom_clear_from_in and clear_pattern_mode in ['clear_from_in', 'adaptive']:
  538. if clear_pattern_mode == 'adaptive':
  539. # For adaptive mode, use cached metadata to check first rho
  540. if path:
  541. first_rho = get_first_rho_from_cache(path, cache_data)
  542. if first_rho is not None and first_rho >= 0.5:
  543. # Use custom clear_from_in if set
  544. custom_path = os.path.join('./patterns', state.custom_clear_from_in)
  545. if os.path.exists(custom_path):
  546. logger.debug(f"Using custom clear_from_in: {custom_path}")
  547. return custom_path
  548. elif clear_pattern_mode == 'clear_from_in':
  549. custom_path = os.path.join('./patterns', state.custom_clear_from_in)
  550. if os.path.exists(custom_path):
  551. logger.debug(f"Using custom clear_from_in: {custom_path}")
  552. return custom_path
  553. logger.debug(f"Clear pattern mode: {clear_pattern_mode} for table type: {state.table_type}")
  554. if clear_pattern_mode == "random":
  555. return random.choice(list(table_patterns.values()))
  556. if clear_pattern_mode == 'adaptive':
  557. if not path:
  558. logger.warning("No path provided for adaptive clear pattern")
  559. return random.choice(list(table_patterns.values()))
  560. # Use cached metadata to get first rho value
  561. first_rho = get_first_rho_from_cache(path, cache_data)
  562. if first_rho is None:
  563. logger.warning("Could not determine first rho value for adaptive clear pattern")
  564. return random.choice(list(table_patterns.values()))
  565. if first_rho < 0.5:
  566. return table_patterns['clear_from_out']
  567. else:
  568. return table_patterns['clear_from_in']
  569. else:
  570. if clear_pattern_mode not in table_patterns:
  571. return False
  572. return table_patterns[clear_pattern_mode]
  573. def is_clear_pattern(file_path):
  574. """Check if a file path is a clear pattern file."""
  575. # Get all possible clear pattern files for all table types
  576. clear_patterns = []
  577. for table_type in ['dune_weaver', 'dune_weaver_mini', 'dune_weaver_pro']:
  578. clear_patterns.extend([
  579. f'./patterns/clear_from_out{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr',
  580. f'./patterns/clear_from_in{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr',
  581. f'./patterns/clear_sideway{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr'
  582. ])
  583. # Normalize paths for comparison
  584. normalized_path = os.path.normpath(file_path)
  585. normalized_clear_patterns = [os.path.normpath(p) for p in clear_patterns]
  586. # Check if the file path matches any clear pattern path
  587. return normalized_path in normalized_clear_patterns
  588. async def run_theta_rho_file(file_path, is_playlist=False):
  589. """Run a theta-rho file by sending data in optimized batches with tqdm ETA tracking."""
  590. lock = get_pattern_lock()
  591. if lock.locked():
  592. logger.warning("Another pattern is already running. Cannot start a new one.")
  593. return
  594. async with 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 get_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. # Update state for main patterns only
  812. logger.info(f"Running pattern {file_path}")
  813. # Execute the pattern
  814. await run_theta_rho_file(file_path, is_playlist=True)
  815. # Increment pattern counter and check auto-home for non-clear patterns
  816. if not current_is_clear:
  817. state.patterns_since_last_home += 1
  818. logger.debug(f"Patterns since last home: {state.patterns_since_last_home}")
  819. # Check if we need to auto-home after this pattern
  820. # Auto-home triggers after X main patterns, regardless of clear pattern setting
  821. if state.auto_home_enabled and state.patterns_since_last_home >= state.auto_home_after_patterns:
  822. logger.info(f"Auto-homing triggered after {state.patterns_since_last_home} patterns")
  823. try:
  824. # Perform homing using connection_manager
  825. success = await asyncio.to_thread(connection_manager.home)
  826. if success:
  827. logger.info("Auto-homing completed successfully")
  828. state.patterns_since_last_home = 0
  829. else:
  830. logger.warning("Auto-homing failed, continuing with playlist")
  831. except Exception as e:
  832. logger.error(f"Error during auto-homing: {e}")
  833. # Check for scheduled pause after pattern completes (when "finish pattern first" is enabled)
  834. if state.scheduled_pause_finish_pattern and is_in_scheduled_pause_period() and not state.stop_requested:
  835. logger.info("Pattern completed. Entering Still Sands period (finish pattern first mode)...")
  836. # Turn off LED controller if control_wled is enabled
  837. wled_was_off_for_scheduled = False
  838. if state.scheduled_pause_control_wled and state.led_controller:
  839. logger.info("Turning off LED lights during Still Sands period")
  840. await state.led_controller.set_power_async(0)
  841. wled_was_off_for_scheduled = True
  842. elif state.led_controller:
  843. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  844. start_idle_led_timeout()
  845. # Wait until we're outside the scheduled pause period
  846. while is_in_scheduled_pause_period() and not state.stop_requested:
  847. await asyncio.sleep(1)
  848. if not state.stop_requested:
  849. logger.info("Still Sands period ended. Resuming playlist...")
  850. if state.led_controller:
  851. if wled_was_off_for_scheduled:
  852. logger.info("Turning LED lights back on as Still Sands period ended")
  853. await state.led_controller.set_power_async(1)
  854. await asyncio.sleep(0.5) # Critical delay for LED controller
  855. await state.led_controller.effect_playing_async(state.dw_led_playing_effect)
  856. idle_timeout_manager.cancel_timeout()
  857. # Handle pause between patterns
  858. if idx < len(pattern_sequence) - 1 and not state.stop_requested and pause_time > 0 and not state.skip_requested:
  859. # Check if current pattern is a clear pattern
  860. if current_is_clear:
  861. logger.info("Skipping pause after clear pattern")
  862. else:
  863. logger.info(f"Pausing for {pause_time} seconds")
  864. state.original_pause_time = pause_time
  865. pause_start = time.time()
  866. while time.time() - pause_start < pause_time:
  867. state.pause_time_remaining = pause_start + pause_time - time.time()
  868. if state.skip_requested:
  869. logger.info("Pause interrupted by stop/skip request")
  870. break
  871. await asyncio.sleep(1)
  872. state.pause_time_remaining = 0
  873. state.skip_requested = False
  874. if run_mode == "indefinite":
  875. logger.info("Playlist completed. Restarting as per 'indefinite' run mode")
  876. if pause_time > 0:
  877. logger.debug(f"Pausing for {pause_time} seconds before restarting")
  878. pause_start = time.time()
  879. while time.time() - pause_start < pause_time:
  880. state.pause_time_remaining = pause_start + pause_time - time.time()
  881. if state.skip_requested:
  882. logger.info("Pause interrupted by stop/skip request")
  883. break
  884. await asyncio.sleep(1)
  885. state.pause_time_remaining = 0
  886. continue
  887. else:
  888. logger.info("Playlist completed")
  889. break
  890. finally:
  891. # Clean up progress update task
  892. if progress_update_task:
  893. progress_update_task.cancel()
  894. try:
  895. await progress_update_task
  896. except asyncio.CancelledError:
  897. pass
  898. progress_update_task = None
  899. # Clear all state variables
  900. state.current_playing_file = None
  901. state.execution_progress = None
  902. state.current_playlist = None
  903. state.current_playlist_index = None
  904. state.playlist_mode = None
  905. state.pause_time_remaining = 0
  906. if state.led_controller:
  907. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  908. start_idle_led_timeout()
  909. logger.info("All requested patterns completed (or stopped) and state cleared")
  910. async def stop_actions(clear_playlist = True, wait_for_lock = True):
  911. """Stop all current actions and wait for pattern to fully release.
  912. Args:
  913. clear_playlist: Whether to clear playlist state
  914. wait_for_lock: Whether to wait for pattern_lock to be released. Set to False when
  915. called from within pattern execution to avoid deadlock.
  916. """
  917. try:
  918. with state.pause_condition:
  919. state.pause_requested = False
  920. state.stop_requested = True
  921. state.current_playing_file = None
  922. state.execution_progress = None
  923. state.is_clearing = False
  924. if clear_playlist:
  925. # Clear playlist state
  926. state.current_playlist = None
  927. state.current_playlist_index = None
  928. state.playlist_mode = None
  929. state.pause_time_remaining = 0
  930. # Cancel progress update task if we're clearing the playlist
  931. global progress_update_task
  932. if progress_update_task and not progress_update_task.done():
  933. progress_update_task.cancel()
  934. state.pause_condition.notify_all()
  935. # Wait for the pattern lock to be released before continuing
  936. # This ensures that when stop_actions completes, the pattern has fully stopped
  937. # Skip this if called from within pattern execution to avoid deadlock
  938. lock = get_pattern_lock()
  939. if wait_for_lock and lock.locked():
  940. logger.info("Waiting for pattern to fully stop...")
  941. # Acquire and immediately release the lock to ensure the pattern has exited
  942. async with lock:
  943. logger.info("Pattern lock acquired - pattern has fully stopped")
  944. # Call async function directly since we're in async context
  945. await connection_manager.update_machine_position()
  946. except Exception as e:
  947. logger.error(f"Error during stop_actions: {e}")
  948. # Ensure we still update machine position even if there's an error
  949. try:
  950. await connection_manager.update_machine_position()
  951. except Exception as update_err:
  952. logger.error(f"Error updating machine position on error: {update_err}")
  953. async def move_polar(theta, rho, speed=None):
  954. """
  955. Queue a motion command to be executed in the dedicated motion control thread.
  956. This makes motion control non-blocking for API endpoints.
  957. Args:
  958. theta (float): Target theta coordinate
  959. rho (float): Target rho coordinate
  960. speed (int, optional): Speed override. If None, uses state.speed
  961. """
  962. # Ensure motion control thread is running
  963. if not motion_controller.running:
  964. motion_controller.start()
  965. # Create future for async/await pattern
  966. loop = asyncio.get_event_loop()
  967. future = loop.create_future()
  968. # Create and queue motion command
  969. command = MotionCommand(
  970. command_type='move',
  971. theta=theta,
  972. rho=rho,
  973. speed=speed,
  974. future=future
  975. )
  976. motion_controller.command_queue.put(command)
  977. logger.debug(f"Queued motion command: theta={theta}, rho={rho}, speed={speed}")
  978. # Wait for command completion
  979. await future
  980. def pause_execution():
  981. """Pause pattern execution using asyncio Event."""
  982. logger.info("Pausing pattern execution")
  983. state.pause_requested = True
  984. get_pause_event().clear() # Clear the event to pause execution
  985. return True
  986. def resume_execution():
  987. """Resume pattern execution using asyncio Event."""
  988. logger.info("Resuming pattern execution")
  989. state.pause_requested = False
  990. get_pause_event().set() # Set the event to resume execution
  991. return True
  992. async def reset_theta():
  993. logger.info('Resetting Theta')
  994. state.current_theta = state.current_theta % (2 * pi)
  995. # Call async function directly since we're in async context
  996. await connection_manager.update_machine_position()
  997. def set_speed(new_speed):
  998. state.speed = new_speed
  999. logger.info(f'Set new state.speed {new_speed}')
  1000. def get_status():
  1001. """Get the current status of pattern execution."""
  1002. status = {
  1003. "current_file": state.current_playing_file,
  1004. "is_paused": state.pause_requested or is_in_scheduled_pause_period(),
  1005. "manual_pause": state.pause_requested,
  1006. "scheduled_pause": is_in_scheduled_pause_period(),
  1007. "is_running": bool(state.current_playing_file and not state.stop_requested),
  1008. "is_homing": state.is_homing,
  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 get_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)