pattern_manager.py 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578
  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, isnan, isinf
  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. # Validate coordinates before sending to prevent GRBL error:2
  425. if isnan(new_x_abs) or isnan(new_y_abs) or isinf(new_x_abs) or isinf(new_y_abs):
  426. logger.error(f"Motion thread: Invalid coordinates detected - X:{new_x_abs}, Y:{new_y_abs}")
  427. logger.error(f" theta:{theta}, rho:{rho}, current_theta:{state.current_theta}, current_rho:{state.current_rho}")
  428. logger.error(f" x_steps_per_mm:{state.x_steps_per_mm}, y_steps_per_mm:{state.y_steps_per_mm}, gear_ratio:{state.gear_ratio}")
  429. state.stop_requested = True
  430. return
  431. # Call sync version of send_grbl_coordinates in this thread
  432. self._send_grbl_coordinates_sync(round(new_x_abs, 3), round(new_y_abs, 3), actual_speed)
  433. # Update state
  434. state.current_theta = theta
  435. state.current_rho = rho
  436. state.machine_x = new_x_abs
  437. state.machine_y = new_y_abs
  438. def _send_grbl_coordinates_sync(self, x: float, y: float, speed: int = 600, timeout: int = 2, home: bool = False):
  439. """Synchronous version of send_grbl_coordinates for motion thread.
  440. Waits for 'ok' with a timeout. GRBL sends 'ok' after the move completes,
  441. which can take many seconds at slow speeds. We use a generous timeout
  442. (120 seconds) to handle slow movements, but prevent indefinite hangs.
  443. """
  444. gcode = f"$J=G91 G21 Y{y} F{speed}" if home else f"G1 G53 X{x} Y{y} F{speed}"
  445. max_wait_time = 120 # Maximum seconds to wait for 'ok' response
  446. while True:
  447. # Check stop_requested at the start of each iteration
  448. if state.stop_requested:
  449. logger.debug("Motion thread: Stop requested, aborting command")
  450. return False
  451. try:
  452. logger.debug(f"Motion thread sending G-code: {gcode}")
  453. state.conn.send(gcode + "\n")
  454. # Wait for 'ok' with timeout
  455. wait_start = time.time()
  456. while True:
  457. # Check stop_requested while waiting
  458. if state.stop_requested:
  459. logger.debug("Motion thread: Stop requested while waiting for response")
  460. return False
  461. # Check for timeout
  462. elapsed = time.time() - wait_start
  463. if elapsed > max_wait_time:
  464. logger.error(f"Motion thread: Timeout ({max_wait_time}s) waiting for 'ok' response")
  465. logger.error("Possible serial communication issue - stopping pattern")
  466. state.stop_requested = True
  467. return False
  468. response = state.conn.readline()
  469. if response:
  470. logger.debug(f"Motion thread response: {response}")
  471. if response.lower() == "ok":
  472. logger.debug("Motion thread: Command execution confirmed.")
  473. return True
  474. # Handle GRBL errors - these mean command failed, stop pattern
  475. if response.lower().startswith("error"):
  476. logger.error(f"Motion thread: GRBL error received: {response}")
  477. logger.error(f"Failed command: {gcode}")
  478. logger.error("Stopping pattern due to GRBL error")
  479. state.stop_requested = True
  480. return False
  481. # Handle GRBL alarms - machine needs attention
  482. if "alarm" in response.lower():
  483. logger.error(f"Motion thread: GRBL ALARM: {response}")
  484. logger.error("Machine alarm triggered - stopping pattern")
  485. state.stop_requested = True
  486. return False
  487. # Small sleep to prevent CPU spin when readline() times out
  488. time.sleep(0.01)
  489. except Exception as e:
  490. error_str = str(e)
  491. logger.warning(f"Motion thread error sending command: {error_str}")
  492. # Immediately return for device not configured errors
  493. if "Device not configured" in error_str or "Errno 6" in error_str:
  494. logger.error(f"Motion thread: Device configuration error detected: {error_str}")
  495. state.stop_requested = True
  496. state.conn = None
  497. state.is_connected = False
  498. logger.info("Connection marked as disconnected due to device error")
  499. return False
  500. # Only retry on exception (not on timeout)
  501. logger.warning(f"Motion thread: Error sending {gcode}, retrying...")
  502. time.sleep(0.1)
  503. # Global motion control thread instance
  504. motion_controller = MotionControlThread()
  505. async def cleanup_pattern_manager():
  506. """Clean up pattern manager resources"""
  507. global progress_update_task, pattern_lock, pause_event
  508. try:
  509. # Signal stop to allow any running pattern to exit gracefully
  510. state.stop_requested = True
  511. # Stop motion control thread
  512. motion_controller.stop()
  513. # Cancel progress update task if running
  514. if progress_update_task and not progress_update_task.done():
  515. try:
  516. progress_update_task.cancel()
  517. # Wait for task to actually cancel
  518. try:
  519. await progress_update_task
  520. except asyncio.CancelledError:
  521. pass
  522. except Exception as e:
  523. logger.error(f"Error cancelling progress update task: {e}")
  524. # Clean up pattern lock - wait for it to be released naturally, don't force release
  525. # Force releasing an asyncio.Lock can corrupt internal state if held by another coroutine
  526. current_lock = pattern_lock
  527. if current_lock and current_lock.locked():
  528. logger.info("Pattern lock is held, waiting for release (max 5s)...")
  529. try:
  530. # Wait with timeout for the lock to become available
  531. async with asyncio.timeout(5.0):
  532. async with current_lock:
  533. pass # Lock acquired means previous holder released it
  534. logger.info("Pattern lock released normally")
  535. except asyncio.TimeoutError:
  536. logger.warning("Timed out waiting for pattern lock - creating fresh lock")
  537. except Exception as e:
  538. logger.error(f"Error waiting for pattern lock: {e}")
  539. # Clean up pause event - wake up any waiting tasks, then create fresh event
  540. current_event = pause_event
  541. if current_event:
  542. try:
  543. current_event.set() # Wake up any waiting tasks
  544. except Exception as e:
  545. logger.error(f"Error setting pause event: {e}")
  546. # Clean up pause condition from state
  547. if state.pause_condition:
  548. try:
  549. with state.pause_condition:
  550. state.pause_condition.notify_all()
  551. state.pause_condition = threading.Condition()
  552. except Exception as e:
  553. logger.error(f"Error cleaning up pause condition: {e}")
  554. # Clear all state variables
  555. state.current_playing_file = None
  556. state.execution_progress = 0
  557. state.is_running = False
  558. state.pause_requested = False
  559. state.stop_requested = True
  560. state.is_clearing = False
  561. # Reset machine position
  562. await connection_manager.update_machine_position()
  563. logger.info("Pattern manager resources cleaned up")
  564. except Exception as e:
  565. logger.error(f"Error during pattern manager cleanup: {e}")
  566. finally:
  567. # Reset to fresh instances instead of None to allow continued operation
  568. progress_update_task = None
  569. pattern_lock = asyncio.Lock() # Fresh lock instead of None
  570. pause_event = asyncio.Event() # Fresh event instead of None
  571. pause_event.set() # Initially not paused
  572. def list_theta_rho_files():
  573. files = []
  574. for root, dirs, filenames in os.walk(THETA_RHO_DIR):
  575. # Skip cached_images directories to avoid scanning thousands of WebP files
  576. if 'cached_images' in dirs:
  577. dirs.remove('cached_images')
  578. # Filter .thr files during traversal for better performance
  579. thr_files = [f for f in filenames if f.endswith('.thr')]
  580. for file in thr_files:
  581. relative_path = os.path.relpath(os.path.join(root, file), THETA_RHO_DIR)
  582. # Normalize path separators to always use forward slashes for consistency across platforms
  583. relative_path = relative_path.replace(os.sep, '/')
  584. files.append(relative_path)
  585. logger.debug(f"Found {len(files)} theta-rho files")
  586. return files
  587. def parse_theta_rho_file(file_path):
  588. """Parse a theta-rho file and return a list of (theta, rho) pairs."""
  589. coordinates = []
  590. try:
  591. logger.debug(f"Parsing theta-rho file: {file_path}")
  592. with open(file_path, 'r', encoding='utf-8') as file:
  593. for line in file:
  594. line = line.strip()
  595. if not line or line.startswith("#"):
  596. continue
  597. try:
  598. theta, rho = map(float, line.split())
  599. coordinates.append((theta, rho))
  600. except ValueError:
  601. logger.warning(f"Skipping invalid line: {line}")
  602. continue
  603. except Exception as e:
  604. logger.error(f"Error reading file: {e}")
  605. return coordinates
  606. logger.debug(f"Parsed {len(coordinates)} coordinates from {file_path}")
  607. return coordinates
  608. def get_first_rho_from_cache(file_path, cache_data=None):
  609. """Get the first rho value from cached metadata, falling back to file parsing if needed.
  610. Args:
  611. file_path: Path to the pattern file
  612. cache_data: Optional pre-loaded cache data dict to avoid repeated disk I/O
  613. """
  614. try:
  615. # Import cache_manager locally to avoid circular import
  616. from modules.core import cache_manager
  617. # Try to get from metadata cache first
  618. # Use relative path from THETA_RHO_DIR to match cache keys (which include subdirectories)
  619. file_name = os.path.relpath(file_path, THETA_RHO_DIR)
  620. # Use provided cache_data if available, otherwise load from disk
  621. if cache_data is not None:
  622. # Extract metadata directly from provided cache
  623. data_section = cache_data.get('data', {})
  624. if file_name in data_section:
  625. cached_entry = data_section[file_name]
  626. metadata = cached_entry.get('metadata')
  627. # When cache_data is provided, trust it without checking mtime
  628. # This significantly speeds up bulk operations (playlists with 1000+ patterns)
  629. # by avoiding 1000+ os.path.getmtime() calls on slow storage (e.g., Pi SD cards)
  630. if metadata and 'first_coordinate' in metadata:
  631. return metadata['first_coordinate']['y']
  632. else:
  633. # Fall back to loading cache from disk (original behavior)
  634. metadata = cache_manager.get_pattern_metadata(file_name)
  635. if metadata and 'first_coordinate' in metadata:
  636. # In the cache, 'x' is theta and 'y' is rho
  637. return metadata['first_coordinate']['y']
  638. # Fallback to parsing the file if not in cache
  639. logger.debug(f"Metadata not cached for {file_name}, parsing file")
  640. coordinates = parse_theta_rho_file(file_path)
  641. if coordinates:
  642. return coordinates[0][1] # Return rho value
  643. return None
  644. except Exception as e:
  645. logger.warning(f"Error getting first rho from cache for {file_path}: {str(e)}")
  646. return None
  647. def get_clear_pattern_file(clear_pattern_mode, path=None, cache_data=None):
  648. """Return a .thr file path based on pattern_name and table type.
  649. Args:
  650. clear_pattern_mode: The clear pattern mode to use
  651. path: Optional path to the pattern file for adaptive mode
  652. cache_data: Optional pre-loaded cache data dict to avoid repeated disk I/O
  653. """
  654. if not clear_pattern_mode or clear_pattern_mode == 'none':
  655. return
  656. # Define patterns for each table type
  657. clear_patterns = {
  658. 'dune_weaver': {
  659. 'clear_from_out': './patterns/clear_from_out.thr',
  660. 'clear_from_in': './patterns/clear_from_in.thr',
  661. 'clear_sideway': './patterns/clear_sideway.thr'
  662. },
  663. 'dune_weaver_mini': {
  664. 'clear_from_out': './patterns/clear_from_out_mini.thr',
  665. 'clear_from_in': './patterns/clear_from_in_mini.thr',
  666. 'clear_sideway': './patterns/clear_sideway_mini.thr'
  667. },
  668. 'dune_weaver_mini_pro': {
  669. 'clear_from_out': './patterns/clear_from_out_mini.thr',
  670. 'clear_from_in': './patterns/clear_from_in_mini.thr',
  671. 'clear_sideway': './patterns/clear_sideway_mini.thr'
  672. },
  673. 'dune_weaver_pro': {
  674. 'clear_from_out': './patterns/clear_from_out_pro.thr',
  675. 'clear_from_out_Ultra': './patterns/clear_from_out_Ultra.thr',
  676. 'clear_from_in': './patterns/clear_from_in_pro.thr',
  677. 'clear_from_in_Ultra': './patterns/clear_from_in_Ultra.thr',
  678. 'clear_sideway': './patterns/clear_sideway_pro.thr'
  679. }
  680. }
  681. # Get patterns for current table type, fallback to standard patterns if type not found
  682. table_patterns = clear_patterns.get(state.table_type, clear_patterns['dune_weaver'])
  683. # Check for custom patterns first
  684. if state.custom_clear_from_out and clear_pattern_mode in ['clear_from_out', 'adaptive']:
  685. if clear_pattern_mode == 'adaptive':
  686. # For adaptive mode, use cached metadata to check first rho
  687. if path:
  688. first_rho = get_first_rho_from_cache(path, cache_data)
  689. if first_rho is not None and first_rho < 0.5:
  690. # Use custom clear_from_out if set
  691. custom_path = os.path.join('./patterns', state.custom_clear_from_out)
  692. if os.path.exists(custom_path):
  693. logger.debug(f"Using custom clear_from_out: {custom_path}")
  694. return custom_path
  695. elif clear_pattern_mode == 'clear_from_out':
  696. custom_path = os.path.join('./patterns', state.custom_clear_from_out)
  697. if os.path.exists(custom_path):
  698. logger.debug(f"Using custom clear_from_out: {custom_path}")
  699. return custom_path
  700. if state.custom_clear_from_in and clear_pattern_mode in ['clear_from_in', 'adaptive']:
  701. if clear_pattern_mode == 'adaptive':
  702. # For adaptive mode, use cached metadata to check first rho
  703. if path:
  704. first_rho = get_first_rho_from_cache(path, cache_data)
  705. if first_rho is not None and first_rho >= 0.5:
  706. # Use custom clear_from_in if set
  707. custom_path = os.path.join('./patterns', state.custom_clear_from_in)
  708. if os.path.exists(custom_path):
  709. logger.debug(f"Using custom clear_from_in: {custom_path}")
  710. return custom_path
  711. elif clear_pattern_mode == 'clear_from_in':
  712. custom_path = os.path.join('./patterns', state.custom_clear_from_in)
  713. if os.path.exists(custom_path):
  714. logger.debug(f"Using custom clear_from_in: {custom_path}")
  715. return custom_path
  716. logger.debug(f"Clear pattern mode: {clear_pattern_mode} for table type: {state.table_type}")
  717. if clear_pattern_mode == "random":
  718. return random.choice(list(table_patterns.values()))
  719. if clear_pattern_mode == 'adaptive':
  720. if not path:
  721. logger.warning("No path provided for adaptive clear pattern")
  722. return random.choice(list(table_patterns.values()))
  723. # Use cached metadata to get first rho value
  724. first_rho = get_first_rho_from_cache(path, cache_data)
  725. if first_rho is None:
  726. logger.warning("Could not determine first rho value for adaptive clear pattern")
  727. return random.choice(list(table_patterns.values()))
  728. if first_rho < 0.5:
  729. return table_patterns['clear_from_out']
  730. else:
  731. return table_patterns['clear_from_in']
  732. else:
  733. if clear_pattern_mode not in table_patterns:
  734. return False
  735. return table_patterns[clear_pattern_mode]
  736. def is_clear_pattern(file_path):
  737. """Check if a file path is a clear pattern file."""
  738. # Get all possible clear pattern files for all table types
  739. clear_patterns = []
  740. for table_type in ['dune_weaver', 'dune_weaver_mini', 'dune_weaver_pro']:
  741. clear_patterns.extend([
  742. f'./patterns/clear_from_out{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr',
  743. f'./patterns/clear_from_in{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr',
  744. f'./patterns/clear_sideway{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr'
  745. ])
  746. # Normalize paths for comparison
  747. normalized_path = os.path.normpath(file_path)
  748. normalized_clear_patterns = [os.path.normpath(p) for p in clear_patterns]
  749. # Check if the file path matches any clear pattern path
  750. return normalized_path in normalized_clear_patterns
  751. async def _execute_pattern_internal(file_path):
  752. """Internal function to execute a pattern file. Must be called with lock already held.
  753. Args:
  754. file_path: Path to the .thr file to execute
  755. Returns:
  756. True if pattern completed successfully, False if stopped/skipped
  757. """
  758. # Run file parsing in thread to avoid blocking the event loop
  759. coordinates = await asyncio.to_thread(parse_theta_rho_file, file_path)
  760. total_coordinates = len(coordinates)
  761. # Cache coordinates in state for frontend preview (avoids re-parsing large files)
  762. state._current_coordinates = coordinates
  763. if total_coordinates < 2:
  764. logger.warning("Not enough coordinates for interpolation")
  765. return False
  766. # Determine if this is a clearing pattern
  767. is_clear_file = is_clear_pattern(file_path)
  768. if is_clear_file:
  769. initial_speed = state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  770. logger.info(f"Running clearing pattern at initial speed {initial_speed}")
  771. else:
  772. logger.info(f"Running normal pattern at initial speed {state.speed}")
  773. state.execution_progress = (0, total_coordinates, None, 0)
  774. # stop actions without resetting the playlist, and don't wait for lock (we already have it)
  775. # Preserve is_clearing flag since stop_actions resets it
  776. was_clearing = state.is_clearing
  777. await stop_actions(clear_playlist=False, wait_for_lock=False)
  778. state.is_clearing = was_clearing
  779. state.current_playing_file = file_path
  780. state.stop_requested = False
  781. # Reset LED idle timeout activity time when pattern starts
  782. import time as time_module
  783. state.dw_led_last_activity_time = time_module.time()
  784. logger.info(f"Starting pattern execution: {file_path}")
  785. logger.info(f"t: {state.current_theta}, r: {state.current_rho}")
  786. await reset_theta()
  787. start_time = time.time()
  788. total_pause_time = 0 # Track total time spent paused (manual + scheduled)
  789. if state.led_controller:
  790. logger.info(f"Setting LED to playing effect: {state.dw_led_playing_effect}")
  791. await state.led_controller.effect_playing_async(state.dw_led_playing_effect)
  792. # Cancel idle timeout when playing starts
  793. idle_timeout_manager.cancel_timeout()
  794. with tqdm(
  795. total=total_coordinates,
  796. unit="coords",
  797. desc=f"Executing Pattern {file_path}",
  798. dynamic_ncols=True,
  799. disable=False,
  800. mininterval=1.0
  801. ) as pbar:
  802. for i, coordinate in enumerate(coordinates):
  803. theta, rho = coordinate
  804. if state.stop_requested:
  805. logger.info("Execution stopped by user")
  806. if state.led_controller:
  807. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  808. start_idle_led_timeout()
  809. break
  810. if state.skip_requested:
  811. logger.info("Skipping pattern...")
  812. await connection_manager.check_idle_async()
  813. if state.led_controller:
  814. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  815. start_idle_led_timeout()
  816. break
  817. # Wait for resume if paused (manual or scheduled)
  818. manual_pause = state.pause_requested
  819. # Only check scheduled pause during pattern if "finish pattern first" is NOT enabled
  820. scheduled_pause = is_in_scheduled_pause_period() if not state.scheduled_pause_finish_pattern else False
  821. if manual_pause or scheduled_pause:
  822. pause_start = time.time() # Track when pause started
  823. if manual_pause and scheduled_pause:
  824. logger.info("Execution paused (manual + scheduled pause active)...")
  825. elif manual_pause:
  826. logger.info("Execution paused (manual)...")
  827. else:
  828. logger.info("Execution paused (scheduled pause period)...")
  829. # Turn off LED controller if scheduled pause and control_wled is enabled
  830. if state.scheduled_pause_control_wled and state.led_controller:
  831. logger.info("Turning off LED lights during Still Sands period")
  832. await state.led_controller.set_power_async(0)
  833. # Only show idle effect if NOT in scheduled pause with LED control
  834. # (manual pause always shows idle effect)
  835. if state.led_controller and not (scheduled_pause and state.scheduled_pause_control_wled):
  836. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  837. start_idle_led_timeout()
  838. # Remember if we turned off LED controller for scheduled pause
  839. wled_was_off_for_scheduled = scheduled_pause and state.scheduled_pause_control_wled and not manual_pause
  840. # Wait until both manual pause is released AND we're outside scheduled pause period
  841. # Also check for stop/skip requests to allow immediate interruption
  842. interrupted = False
  843. while state.pause_requested or is_in_scheduled_pause_period():
  844. # Check for stop/skip first
  845. if state.stop_requested:
  846. logger.info("Stop requested during pause, exiting")
  847. interrupted = True
  848. break
  849. if state.skip_requested:
  850. logger.info("Skip requested during pause, skipping pattern")
  851. interrupted = True
  852. break
  853. if state.pause_requested:
  854. # For manual pause, wait on multiple events for immediate response
  855. # Wake on: resume, stop, skip, or timeout (for flag polling fallback)
  856. pause_event = get_pause_event()
  857. stop_event = state.get_stop_event()
  858. skip_event = state.get_skip_event()
  859. wait_tasks = [asyncio.create_task(pause_event.wait(), name='pause')]
  860. if stop_event:
  861. wait_tasks.append(asyncio.create_task(stop_event.wait(), name='stop'))
  862. if skip_event:
  863. wait_tasks.append(asyncio.create_task(skip_event.wait(), name='skip'))
  864. # Add timeout to ensure we periodically check flags even if events aren't set
  865. # This handles the case where stop is called from sync context (no event loop)
  866. timeout_task = asyncio.create_task(asyncio.sleep(1.0), name='timeout')
  867. wait_tasks.append(timeout_task)
  868. try:
  869. done, pending = await asyncio.wait(
  870. wait_tasks, return_when=asyncio.FIRST_COMPLETED
  871. )
  872. finally:
  873. for task in pending:
  874. task.cancel()
  875. for task in pending:
  876. try:
  877. await task
  878. except asyncio.CancelledError:
  879. pass
  880. else:
  881. # For scheduled pause, use wait_for_interrupt for instant response
  882. result = await state.wait_for_interrupt(timeout=1.0)
  883. if result in ('stopped', 'skipped'):
  884. interrupted = True
  885. break
  886. total_pause_time += time.time() - pause_start # Add pause duration
  887. if interrupted:
  888. # Exit the coordinate loop if we were interrupted
  889. break
  890. logger.info("Execution resumed...")
  891. if state.led_controller:
  892. # Turn LED controller back on if it was turned off for scheduled pause
  893. if wled_was_off_for_scheduled:
  894. logger.info("Turning LED lights back on as Still Sands period ended")
  895. await state.led_controller.set_power_async(1)
  896. # CRITICAL: Give LED controller time to fully power on before sending more commands
  897. # Without this delay, rapid-fire requests can crash controllers on resource-constrained Pis
  898. await asyncio.sleep(0.5)
  899. await state.led_controller.effect_playing_async(state.dw_led_playing_effect)
  900. # Cancel idle timeout when resuming from pause
  901. idle_timeout_manager.cancel_timeout()
  902. # Dynamically determine the speed for each movement
  903. # Use clear_pattern_speed if it's set and this is a clear file, otherwise use state.speed
  904. if is_clear_file and state.clear_pattern_speed is not None:
  905. current_speed = state.clear_pattern_speed
  906. else:
  907. current_speed = state.speed
  908. await move_polar(theta, rho, current_speed)
  909. # Update progress for all coordinates including the first one
  910. pbar.update(1)
  911. elapsed_time = time.time() - start_time
  912. estimated_remaining_time = (total_coordinates - (i + 1)) / pbar.format_dict['rate'] if pbar.format_dict['rate'] and total_coordinates else 0
  913. state.execution_progress = (i + 1, total_coordinates, estimated_remaining_time, elapsed_time)
  914. # Add a small delay to allow other async operations
  915. await asyncio.sleep(0.001)
  916. # Update progress one last time to show 100%
  917. elapsed_time = time.time() - start_time
  918. actual_execution_time = elapsed_time - total_pause_time
  919. state.execution_progress = (total_coordinates, total_coordinates, 0, elapsed_time)
  920. # Give WebSocket a chance to send the final update
  921. await asyncio.sleep(0.1)
  922. # Log execution time (only for completed patterns, not stopped/skipped)
  923. was_completed = not state.stop_requested and not state.skip_requested
  924. pattern_name = os.path.basename(file_path)
  925. effective_speed = state.clear_pattern_speed if (is_clear_file and state.clear_pattern_speed is not None) else state.speed
  926. log_execution_time(
  927. pattern_name=pattern_name,
  928. table_type=state.table_type,
  929. speed=effective_speed,
  930. actual_time=actual_execution_time,
  931. total_coordinates=total_coordinates,
  932. was_completed=was_completed
  933. )
  934. if not state.conn:
  935. logger.error("Device is not connected. Stopping pattern execution.")
  936. return False
  937. await connection_manager.check_idle_async()
  938. # Set LED back to idle when pattern completes normally (not stopped early)
  939. if state.led_controller and not state.stop_requested:
  940. logger.info(f"Setting LED to idle effect: {state.dw_led_idle_effect}")
  941. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  942. start_idle_led_timeout()
  943. logger.debug("LED effect set to idle after pattern completion")
  944. return was_completed
  945. async def run_theta_rho_file(file_path, is_playlist=False, clear_pattern=None, cache_data=None):
  946. """Run a theta-rho file with optional pre-execution clear pattern.
  947. Args:
  948. file_path: Path to the main .thr file to execute
  949. is_playlist: True if running as part of a playlist
  950. clear_pattern: Clear pattern mode ('adaptive', 'clear_from_in', 'clear_from_out', 'none', or None)
  951. cache_data: Pre-loaded metadata cache for adaptive clear pattern selection
  952. """
  953. lock = get_pattern_lock()
  954. if lock.locked():
  955. logger.warning("Another pattern is already running. Cannot start a new one.")
  956. return
  957. async with lock: # This ensures only one pattern can run at a time
  958. # Clear any stale pause state from previous playlist
  959. state.pause_time_remaining = 0
  960. state.original_pause_time = None
  961. # Start progress update task only if not part of a playlist
  962. global progress_update_task
  963. if not is_playlist and not progress_update_task:
  964. progress_update_task = asyncio.create_task(broadcast_progress())
  965. # Run clear pattern first if specified
  966. if clear_pattern and clear_pattern != 'none':
  967. clear_file_path = get_clear_pattern_file(clear_pattern, file_path, cache_data)
  968. if clear_file_path:
  969. logger.info(f"Running pre-execution clear pattern: {clear_file_path}")
  970. state.is_clearing = True
  971. await _execute_pattern_internal(clear_file_path)
  972. state.is_clearing = False
  973. # Reset skip flag after clear pattern (if user skipped clear, continue to main)
  974. state.skip_requested = False
  975. # Check if stopped during clear pattern
  976. if state.stop_requested:
  977. logger.info("Execution stopped during clear pattern")
  978. if not is_playlist:
  979. state.current_playing_file = None
  980. state.execution_progress = None
  981. return
  982. # Run the main pattern
  983. completed = await _execute_pattern_internal(file_path)
  984. # Only clear state if not part of a playlist
  985. if not is_playlist:
  986. state.current_playing_file = None
  987. state.execution_progress = None
  988. logger.info("Pattern execution completed and state cleared")
  989. # Only cancel progress update task if not part of a playlist
  990. if progress_update_task:
  991. progress_update_task.cancel()
  992. try:
  993. await progress_update_task
  994. except asyncio.CancelledError:
  995. pass
  996. progress_update_task = None
  997. else:
  998. logger.info("Pattern execution completed, maintaining state for playlist")
  999. async def run_theta_rho_files(file_paths, pause_time=0, clear_pattern=None, run_mode="single", shuffle=False):
  1000. """Run multiple .thr files in sequence with options.
  1001. The playlist now stores only main patterns. Clear patterns are executed dynamically
  1002. before each main pattern based on the clear_pattern option.
  1003. """
  1004. state.stop_requested = False
  1005. # Reset LED idle timeout activity time when playlist starts
  1006. import time as time_module
  1007. state.dw_led_last_activity_time = time_module.time()
  1008. # Set initial playlist state
  1009. state.playlist_mode = run_mode
  1010. state.current_playlist_index = 0
  1011. # Start progress update task for the playlist
  1012. global progress_update_task
  1013. if not progress_update_task:
  1014. progress_update_task = asyncio.create_task(broadcast_progress())
  1015. # Shuffle main patterns if requested (before starting)
  1016. if shuffle:
  1017. random.shuffle(file_paths)
  1018. logger.info("Playlist shuffled")
  1019. # Store only main patterns in the playlist
  1020. state.current_playlist = file_paths
  1021. try:
  1022. while True:
  1023. # Load metadata cache once per playlist iteration (for adaptive clear patterns)
  1024. cache_data = None
  1025. if clear_pattern and clear_pattern in ['adaptive', 'clear_from_in', 'clear_from_out']:
  1026. from modules.core import cache_manager
  1027. cache_data = await asyncio.to_thread(cache_manager.load_metadata_cache)
  1028. logger.info(f"Loaded metadata cache for {len(cache_data.get('data', {}))} patterns")
  1029. # Reset pattern counter at the start of the playlist
  1030. state.patterns_since_last_home = 0
  1031. # Execute main patterns using index-based access
  1032. # This allows the playlist to be reordered during execution
  1033. idx = 0
  1034. while state.current_playlist and idx < len(state.current_playlist):
  1035. state.current_playlist_index = idx
  1036. if state.stop_requested or not state.current_playlist:
  1037. logger.info("Execution stopped")
  1038. return
  1039. # Get the pattern at the current index (may have changed due to reordering)
  1040. file_path = state.current_playlist[idx]
  1041. logger.info(f"Running pattern {idx + 1}/{len(state.current_playlist)}: {file_path}")
  1042. # Clear pause state when starting a new pattern (prevents stale "waiting" UI)
  1043. state.pause_time_remaining = 0
  1044. state.original_pause_time = None
  1045. # Execute the pattern with optional clear pattern
  1046. await run_theta_rho_file(
  1047. file_path,
  1048. is_playlist=True,
  1049. clear_pattern=clear_pattern,
  1050. cache_data=cache_data
  1051. )
  1052. # Increment pattern counter (auto-home check happens after pause time)
  1053. state.patterns_since_last_home += 1
  1054. logger.debug(f"Patterns since last home: {state.patterns_since_last_home}")
  1055. # Check for scheduled pause after pattern completes (when "finish pattern first" is enabled)
  1056. if state.scheduled_pause_finish_pattern and is_in_scheduled_pause_period() and not state.stop_requested and not state.skip_requested:
  1057. logger.info("Pattern completed. Entering Still Sands period (finish pattern first mode)...")
  1058. wled_was_off_for_scheduled = False
  1059. if state.scheduled_pause_control_wled and state.led_controller:
  1060. logger.info("Turning off LED lights during Still Sands period")
  1061. await state.led_controller.set_power_async(0)
  1062. wled_was_off_for_scheduled = True
  1063. elif state.led_controller:
  1064. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  1065. start_idle_led_timeout()
  1066. # Wait for scheduled pause to end, but allow stop/skip to interrupt
  1067. result = await wait_with_interrupt(
  1068. is_in_scheduled_pause_period,
  1069. check_stop=True,
  1070. check_skip=True,
  1071. )
  1072. if result == 'completed':
  1073. logger.info("Still Sands period ended. Resuming playlist...")
  1074. if state.led_controller:
  1075. if wled_was_off_for_scheduled:
  1076. logger.info("Turning LED lights back on as Still Sands period ended")
  1077. await state.led_controller.set_power_async(1)
  1078. await asyncio.sleep(0.5)
  1079. await state.led_controller.effect_playing_async(state.dw_led_playing_effect)
  1080. idle_timeout_manager.cancel_timeout()
  1081. # Handle pause between patterns
  1082. 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:
  1083. logger.info(f"Pausing for {pause_time} seconds")
  1084. state.original_pause_time = pause_time
  1085. pause_start = time.time()
  1086. while time.time() - pause_start < pause_time:
  1087. state.pause_time_remaining = pause_start + pause_time - time.time()
  1088. if state.skip_requested:
  1089. logger.info("Pause interrupted by skip request")
  1090. break
  1091. await asyncio.sleep(1)
  1092. # Clear both pause state vars immediately (so UI updates right away)
  1093. state.pause_time_remaining = 0
  1094. state.original_pause_time = None
  1095. # Auto-home after pause time, before next clear pattern starts
  1096. # Only home if there's a next pattern and we haven't been stopped
  1097. if (state.auto_home_enabled and
  1098. state.patterns_since_last_home >= state.auto_home_after_patterns and
  1099. state.current_playlist and idx < len(state.current_playlist) - 1 and
  1100. not state.stop_requested):
  1101. logger.info(f"Auto-homing triggered after {state.patterns_since_last_home} patterns (before next clear pattern)")
  1102. try:
  1103. success = await asyncio.to_thread(connection_manager.home)
  1104. if success:
  1105. logger.info("Auto-homing completed successfully")
  1106. state.patterns_since_last_home = 0
  1107. else:
  1108. logger.warning("Auto-homing failed, continuing with playlist")
  1109. except Exception as e:
  1110. logger.error(f"Error during auto-homing: {e}")
  1111. state.skip_requested = False
  1112. idx += 1
  1113. if run_mode == "indefinite":
  1114. logger.info("Playlist completed. Restarting as per 'indefinite' run mode")
  1115. if pause_time > 0:
  1116. pause_start = time.time()
  1117. while time.time() - pause_start < pause_time:
  1118. state.pause_time_remaining = pause_start + pause_time - time.time()
  1119. if state.skip_requested:
  1120. logger.info("Pause interrupted by skip request")
  1121. break
  1122. await asyncio.sleep(1)
  1123. # Clear both pause state vars immediately (so UI updates right away)
  1124. state.pause_time_remaining = 0
  1125. state.original_pause_time = None
  1126. continue
  1127. else:
  1128. logger.info("Playlist completed")
  1129. break
  1130. finally:
  1131. if progress_update_task:
  1132. progress_update_task.cancel()
  1133. try:
  1134. await progress_update_task
  1135. except asyncio.CancelledError:
  1136. pass
  1137. progress_update_task = None
  1138. state.current_playing_file = None
  1139. state.execution_progress = None
  1140. state.current_playlist = None
  1141. state.current_playlist_index = None
  1142. state.playlist_mode = None
  1143. state.pause_time_remaining = 0
  1144. if state.led_controller:
  1145. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  1146. start_idle_led_timeout()
  1147. logger.info("All requested patterns completed (or stopped) and state cleared")
  1148. async def stop_actions(clear_playlist = True, wait_for_lock = True):
  1149. """Stop all current actions and wait for pattern to fully release.
  1150. Args:
  1151. clear_playlist: Whether to clear playlist state
  1152. wait_for_lock: Whether to wait for pattern_lock to be released. Set to False when
  1153. called from within pattern execution to avoid deadlock.
  1154. Returns:
  1155. True if stopped cleanly, False if timed out waiting for pattern lock
  1156. """
  1157. timed_out = False
  1158. try:
  1159. with state.pause_condition:
  1160. state.pause_requested = False
  1161. state.stop_requested = True
  1162. state.is_clearing = False
  1163. # Always clear pause time between patterns on stop
  1164. state.pause_time_remaining = 0
  1165. state.original_pause_time = None
  1166. if clear_playlist:
  1167. # Clear playlist state
  1168. state.current_playlist = None
  1169. state.current_playlist_index = None
  1170. state.playlist_mode = None
  1171. # Cancel progress update task if we're clearing the playlist
  1172. global progress_update_task
  1173. if progress_update_task and not progress_update_task.done():
  1174. progress_update_task.cancel()
  1175. # Cancel the playlist task itself (late import to avoid circular dependency)
  1176. from modules.core import playlist_manager
  1177. await playlist_manager.cancel_current_playlist()
  1178. state.pause_condition.notify_all()
  1179. # Also set the pause event to wake up any paused patterns
  1180. get_pause_event().set()
  1181. # Send stop command to motion thread to clear its queue
  1182. if motion_controller.running:
  1183. motion_controller.command_queue.put(MotionCommand('stop'))
  1184. # Wait for the pattern lock to be released before continuing
  1185. # This ensures that when stop_actions completes, the pattern has fully stopped
  1186. # Skip this if called from within pattern execution to avoid deadlock
  1187. lock = get_pattern_lock()
  1188. if wait_for_lock and lock.locked():
  1189. logger.info("Waiting for pattern to fully stop...")
  1190. # Use a timeout to prevent hanging forever
  1191. try:
  1192. async with asyncio.timeout(10.0):
  1193. async with lock:
  1194. logger.info("Pattern lock acquired - pattern has fully stopped")
  1195. except asyncio.TimeoutError:
  1196. logger.warning("Timeout waiting for pattern to stop - forcing cleanup")
  1197. timed_out = True
  1198. # Force cleanup of state even if pattern didn't release lock gracefully
  1199. state.current_playing_file = None
  1200. state.execution_progress = None
  1201. state.is_running = False
  1202. # Always clear the current playing file after stop
  1203. state.current_playing_file = None
  1204. state.execution_progress = None
  1205. # Call async function directly since we're in async context
  1206. await connection_manager.update_machine_position()
  1207. return not timed_out
  1208. except Exception as e:
  1209. logger.error(f"Error during stop_actions: {e}")
  1210. # Force cleanup state on error
  1211. state.current_playing_file = None
  1212. state.execution_progress = None
  1213. state.is_running = False
  1214. # Ensure we still update machine position even if there's an error
  1215. try:
  1216. await connection_manager.update_machine_position()
  1217. except Exception as update_err:
  1218. logger.error(f"Error updating machine position on error: {update_err}")
  1219. return False
  1220. async def move_polar(theta, rho, speed=None):
  1221. """
  1222. Queue a motion command to be executed in the dedicated motion control thread.
  1223. This makes motion control non-blocking for API endpoints.
  1224. Args:
  1225. theta (float): Target theta coordinate
  1226. rho (float): Target rho coordinate
  1227. speed (int, optional): Speed override. If None, uses state.speed
  1228. """
  1229. # Note: stop_requested is cleared once at pattern start (execute_theta_rho_file line 890)
  1230. # Don't clear it here on every coordinate - causes performance issues with event system
  1231. # Ensure motion control thread is running
  1232. if not motion_controller.running:
  1233. motion_controller.start()
  1234. # Create future for async/await pattern
  1235. loop = asyncio.get_event_loop()
  1236. future = loop.create_future()
  1237. # Create and queue motion command
  1238. command = MotionCommand(
  1239. command_type='move',
  1240. theta=theta,
  1241. rho=rho,
  1242. speed=speed,
  1243. future=future
  1244. )
  1245. motion_controller.command_queue.put(command)
  1246. logger.debug(f"Queued motion command: theta={theta}, rho={rho}, speed={speed}")
  1247. # Wait for command completion
  1248. await future
  1249. def pause_execution():
  1250. """Pause pattern execution using asyncio Event."""
  1251. logger.info("Pausing pattern execution")
  1252. state.pause_requested = True
  1253. get_pause_event().clear() # Clear the event to pause execution
  1254. return True
  1255. def resume_execution():
  1256. """Resume pattern execution using asyncio Event."""
  1257. logger.info("Resuming pattern execution")
  1258. state.pause_requested = False
  1259. get_pause_event().set() # Set the event to resume execution
  1260. return True
  1261. async def reset_theta():
  1262. logger.info('Resetting Theta')
  1263. state.current_theta = state.current_theta % (2 * pi)
  1264. # Call async function directly since we're in async context
  1265. await connection_manager.update_machine_position()
  1266. def set_speed(new_speed):
  1267. state.speed = new_speed
  1268. logger.info(f'Set new state.speed {new_speed}')
  1269. def get_status():
  1270. """Get the current status of pattern execution."""
  1271. status = {
  1272. "current_file": state.current_playing_file,
  1273. "is_paused": state.pause_requested or is_in_scheduled_pause_period(),
  1274. "manual_pause": state.pause_requested,
  1275. "scheduled_pause": is_in_scheduled_pause_period(),
  1276. "is_running": bool(state.current_playing_file and not state.stop_requested),
  1277. "is_homing": state.is_homing,
  1278. "is_clearing": state.is_clearing,
  1279. "progress": None,
  1280. "playlist": None,
  1281. "speed": state.speed,
  1282. "pause_time_remaining": state.pause_time_remaining,
  1283. "original_pause_time": getattr(state, 'original_pause_time', None),
  1284. "connection_status": state.conn.is_connected() if state.conn else False,
  1285. "current_theta": state.current_theta,
  1286. "current_rho": state.current_rho
  1287. }
  1288. # Add playlist information if available
  1289. if state.current_playlist and state.current_playlist_index is not None:
  1290. # When a clear pattern is running, the "next" pattern is the current main pattern
  1291. # (since the clear pattern runs before the main pattern at current_playlist_index)
  1292. if state.is_clearing:
  1293. next_file = state.current_playlist[state.current_playlist_index]
  1294. else:
  1295. next_index = state.current_playlist_index + 1
  1296. next_file = state.current_playlist[next_index] if next_index < len(state.current_playlist) else None
  1297. status["playlist"] = {
  1298. "current_index": state.current_playlist_index,
  1299. "total_files": len(state.current_playlist),
  1300. "mode": state.playlist_mode,
  1301. "next_file": next_file,
  1302. "files": state.current_playlist,
  1303. "name": state.current_playlist_name
  1304. }
  1305. if state.execution_progress:
  1306. current, total, remaining_time, elapsed_time = state.execution_progress
  1307. status["progress"] = {
  1308. "current": current,
  1309. "total": total,
  1310. "remaining_time": remaining_time,
  1311. "elapsed_time": elapsed_time,
  1312. "percentage": (current / total * 100) if total > 0 else 0
  1313. }
  1314. # Add historical execution time if available for this pattern at current speed
  1315. if state.current_playing_file:
  1316. pattern_name = os.path.basename(state.current_playing_file)
  1317. historical_time = get_last_completed_execution_time(pattern_name, state.speed)
  1318. if historical_time:
  1319. status["progress"]["last_completed_time"] = historical_time
  1320. return status
  1321. async def broadcast_progress():
  1322. """Background task to broadcast progress updates."""
  1323. from main import broadcast_status_update
  1324. while True:
  1325. # Send status updates regardless of pattern_lock state
  1326. status = get_status()
  1327. # Use the existing broadcast function from main.py
  1328. await broadcast_status_update(status)
  1329. # Check if we should stop broadcasting
  1330. if not state.current_playlist:
  1331. # If no playlist, only stop if no pattern is being executed
  1332. if not get_pattern_lock().locked():
  1333. logger.info("No playlist or pattern running, stopping broadcast")
  1334. break
  1335. # Wait before next update
  1336. await asyncio.sleep(1)