pattern_manager.py 64 KB

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