1
0

pattern_manager.py 95 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046
  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. from modules.led.idle_timeout_manager import idle_timeout_manager
  15. import queue
  16. from dataclasses import dataclass
  17. from typing import Optional, Callable, Literal
  18. # Configure logging
  19. logger = logging.getLogger(__name__)
  20. # Global state
  21. THETA_RHO_DIR = './patterns'
  22. os.makedirs(THETA_RHO_DIR, exist_ok=True)
  23. # Execution time log file (JSON Lines format - one JSON object per line)
  24. EXECUTION_LOG_FILE = './execution_times.jsonl'
  25. async def wait_with_interrupt(
  26. condition_fn: Callable[[], bool],
  27. check_stop: bool = True,
  28. check_skip: bool = True,
  29. interval: float = 1.0,
  30. ) -> Literal['completed', 'stopped', 'skipped']:
  31. """
  32. Wait while condition_fn() returns True, with instant interrupt support.
  33. Uses asyncio.Event for instant response to stop/skip requests rather than
  34. polling at fixed intervals. This ensures users get immediate feedback when
  35. pressing stop or skip buttons.
  36. Args:
  37. condition_fn: Function that returns True while waiting should continue
  38. check_stop: Whether to respond to stop requests (default True)
  39. check_skip: Whether to respond to skip requests (default True)
  40. interval: How often to re-check condition_fn in seconds (default 1.0)
  41. Returns:
  42. 'completed' - condition_fn() returned False (normal completion)
  43. 'stopped' - stop was requested
  44. 'skipped' - skip was requested
  45. Example:
  46. result = await wait_with_interrupt(
  47. lambda: state.pause_requested or is_in_scheduled_pause_period()
  48. )
  49. if result == 'stopped':
  50. return # Exit pattern execution
  51. if result == 'skipped':
  52. break # Skip to next pattern
  53. """
  54. while condition_fn():
  55. result = await state.wait_for_interrupt(
  56. timeout=interval,
  57. check_stop=check_stop,
  58. check_skip=check_skip,
  59. )
  60. if result == 'stopped':
  61. return 'stopped'
  62. if result == 'skipped':
  63. return 'skipped'
  64. # 'timeout' means we should re-check condition_fn
  65. return 'completed'
  66. def log_execution_time(pattern_name: str, table_type: str, speed: int, actual_time: float,
  67. total_coordinates: int, was_completed: bool):
  68. """Log pattern execution time to JSON Lines file for analysis.
  69. Args:
  70. pattern_name: Name of the pattern file
  71. table_type: Type of table (e.g., 'dune_weaver', 'dune_weaver_mini')
  72. speed: Speed setting used (0-255)
  73. actual_time: Actual execution time in seconds (excluding pauses)
  74. total_coordinates: Total number of coordinates in the pattern
  75. was_completed: Whether the pattern completed normally (not stopped/skipped)
  76. """
  77. # Format time as HH:MM:SS
  78. hours, remainder = divmod(int(actual_time), 3600)
  79. minutes, seconds = divmod(remainder, 60)
  80. time_formatted = f"{hours:02d}:{minutes:02d}:{seconds:02d}"
  81. log_entry = {
  82. "timestamp": datetime.now().isoformat(),
  83. "pattern_name": pattern_name,
  84. "table_type": table_type or "unknown",
  85. "speed": speed,
  86. "actual_time_seconds": round(actual_time, 2),
  87. "actual_time_formatted": time_formatted,
  88. "total_coordinates": total_coordinates,
  89. "completed": was_completed
  90. }
  91. try:
  92. with open(EXECUTION_LOG_FILE, 'a') as f:
  93. f.write(json.dumps(log_entry) + '\n')
  94. logger.info(f"Execution time logged: {pattern_name} - {time_formatted} (speed: {speed}, table: {table_type})")
  95. except Exception as e:
  96. logger.error(f"Failed to log execution time: {e}")
  97. def get_last_completed_execution_time(pattern_name: str, speed: float) -> Optional[dict]:
  98. """Get the last completed execution time for a pattern at a specific speed.
  99. Args:
  100. pattern_name: Name of the pattern file (e.g., 'circle.thr')
  101. speed: Speed setting to match
  102. Returns:
  103. Dict with execution time info if found, None otherwise.
  104. Format: {"actual_time_seconds": float, "actual_time_formatted": str, "timestamp": str}
  105. """
  106. if not os.path.exists(EXECUTION_LOG_FILE):
  107. return None
  108. try:
  109. matching_entry = None
  110. with open(EXECUTION_LOG_FILE, 'r') as f:
  111. for line in f:
  112. line = line.strip()
  113. if not line:
  114. continue
  115. try:
  116. entry = json.loads(line)
  117. # Only consider fully completed patterns (100% finished)
  118. if (entry.get('completed', False) and
  119. entry.get('pattern_name') == pattern_name and
  120. entry.get('speed') == speed):
  121. # Keep the most recent match (last one in file)
  122. matching_entry = entry
  123. except json.JSONDecodeError:
  124. continue
  125. if matching_entry:
  126. return {
  127. "actual_time_seconds": matching_entry.get('actual_time_seconds'),
  128. "actual_time_formatted": matching_entry.get('actual_time_formatted'),
  129. "timestamp": matching_entry.get('timestamp')
  130. }
  131. return None
  132. except Exception as e:
  133. logger.error(f"Failed to read execution time log: {e}")
  134. return None
  135. def get_pattern_execution_history(pattern_name: str) -> Optional[dict]:
  136. """Get the most recent completed execution for a pattern (any speed).
  137. Args:
  138. pattern_name: Name of the pattern file (e.g., 'circle.thr')
  139. Returns:
  140. Dict with execution time info if found, None otherwise.
  141. Format: {"actual_time_seconds": float, "actual_time_formatted": str,
  142. "speed": int, "timestamp": str}
  143. """
  144. if not os.path.exists(EXECUTION_LOG_FILE):
  145. return None
  146. try:
  147. matching_entry = None
  148. with open(EXECUTION_LOG_FILE, 'r') as f:
  149. for line in f:
  150. line = line.strip()
  151. if not line:
  152. continue
  153. try:
  154. entry = json.loads(line)
  155. # Only consider fully completed patterns
  156. if (entry.get('completed', False) and
  157. entry.get('pattern_name') == pattern_name):
  158. # Keep the most recent match (last one in file)
  159. matching_entry = entry
  160. except json.JSONDecodeError:
  161. continue
  162. if matching_entry:
  163. return {
  164. "actual_time_seconds": matching_entry.get('actual_time_seconds'),
  165. "actual_time_formatted": matching_entry.get('actual_time_formatted'),
  166. "speed": matching_entry.get('speed'),
  167. "timestamp": matching_entry.get('timestamp')
  168. }
  169. return None
  170. except Exception as e:
  171. logger.error(f"Failed to read execution time log: {e}")
  172. return None
  173. # Asyncio primitives - initialized lazily to avoid event loop issues
  174. # These must be created in the context of the running event loop
  175. pause_event: Optional[asyncio.Event] = None
  176. pattern_lock: Optional[asyncio.Lock] = None
  177. progress_update_task = None
  178. def get_pause_event() -> asyncio.Event:
  179. """Get or create the pause event in the current event loop."""
  180. global pause_event
  181. if pause_event is None:
  182. pause_event = asyncio.Event()
  183. pause_event.set() # Initially not paused
  184. return pause_event
  185. def get_pattern_lock() -> asyncio.Lock:
  186. """Get or create the pattern lock in the current event loop."""
  187. global pattern_lock
  188. if pattern_lock is None:
  189. pattern_lock = asyncio.Lock()
  190. return pattern_lock
  191. # Cache timezone at module level - read once per session (cleared when user changes timezone)
  192. _cached_timezone = None
  193. _cached_zoneinfo = None
  194. def _get_timezone():
  195. """Get and cache the timezone for Still Sands. Uses user-selected timezone if set, otherwise system timezone."""
  196. global _cached_timezone, _cached_zoneinfo
  197. if _cached_timezone is not None:
  198. return _cached_zoneinfo
  199. user_tz = 'UTC' # Default fallback
  200. # First, check if user has selected a specific timezone in settings
  201. if state.scheduled_pause_timezone:
  202. user_tz = state.scheduled_pause_timezone
  203. logger.info(f"Still Sands using timezone: {user_tz} (user-selected)")
  204. else:
  205. # Fall back to system timezone detection
  206. try:
  207. if os.path.exists('/etc/timezone'):
  208. with open('/etc/timezone', 'r') as f:
  209. user_tz = f.read().strip()
  210. logger.info(f"Still Sands using timezone: {user_tz} (from system)")
  211. # Fallback to TZ environment variable
  212. elif os.environ.get('TZ'):
  213. user_tz = os.environ.get('TZ')
  214. logger.info(f"Still Sands using timezone: {user_tz} (from environment)")
  215. else:
  216. logger.info("Still Sands using timezone: UTC (system default)")
  217. except Exception as e:
  218. logger.debug(f"Could not read timezone: {e}")
  219. # Cache the timezone
  220. _cached_timezone = user_tz
  221. try:
  222. _cached_zoneinfo = ZoneInfo(user_tz)
  223. except Exception as e:
  224. logger.warning(f"Invalid timezone '{user_tz}', falling back to system time: {e}")
  225. _cached_zoneinfo = None
  226. return _cached_zoneinfo
  227. def is_in_scheduled_pause_period():
  228. """Check if current time falls within any scheduled pause period."""
  229. if not state.scheduled_pause_enabled or not state.scheduled_pause_time_slots:
  230. return False
  231. # Get cached timezone (user-selected or system default)
  232. tz_info = _get_timezone()
  233. try:
  234. # Get current time in user's timezone
  235. if tz_info:
  236. now = datetime.now(tz_info)
  237. else:
  238. now = datetime.now()
  239. except Exception as e:
  240. logger.warning(f"Error getting current time: {e}")
  241. now = datetime.now()
  242. current_time = now.time()
  243. current_weekday = now.strftime("%A").lower() # monday, tuesday, etc.
  244. for slot in state.scheduled_pause_time_slots:
  245. # Parse start and end times
  246. try:
  247. start_time = datetime_time.fromisoformat(slot['start_time'])
  248. end_time = datetime_time.fromisoformat(slot['end_time'])
  249. except (ValueError, KeyError):
  250. logger.warning(f"Invalid time format in scheduled pause slot: {slot}")
  251. continue
  252. # Check if this slot applies to today
  253. slot_applies_today = False
  254. days_setting = slot.get('days', 'daily')
  255. if days_setting == 'daily':
  256. slot_applies_today = True
  257. elif days_setting == 'weekdays':
  258. slot_applies_today = current_weekday in ['monday', 'tuesday', 'wednesday', 'thursday', 'friday']
  259. elif days_setting == 'weekends':
  260. slot_applies_today = current_weekday in ['saturday', 'sunday']
  261. elif days_setting == 'custom':
  262. custom_days = slot.get('custom_days', [])
  263. slot_applies_today = current_weekday in custom_days
  264. if not slot_applies_today:
  265. continue
  266. # Check if current time is within the pause period
  267. if start_time <= end_time:
  268. # Normal case: start and end are on the same day
  269. if start_time <= current_time <= end_time:
  270. return True
  271. else:
  272. # Time spans midnight: start is before midnight, end is after midnight
  273. if current_time >= start_time or current_time <= end_time:
  274. return True
  275. return False
  276. async def check_table_is_idle() -> bool:
  277. """
  278. Check if the table is currently idle by querying actual machine status.
  279. Returns True if idle, False if playing/moving.
  280. This checks the real machine state rather than relying on state variables,
  281. making it more reliable for detecting when table is truly idle.
  282. """
  283. # Use the connection_manager's is_machine_idle() function
  284. # Run it in a thread since it's a synchronous function
  285. return await asyncio.to_thread(connection_manager.is_machine_idle)
  286. async def start_idle_led_timeout(check_still_sands: bool = True):
  287. """
  288. Set LED to idle state and start timeout if enabled.
  289. Handles Still Sands: if in scheduled pause period with LED control enabled,
  290. turns off LEDs instead of showing idle effect.
  291. Should be called whenever the table goes idle.
  292. Args:
  293. check_still_sands: If True, checks Still Sands period and turns off LEDs if applicable.
  294. Set to False when caller already handles Still Sands logic
  295. (e.g., during pause with "finish pattern first" mode).
  296. """
  297. if not state.led_controller:
  298. return
  299. if not state.led_automation_enabled:
  300. # Manual mode: Still Sands can still turn OFF, but skip idle effect + timeout
  301. if check_still_sands and is_in_scheduled_pause_period() and state.scheduled_pause_control_wled:
  302. logger.info("Manual mode: Turning off LEDs during Still Sands period")
  303. await state.led_controller.set_power_async(0)
  304. return
  305. # Still Sands with LED control: turn off instead of idle effect
  306. if check_still_sands and is_in_scheduled_pause_period() and state.scheduled_pause_control_wled:
  307. logger.info("Turning off LED lights during Still Sands period")
  308. await state.led_controller.set_power_async(0)
  309. return
  310. # Normal flow: show idle effect
  311. # For WLED: always trigger (uses hardcoded preset 1)
  312. # For DW_LED: only trigger if effect is configured
  313. if state.led_provider != "wled" and not state.dw_led_idle_effect:
  314. logger.debug("No idle effect configured, leaving LEDs unchanged")
  315. return
  316. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  317. # Start timeout if enabled
  318. if not state.dw_led_idle_timeout_enabled:
  319. logger.debug("Idle LED timeout not enabled")
  320. return
  321. timeout_minutes = state.dw_led_idle_timeout_minutes
  322. if timeout_minutes <= 0:
  323. logger.debug("Idle LED timeout not configured (timeout <= 0)")
  324. return
  325. logger.debug(f"Starting idle LED timeout: {timeout_minutes} minutes")
  326. idle_timeout_manager.start_idle_timeout(
  327. timeout_minutes=timeout_minutes,
  328. state=state,
  329. check_idle_callback=check_table_is_idle
  330. )
  331. # Motion Control Thread Infrastructure
  332. @dataclass
  333. class MotionCommand:
  334. """Represents a motion command for the motion control thread."""
  335. command_type: str # 'move', 'stop', 'pause', 'resume', 'shutdown'
  336. theta: Optional[float] = None
  337. rho: Optional[float] = None
  338. speed: Optional[float] = None
  339. callback: Optional[Callable] = None
  340. future: Optional[asyncio.Future] = None
  341. class MotionControlThread:
  342. """Dedicated thread for hardware motion control operations."""
  343. def __init__(self):
  344. self.command_queue = queue.Queue()
  345. self.thread = None
  346. self.running = False
  347. self.paused = False
  348. def start(self):
  349. """Start the motion control thread with elevated priority."""
  350. if self.thread and self.thread.is_alive():
  351. return
  352. self.running = True
  353. self.thread = threading.Thread(target=self._motion_loop, daemon=True)
  354. self.thread.start()
  355. logger.info("Motion control thread started")
  356. def stop(self):
  357. """Stop the motion control thread."""
  358. if not self.running:
  359. return
  360. self.running = False
  361. # Send shutdown command
  362. self.command_queue.put(MotionCommand('shutdown'))
  363. if self.thread and self.thread.is_alive():
  364. self.thread.join(timeout=5.0)
  365. logger.info("Motion control thread stopped")
  366. def _motion_loop(self):
  367. """Main loop for the motion control thread."""
  368. logger.info("Motion control thread loop started")
  369. while self.running:
  370. try:
  371. # Get command with timeout to allow periodic checks
  372. command = self.command_queue.get(timeout=1.0)
  373. if command.command_type == 'shutdown':
  374. break
  375. elif command.command_type == 'move':
  376. self._execute_move(command)
  377. elif command.command_type == 'pause':
  378. self.paused = True
  379. elif command.command_type == 'resume':
  380. self.paused = False
  381. elif command.command_type == 'stop':
  382. # Clear any pending commands
  383. while not self.command_queue.empty():
  384. try:
  385. self.command_queue.get_nowait()
  386. except queue.Empty:
  387. break
  388. self.command_queue.task_done()
  389. except queue.Empty:
  390. # Timeout - continue loop for shutdown check
  391. continue
  392. except Exception as e:
  393. logger.error(f"Error in motion control thread: {e}")
  394. logger.info("Motion control thread loop ended")
  395. def _execute_move(self, command: MotionCommand):
  396. """Execute a move command in the motion thread."""
  397. try:
  398. # Wait if paused
  399. while self.paused and self.running:
  400. time.sleep(0.1)
  401. if not self.running:
  402. return
  403. # Execute the actual motion using sync version
  404. self._move_polar_sync(command.theta, command.rho, command.speed)
  405. # Signal completion if future provided
  406. if command.future and not command.future.done():
  407. command.future.get_loop().call_soon_threadsafe(
  408. command.future.set_result, None
  409. )
  410. except Exception as e:
  411. logger.error(f"Error executing move command: {e}")
  412. if command.future and not command.future.done():
  413. command.future.get_loop().call_soon_threadsafe(
  414. command.future.set_exception, e
  415. )
  416. def _move_polar_sync(self, theta: float, rho: float, speed: Optional[float] = None):
  417. """Synchronous version of move_polar for use in motion thread."""
  418. # Check for valid machine position (can be None if homing failed)
  419. if state.machine_x is None or state.machine_y is None:
  420. logger.error("Cannot execute move: machine position unknown (homing may have failed)")
  421. logger.error("Please home the machine before running patterns")
  422. state.stop_requested = True
  423. return
  424. # This is the original sync logic but running in dedicated thread
  425. if state.table_type == 'dune_weaver_mini':
  426. x_scaling_factor = 2
  427. y_scaling_factor = 3.7
  428. else:
  429. x_scaling_factor = 2
  430. y_scaling_factor = 5
  431. delta_theta = theta - state.current_theta
  432. delta_rho = rho - state.current_rho
  433. x_increment = delta_theta * 100 / (2 * pi * x_scaling_factor)
  434. y_increment = delta_rho * 100 / y_scaling_factor
  435. x_total_steps = state.x_steps_per_mm * (100/x_scaling_factor)
  436. y_total_steps = state.y_steps_per_mm * (100/y_scaling_factor)
  437. offset = x_increment * (x_total_steps * x_scaling_factor / (state.gear_ratio * y_total_steps * y_scaling_factor))
  438. if state.table_type == 'dune_weaver_mini' or state.y_steps_per_mm == 546:
  439. y_increment -= offset
  440. else:
  441. y_increment += offset
  442. new_x_abs = state.machine_x + x_increment
  443. new_y_abs = state.machine_y + y_increment
  444. # Use provided speed or fall back to state.speed
  445. actual_speed = speed if speed is not None else state.speed
  446. # Validate coordinates before sending to prevent GRBL error:2
  447. if isnan(new_x_abs) or isnan(new_y_abs) or isinf(new_x_abs) or isinf(new_y_abs):
  448. logger.error(f"Motion thread: Invalid coordinates detected - X:{new_x_abs}, Y:{new_y_abs}")
  449. logger.error(f" theta:{theta}, rho:{rho}, current_theta:{state.current_theta}, current_rho:{state.current_rho}")
  450. 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}")
  451. state.stop_requested = True
  452. return
  453. # Call sync version of send_grbl_coordinates in this thread
  454. # Use 2 decimal precision to reduce GRBL parsing overhead
  455. self._send_grbl_coordinates_sync(round(new_x_abs, 2), round(new_y_abs, 2), actual_speed)
  456. # Update state
  457. state.current_theta = theta
  458. state.current_rho = rho
  459. state.machine_x = new_x_abs
  460. state.machine_y = new_y_abs
  461. def _send_grbl_coordinates_sync(self, x: float, y: float, speed: int = 600, timeout: int = 2, home: bool = False):
  462. """Synchronous version of send_grbl_coordinates for motion thread.
  463. Waits for 'ok' with a timeout. GRBL sends 'ok' after the move completes,
  464. which can take many seconds at slow speeds. We use a generous timeout
  465. (120 seconds) to handle slow movements, but prevent indefinite hangs.
  466. Includes retry logic for serial corruption errors (common on Pi 3B+).
  467. """
  468. gcode = f"$J=G91 G21 Y{y:.2f} F{speed}" if home else f"G1 X{x:.2f} Y{y:.2f} F{speed}"
  469. max_wait_time = 120 # Maximum seconds to wait for 'ok' response
  470. max_corruption_retries = 10 # Max retries for corruption-type errors
  471. max_timeout_retries = 10 # Max retries for timeout (lost 'ok' response)
  472. corruption_retry_count = 0
  473. timeout_retry_count = 0
  474. # GRBL error codes that indicate likely serial corruption (syntax errors)
  475. # These are recoverable by resending the command
  476. corruption_error_codes = {
  477. 'error:1', # Expected command letter
  478. 'error:2', # Bad number format
  479. 'error:20', # Invalid gcode ID (e.g., G5s instead of G53)
  480. 'error:21', # Invalid gcode command value
  481. 'error:22', # Invalid gcode command value in negative
  482. 'error:23', # Invalid gcode command value in decimal
  483. }
  484. while True:
  485. # Check stop_requested at the start of each iteration
  486. if state.stop_requested:
  487. logger.debug("Motion thread: Stop requested, aborting command")
  488. return False
  489. try:
  490. # Clear any stale input data before sending to prevent interleaving
  491. # This helps with timing issues on slower UARTs like Pi 3B+
  492. if hasattr(state.conn, 'reset_input_buffer'):
  493. state.conn.reset_input_buffer()
  494. logger.debug(f"Motion thread sending G-code: {gcode}")
  495. state.conn.send(gcode + "\n")
  496. # Small delay for serial buffer to stabilize on slower UARTs
  497. # Prevents timing-related corruption on Pi 3B+
  498. time.sleep(0.005)
  499. # Wait for 'ok' with timeout
  500. wait_start = time.time()
  501. while True:
  502. # Check stop_requested while waiting
  503. if state.stop_requested:
  504. logger.debug("Motion thread: Stop requested while waiting for response")
  505. return False
  506. # Check for timeout
  507. elapsed = time.time() - wait_start
  508. if elapsed > max_wait_time:
  509. logger.warning(f"Motion thread: Timeout ({max_wait_time}s) waiting for 'ok' response")
  510. logger.warning(f"Motion thread: Failed command was: {gcode}")
  511. # Attempt to recover by checking machine status
  512. # The 'ok' might have been lost but command may have executed
  513. logger.info("Motion thread: Attempting timeout recovery - checking machine status")
  514. logger.info(f"Motion thread: Current retry counts - timeout: {timeout_retry_count}/{max_timeout_retries}, corruption: {corruption_retry_count}/{max_corruption_retries}")
  515. try:
  516. # Check connection state first
  517. conn_type = type(state.conn).__name__ if state.conn else "None"
  518. logger.info(f"Motion thread: Connection type: {conn_type}")
  519. if not state.conn:
  520. logger.error("Motion thread: Connection object is None!")
  521. raise Exception("Connection is None")
  522. # Clear buffer first
  523. if hasattr(state.conn, 'reset_input_buffer'):
  524. state.conn.reset_input_buffer()
  525. logger.info("Motion thread: Input buffer cleared")
  526. else:
  527. logger.warning("Motion thread: Connection has no reset_input_buffer method")
  528. # Check if there's data waiting before we send
  529. if hasattr(state.conn, 'in_waiting'):
  530. waiting = state.conn.in_waiting()
  531. logger.info(f"Motion thread: Bytes waiting in buffer after clear: {waiting}")
  532. # Send status query
  533. logger.info("Motion thread: Sending status query '?'...")
  534. state.conn.send("?\n")
  535. time.sleep(0.2)
  536. logger.info("Motion thread: Status query sent, reading responses...")
  537. # Try to read status response
  538. status_response = None
  539. responses_received = []
  540. for i in range(10):
  541. resp = state.conn.readline()
  542. if resp:
  543. responses_received.append(resp)
  544. logger.info(f"Motion thread: Recovery response [{i+1}/10]: '{resp}'")
  545. if '<' in resp or 'Idle' in resp or 'Run' in resp or 'Hold' in resp or 'Alarm' in resp:
  546. status_response = resp
  547. logger.info(f"Motion thread: Found valid status response: '{resp}'")
  548. break
  549. # Also check for 'ok' that might have been delayed
  550. if resp.lower() == 'ok':
  551. logger.info("Motion thread: Received delayed 'ok' during recovery - SUCCESS")
  552. return True
  553. else:
  554. logger.debug(f"Motion thread: Recovery read [{i+1}/10]: no data (timeout)")
  555. time.sleep(0.05)
  556. # Log summary of what we received
  557. if responses_received:
  558. logger.info(f"Motion thread: Total responses received during recovery: {len(responses_received)}")
  559. logger.info(f"Motion thread: All responses: {responses_received}")
  560. else:
  561. logger.warning("Motion thread: No responses received during recovery - connection may be dead")
  562. if status_response:
  563. if 'Idle' in status_response:
  564. # Machine is idle - command likely completed, 'ok' was lost
  565. logger.info("Motion thread: Machine is Idle - assuming command completed (ok was lost) - SUCCESS")
  566. return True
  567. elif 'Run' in status_response:
  568. # Machine still running - extend timeout
  569. logger.info("Motion thread: Machine still running, extending wait time")
  570. wait_start = time.time() # Reset timeout
  571. continue
  572. elif 'Hold' in status_response:
  573. # Machine is in Hold state - attempt to resume
  574. logger.warning(f"Motion thread: Machine in Hold state: '{status_response}'")
  575. logger.info("Motion thread: Sending cycle start command '~' to resume from Hold...")
  576. # Send cycle start command to resume
  577. state.conn.send("~\n")
  578. time.sleep(0.3) # Give time for resume to process
  579. # Re-check status after resume attempt
  580. state.conn.send("?\n")
  581. time.sleep(0.2)
  582. # Read new status
  583. resume_response = None
  584. for _ in range(5):
  585. resp = state.conn.readline()
  586. if resp:
  587. logger.info(f"Motion thread: Post-resume response: '{resp}'")
  588. if '<' in resp:
  589. resume_response = resp
  590. break
  591. time.sleep(0.05)
  592. if resume_response:
  593. if 'Idle' in resume_response:
  594. logger.info("Motion thread: Machine resumed and is now Idle - SUCCESS")
  595. return True
  596. elif 'Run' in resume_response:
  597. logger.info("Motion thread: Machine resumed and running, extending wait time")
  598. wait_start = time.time()
  599. continue
  600. elif 'Hold' in resume_response:
  601. # Still in Hold - may need user intervention
  602. logger.warning(f"Motion thread: Still in Hold after resume: '{resume_response}'")
  603. else:
  604. logger.warning("Motion thread: No response after resume attempt")
  605. elif 'Alarm' in status_response:
  606. # Machine is in Alarm state - attempt to unlock
  607. logger.warning(f"Motion thread: Machine in ALARM state: '{status_response}'")
  608. logger.info("Motion thread: Sending $X to unlock from Alarm...")
  609. # Send unlock command
  610. state.conn.send("$X\n")
  611. time.sleep(0.5) # Give time for unlock to process
  612. # Re-check status after unlock attempt
  613. state.conn.send("?\n")
  614. time.sleep(0.2)
  615. # Read new status
  616. unlock_response = None
  617. for _ in range(5):
  618. resp = state.conn.readline()
  619. if resp:
  620. logger.info(f"Motion thread: Post-unlock response: '{resp}'")
  621. if '<' in resp:
  622. unlock_response = resp
  623. break
  624. time.sleep(0.05)
  625. if unlock_response:
  626. if 'Idle' in unlock_response:
  627. logger.info("Motion thread: Machine unlocked and is now Idle - retrying command")
  628. # Don't return True - we need to resend the failed command
  629. break # Break inner loop to retry the command
  630. elif 'Alarm' in unlock_response:
  631. # Still in Alarm - underlying issue persists (e.g., sensor triggered)
  632. logger.error(f"Motion thread: Still in ALARM after unlock: '{unlock_response}'")
  633. logger.error("Motion thread: Machine may need physical attention")
  634. state.stop_requested = True
  635. return False
  636. else:
  637. logger.warning("Motion thread: No response after unlock attempt")
  638. else:
  639. logger.warning(f"Motion thread: Unrecognized status response: '{status_response}'")
  640. else:
  641. logger.warning("Motion thread: No valid status response found in any received data")
  642. # No valid status response - connection may be dead
  643. timeout_retry_count += 1
  644. if timeout_retry_count <= max_timeout_retries:
  645. logger.warning(f"Motion thread: Recovery failed, will retry command ({timeout_retry_count}/{max_timeout_retries})")
  646. time.sleep(0.1)
  647. break # Break inner loop to resend command
  648. else:
  649. logger.error(f"Motion thread: Max timeout retries ({max_timeout_retries}) exceeded")
  650. except Exception as e:
  651. logger.error(f"Motion thread: Error during timeout recovery: {e}")
  652. import traceback
  653. logger.error(f"Motion thread: Traceback: {traceback.format_exc()}")
  654. # Max retries exceeded or recovery failed
  655. logger.error("=" * 60)
  656. logger.error("Motion thread: TIMEOUT RECOVERY FAILED - STOPPING PATTERN")
  657. logger.error(f" Failed command: {gcode}")
  658. logger.error(f" Timeout retries used: {timeout_retry_count}/{max_timeout_retries}")
  659. logger.error(f" Corruption retries used: {corruption_retry_count}/{max_corruption_retries}")
  660. logger.error(" Possible causes:")
  661. logger.error(" - Serial connection lost or unstable")
  662. logger.error(" - Hardware controller unresponsive")
  663. logger.error(" - USB power issue (try powered hub)")
  664. logger.error("=" * 60)
  665. state.stop_requested = True
  666. return False
  667. response = state.conn.readline()
  668. if response:
  669. logger.debug(f"Motion thread response: {response}")
  670. if response.lower() == "ok":
  671. logger.debug("Motion thread: Command execution confirmed.")
  672. # Reset corruption retry count on success
  673. if corruption_retry_count > 0:
  674. logger.info(f"Motion thread: Command succeeded after {corruption_retry_count} corruption retry(ies)")
  675. return True
  676. # Handle GRBL errors
  677. if response.lower().startswith("error"):
  678. error_code = response.lower().split()[0] if response else ""
  679. # Check if this is a corruption-type error (recoverable)
  680. if error_code in corruption_error_codes:
  681. corruption_retry_count += 1
  682. if corruption_retry_count <= max_corruption_retries:
  683. logger.warning(f"Motion thread: Likely serial corruption detected ({response})")
  684. logger.warning(f"Motion thread: Retrying command ({corruption_retry_count}/{max_corruption_retries}): {gcode}")
  685. # Clear buffer and wait longer before retry
  686. if hasattr(state.conn, 'reset_input_buffer'):
  687. state.conn.reset_input_buffer()
  688. time.sleep(0.02) # 20ms delay before retry
  689. break # Break inner loop to retry send
  690. else:
  691. logger.error(f"Motion thread: Max corruption retries ({max_corruption_retries}) exceeded")
  692. logger.error(f"Motion thread: GRBL error received: {response}")
  693. logger.error(f"Failed command: {gcode}")
  694. logger.error("Stopping pattern due to persistent serial corruption")
  695. state.stop_requested = True
  696. return False
  697. else:
  698. # Non-corruption error - stop immediately
  699. logger.error(f"Motion thread: GRBL error received: {response}")
  700. logger.error(f"Failed command: {gcode}")
  701. logger.error("Stopping pattern due to GRBL error")
  702. state.stop_requested = True
  703. return False
  704. # Handle GRBL alarms - machine needs attention
  705. if "alarm" in response.lower():
  706. logger.error(f"Motion thread: GRBL ALARM: {response}")
  707. logger.error("Machine alarm triggered - stopping pattern")
  708. state.stop_requested = True
  709. return False
  710. # FluidNC may echo commands back before sending 'ok'
  711. # Silently ignore echoed G-code commands (G0, G1, $J, etc.)
  712. if response.startswith(('G0', 'G1', 'G2', 'G3', '$J', 'M')):
  713. logger.debug(f"Motion thread: Ignoring echoed command: {response}")
  714. continue # Read next line to get 'ok'
  715. # Check for corruption indicator in MSG:ERR responses
  716. if 'MSG:ERR' in response and 'Bad GCode' in response:
  717. corruption_retry_count += 1
  718. if corruption_retry_count <= max_corruption_retries:
  719. logger.warning(f"Motion thread: Corrupted command detected: {response}")
  720. logger.warning(f"Motion thread: Retrying command ({corruption_retry_count}/{max_corruption_retries}): {gcode}")
  721. # Don't break yet - wait for the error:XX that follows
  722. continue
  723. # If we've exceeded retries, the error:XX handler above will catch it
  724. # Log truly unexpected responses
  725. logger.warning(f"Motion thread: Unexpected response: '{response}'")
  726. else:
  727. # Log periodically when waiting for response (every 30s)
  728. if int(elapsed) > 0 and int(elapsed) % 30 == 0 and elapsed - int(elapsed) < 0.1:
  729. logger.warning(f"Motion thread: Still waiting for 'ok' after {int(elapsed)}s for command: {gcode}")
  730. else:
  731. # Inner while loop completed without break - shouldn't happen normally
  732. # This means we hit timeout, which is handled above
  733. continue
  734. except Exception as e:
  735. error_str = str(e)
  736. logger.warning(f"Motion thread error sending command: {error_str}")
  737. # Immediately return for device not configured errors
  738. if "Device not configured" in error_str or "Errno 6" in error_str:
  739. logger.error(f"Motion thread: Device configuration error detected: {error_str}")
  740. state.stop_requested = True
  741. state.conn = None
  742. state.is_connected = False
  743. logger.info("Connection marked as disconnected due to device error")
  744. return False
  745. # Retry on exception or corruption error
  746. logger.warning(f"Motion thread: Retrying {gcode}...")
  747. time.sleep(0.1)
  748. # Global motion control thread instance
  749. motion_controller = MotionControlThread()
  750. async def cleanup_pattern_manager():
  751. """Clean up pattern manager resources"""
  752. global progress_update_task, pattern_lock, pause_event
  753. try:
  754. # Signal stop to allow any running pattern to exit gracefully
  755. state.stop_requested = True
  756. # Stop motion control thread
  757. motion_controller.stop()
  758. # Cancel progress update task if running
  759. if progress_update_task and not progress_update_task.done():
  760. try:
  761. progress_update_task.cancel()
  762. # Wait for task to actually cancel
  763. try:
  764. await progress_update_task
  765. except asyncio.CancelledError:
  766. pass
  767. except Exception as e:
  768. logger.error(f"Error cancelling progress update task: {e}")
  769. # Clean up pattern lock - wait for it to be released naturally, don't force release
  770. # Force releasing an asyncio.Lock can corrupt internal state if held by another coroutine
  771. current_lock = pattern_lock
  772. if current_lock and current_lock.locked():
  773. logger.info("Pattern lock is held, waiting for release (max 5s)...")
  774. try:
  775. # Wait with timeout for the lock to become available
  776. # Use wait_for for Python 3.9 compatibility (asyncio.timeout is 3.11+)
  777. async def acquire_lock():
  778. async with current_lock:
  779. pass # Lock acquired means previous holder released it
  780. await asyncio.wait_for(acquire_lock(), timeout=5.0)
  781. logger.info("Pattern lock released normally")
  782. except asyncio.TimeoutError:
  783. logger.warning("Timed out waiting for pattern lock - creating fresh lock")
  784. except Exception as e:
  785. logger.error(f"Error waiting for pattern lock: {e}")
  786. # Clean up pause event - wake up any waiting tasks, then create fresh event
  787. current_event = pause_event
  788. if current_event:
  789. try:
  790. current_event.set() # Wake up any waiting tasks
  791. except Exception as e:
  792. logger.error(f"Error setting pause event: {e}")
  793. # Clean up pause condition from state
  794. if state.pause_condition:
  795. try:
  796. with state.pause_condition:
  797. state.pause_condition.notify_all()
  798. state.pause_condition = threading.Condition()
  799. except Exception as e:
  800. logger.error(f"Error cleaning up pause condition: {e}")
  801. # Clear all state variables
  802. state.current_playing_file = None
  803. state.execution_progress = 0
  804. state.is_running = False
  805. state.pause_requested = False
  806. state.stop_requested = True
  807. state.is_clearing = False
  808. # Reset machine position
  809. await connection_manager.update_machine_position()
  810. logger.info("Pattern manager resources cleaned up")
  811. except Exception as e:
  812. logger.error(f"Error during pattern manager cleanup: {e}")
  813. finally:
  814. # Reset to fresh instances instead of None to allow continued operation
  815. progress_update_task = None
  816. pattern_lock = asyncio.Lock() # Fresh lock instead of None
  817. pause_event = asyncio.Event() # Fresh event instead of None
  818. pause_event.set() # Initially not paused
  819. def list_theta_rho_files():
  820. files = []
  821. for root, dirs, filenames in os.walk(THETA_RHO_DIR):
  822. # Skip cached_images directories to avoid scanning thousands of WebP files
  823. if 'cached_images' in dirs:
  824. dirs.remove('cached_images')
  825. # Filter .thr files during traversal for better performance
  826. thr_files = [f for f in filenames if f.endswith('.thr')]
  827. for file in thr_files:
  828. relative_path = os.path.relpath(os.path.join(root, file), THETA_RHO_DIR)
  829. # Normalize path separators to always use forward slashes for consistency across platforms
  830. relative_path = relative_path.replace(os.sep, '/')
  831. files.append(relative_path)
  832. logger.debug(f"Found {len(files)} theta-rho files")
  833. return files
  834. def parse_theta_rho_file(file_path):
  835. """Parse a theta-rho file and return a list of (theta, rho) pairs."""
  836. coordinates = []
  837. try:
  838. logger.debug(f"Parsing theta-rho file: {file_path}")
  839. with open(file_path, 'r', encoding='utf-8') as file:
  840. for line in file:
  841. line = line.strip()
  842. if not line or line.startswith("#"):
  843. continue
  844. try:
  845. theta, rho = map(float, line.split())
  846. coordinates.append((theta, rho))
  847. except ValueError:
  848. logger.warning(f"Skipping invalid line: {line}")
  849. continue
  850. except Exception as e:
  851. logger.error(f"Error reading file: {e}")
  852. return coordinates
  853. logger.debug(f"Parsed {len(coordinates)} coordinates from {file_path}")
  854. return coordinates
  855. def get_first_rho_from_cache(file_path, cache_data=None):
  856. """Get the first rho value from cached metadata, falling back to file parsing if needed.
  857. Args:
  858. file_path: Path to the pattern file
  859. cache_data: Optional pre-loaded cache data dict to avoid repeated disk I/O
  860. """
  861. try:
  862. # Import cache_manager locally to avoid circular import
  863. from modules.core import cache_manager
  864. # Try to get from metadata cache first
  865. # Use relative path from THETA_RHO_DIR to match cache keys (which include subdirectories)
  866. file_name = os.path.relpath(file_path, THETA_RHO_DIR)
  867. # Use provided cache_data if available, otherwise load from disk
  868. if cache_data is not None:
  869. # Extract metadata directly from provided cache
  870. data_section = cache_data.get('data', {})
  871. if file_name in data_section:
  872. cached_entry = data_section[file_name]
  873. metadata = cached_entry.get('metadata')
  874. # When cache_data is provided, trust it without checking mtime
  875. # This significantly speeds up bulk operations (playlists with 1000+ patterns)
  876. # by avoiding 1000+ os.path.getmtime() calls on slow storage (e.g., Pi SD cards)
  877. if metadata and 'first_coordinate' in metadata:
  878. return metadata['first_coordinate']['y']
  879. else:
  880. # Fall back to loading cache from disk (original behavior)
  881. metadata = cache_manager.get_pattern_metadata(file_name)
  882. if metadata and 'first_coordinate' in metadata:
  883. # In the cache, 'x' is theta and 'y' is rho
  884. return metadata['first_coordinate']['y']
  885. # Fallback to parsing the file if not in cache
  886. logger.debug(f"Metadata not cached for {file_name}, parsing file")
  887. coordinates = parse_theta_rho_file(file_path)
  888. if coordinates:
  889. return coordinates[0][1] # Return rho value
  890. return None
  891. except Exception as e:
  892. logger.warning(f"Error getting first rho from cache for {file_path}: {str(e)}")
  893. return None
  894. def get_clear_pattern_file(clear_pattern_mode, path=None, cache_data=None):
  895. """Return a .thr file path based on pattern_name and table type.
  896. Args:
  897. clear_pattern_mode: The clear pattern mode to use
  898. path: Optional path to the pattern file for adaptive mode
  899. cache_data: Optional pre-loaded cache data dict to avoid repeated disk I/O
  900. """
  901. if not clear_pattern_mode or clear_pattern_mode == 'none':
  902. return
  903. # Define patterns for each table type
  904. clear_patterns = {
  905. 'dune_weaver': {
  906. 'clear_from_out': './patterns/clear_from_out.thr',
  907. 'clear_from_in': './patterns/clear_from_in.thr',
  908. 'clear_sideway': './patterns/clear_sideway.thr'
  909. },
  910. 'dune_weaver_mini': {
  911. 'clear_from_out': './patterns/clear_from_out_mini.thr',
  912. 'clear_from_in': './patterns/clear_from_in_mini.thr',
  913. 'clear_sideway': './patterns/clear_sideway_mini.thr'
  914. },
  915. 'dune_weaver_mini_pro': {
  916. 'clear_from_out': './patterns/clear_from_out_mini.thr',
  917. 'clear_from_in': './patterns/clear_from_in_mini.thr',
  918. 'clear_sideway': './patterns/clear_sideway_mini.thr'
  919. },
  920. 'dune_weaver_pro': {
  921. 'clear_from_out': './patterns/clear_from_out_pro.thr',
  922. 'clear_from_out_Ultra': './patterns/clear_from_out_Ultra.thr',
  923. 'clear_from_in': './patterns/clear_from_in_pro.thr',
  924. 'clear_from_in_Ultra': './patterns/clear_from_in_Ultra.thr',
  925. 'clear_sideway': './patterns/clear_sideway_pro.thr'
  926. }
  927. }
  928. # Get patterns for current table type, fallback to standard patterns if type not found
  929. table_patterns = clear_patterns.get(state.table_type, clear_patterns['dune_weaver'])
  930. # Check for custom patterns first
  931. if state.custom_clear_from_out and clear_pattern_mode in ['clear_from_out', 'adaptive']:
  932. if clear_pattern_mode == 'adaptive':
  933. # For adaptive mode, use cached metadata to check first rho
  934. if path:
  935. first_rho = get_first_rho_from_cache(path, cache_data)
  936. if first_rho is not None and first_rho < 0.5:
  937. # Use custom clear_from_out if set
  938. custom_path = os.path.join('./patterns', state.custom_clear_from_out)
  939. if os.path.exists(custom_path):
  940. logger.debug(f"Using custom clear_from_out: {custom_path}")
  941. return custom_path
  942. elif clear_pattern_mode == 'clear_from_out':
  943. custom_path = os.path.join('./patterns', state.custom_clear_from_out)
  944. if os.path.exists(custom_path):
  945. logger.debug(f"Using custom clear_from_out: {custom_path}")
  946. return custom_path
  947. if state.custom_clear_from_in and clear_pattern_mode in ['clear_from_in', 'adaptive']:
  948. if clear_pattern_mode == 'adaptive':
  949. # For adaptive mode, use cached metadata to check first rho
  950. if path:
  951. first_rho = get_first_rho_from_cache(path, cache_data)
  952. if first_rho is not None and first_rho >= 0.5:
  953. # Use custom clear_from_in if set
  954. custom_path = os.path.join('./patterns', state.custom_clear_from_in)
  955. if os.path.exists(custom_path):
  956. logger.debug(f"Using custom clear_from_in: {custom_path}")
  957. return custom_path
  958. elif clear_pattern_mode == 'clear_from_in':
  959. custom_path = os.path.join('./patterns', state.custom_clear_from_in)
  960. if os.path.exists(custom_path):
  961. logger.debug(f"Using custom clear_from_in: {custom_path}")
  962. return custom_path
  963. logger.debug(f"Clear pattern mode: {clear_pattern_mode} for table type: {state.table_type}")
  964. if clear_pattern_mode == "random":
  965. return random.choice(list(table_patterns.values()))
  966. if clear_pattern_mode == 'adaptive':
  967. if not path:
  968. logger.warning("No path provided for adaptive clear pattern")
  969. return random.choice(list(table_patterns.values()))
  970. # Use cached metadata to get first rho value
  971. first_rho = get_first_rho_from_cache(path, cache_data)
  972. if first_rho is None:
  973. logger.warning("Could not determine first rho value for adaptive clear pattern")
  974. return random.choice(list(table_patterns.values()))
  975. if first_rho < 0.5:
  976. return table_patterns['clear_from_out']
  977. else:
  978. return table_patterns['clear_from_in']
  979. else:
  980. if clear_pattern_mode not in table_patterns:
  981. return False
  982. return table_patterns[clear_pattern_mode]
  983. def is_clear_pattern(file_path):
  984. """Check if a file path is a clear pattern file."""
  985. # Get all possible clear pattern files for all table types
  986. clear_patterns = []
  987. for table_type in ['dune_weaver', 'dune_weaver_mini', 'dune_weaver_pro']:
  988. clear_patterns.extend([
  989. f'./patterns/clear_from_out{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr',
  990. f'./patterns/clear_from_in{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr',
  991. f'./patterns/clear_sideway{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr'
  992. ])
  993. # Normalize paths for comparison
  994. normalized_path = os.path.normpath(file_path)
  995. normalized_clear_patterns = [os.path.normpath(p) for p in clear_patterns]
  996. # Check if the file path matches any clear pattern path
  997. return normalized_path in normalized_clear_patterns
  998. async def _execute_pattern_internal(file_path):
  999. """Internal function to execute a pattern file. Must be called with lock already held.
  1000. Args:
  1001. file_path: Path to the .thr file to execute
  1002. Returns:
  1003. True if pattern completed successfully, False if stopped/skipped
  1004. """
  1005. # Run file parsing in thread to avoid blocking the event loop
  1006. coordinates = await asyncio.to_thread(parse_theta_rho_file, file_path)
  1007. total_coordinates = len(coordinates)
  1008. if total_coordinates < 2:
  1009. logger.warning("Not enough coordinates for interpolation")
  1010. return False
  1011. # Normalize theta values to avoid unnecessary revolutions at pattern start.
  1012. # Many community patterns have theta starting at high values (e.g., 498 rad ≈ 79 revolutions).
  1013. # Some patterns also start with two "0 0" origin points before jumping to a large theta.
  1014. # Detect this preamble and use the third coordinate as the reference instead.
  1015. ref_theta = coordinates[0][0]
  1016. if (len(coordinates) >= 3
  1017. and abs(coordinates[0][0]) < 1e-9 and abs(coordinates[0][1]) < 1e-9
  1018. and abs(coordinates[1][0]) < 1e-9 and abs(coordinates[1][1]) < 1e-9):
  1019. ref_theta = coordinates[2][0]
  1020. theta_offset = ref_theta - (ref_theta % (2 * pi))
  1021. if abs(theta_offset) > 1e-9:
  1022. coordinates = [(theta - theta_offset, rho) for theta, rho in coordinates]
  1023. logger.info(f"Normalized pattern theta by {theta_offset:.2f} rad ({theta_offset / (2 * pi):.1f} revolutions)")
  1024. # Cache coordinates in state for frontend preview (avoids re-parsing large files)
  1025. state._current_coordinates = coordinates
  1026. # Pre-calculate rho-based weights for more accurate time estimation
  1027. # Moves near center (low rho) are slower than perimeter moves due to
  1028. # polar geometry - less linear distance per theta change at low rho
  1029. def calc_move_weight(rho):
  1030. # Weight inversely proportional to rho, with floor to avoid extreme values
  1031. # At rho=0: weight≈6.7, at rho=0.5: weight≈1.5, at rho=1.0: weight≈0.87
  1032. return 1.0 / (rho + 0.15)
  1033. coord_weights = [calc_move_weight(rho) for _, rho in coordinates]
  1034. total_weight = sum(coord_weights)
  1035. # Determine if this is a clearing pattern
  1036. is_clear_file = is_clear_pattern(file_path)
  1037. if is_clear_file:
  1038. initial_speed = state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  1039. logger.info(f"Running clearing pattern at initial speed {initial_speed}")
  1040. else:
  1041. logger.info(f"Running normal pattern at initial speed {state.speed}")
  1042. state.execution_progress = (0, total_coordinates, None, 0)
  1043. # stop actions without resetting the playlist, and don't wait for lock (we already have it)
  1044. # Preserve is_clearing flag since stop_actions resets it
  1045. was_clearing = state.is_clearing
  1046. await stop_actions(clear_playlist=False, wait_for_lock=False)
  1047. state.is_clearing = was_clearing
  1048. state.current_playing_file = file_path
  1049. state.stop_requested = False
  1050. # Reset LED idle timeout activity time when pattern starts
  1051. import time as time_module
  1052. state.dw_led_last_activity_time = time_module.time()
  1053. logger.info(f"Starting pattern execution: {file_path}")
  1054. logger.info(f"t: {state.current_theta}, r: {state.current_rho}")
  1055. await reset_theta()
  1056. start_time = time.time()
  1057. total_pause_time = 0 # Track total time spent paused (manual + scheduled)
  1058. completed_weight = 0.0 # Track rho-weighted progress
  1059. smoothed_rate = None # For exponential smoothing of time-per-unit-weight rate
  1060. # For WLED: always trigger (uses hardcoded preset 2)
  1061. # For DW_LED: only trigger if effect is configured
  1062. if state.led_controller and state.led_automation_enabled and (state.led_provider == "wled" or state.dw_led_playing_effect):
  1063. logger.info(f"Setting LED to playing effect: {state.dw_led_playing_effect}")
  1064. await state.led_controller.effect_playing_async(state.dw_led_playing_effect)
  1065. # Cancel idle timeout when playing starts
  1066. idle_timeout_manager.cancel_timeout()
  1067. with tqdm(
  1068. total=total_coordinates,
  1069. unit="coords",
  1070. desc=f"Executing Pattern {file_path}",
  1071. dynamic_ncols=True,
  1072. disable=False,
  1073. mininterval=1.0
  1074. ) as pbar:
  1075. for i, coordinate in enumerate(coordinates):
  1076. theta, rho = coordinate
  1077. if state.stop_requested:
  1078. logger.info("Execution stopped by user")
  1079. await start_idle_led_timeout()
  1080. break
  1081. if state.skip_requested:
  1082. logger.info("Skipping pattern...")
  1083. await connection_manager.check_idle_async()
  1084. await start_idle_led_timeout()
  1085. break
  1086. # Wait for resume if paused (manual or scheduled)
  1087. manual_pause = state.pause_requested
  1088. # Only check scheduled pause during pattern if "finish pattern first" is NOT enabled
  1089. scheduled_pause = is_in_scheduled_pause_period() if not state.scheduled_pause_finish_pattern else False
  1090. if manual_pause or scheduled_pause:
  1091. pause_start = time.time() # Track when pause started
  1092. if manual_pause and scheduled_pause:
  1093. logger.info("Execution paused (manual + scheduled pause active)...")
  1094. elif manual_pause:
  1095. logger.info("Execution paused (manual)...")
  1096. else:
  1097. logger.info("Execution paused (scheduled pause period)...")
  1098. # Turn off LED controller if scheduled pause and control_wled is enabled
  1099. if state.scheduled_pause_control_wled and state.led_controller:
  1100. logger.info("Turning off LED lights during Still Sands period")
  1101. await state.led_controller.set_power_async(0)
  1102. # Show idle effect for manual pause or scheduled pause without LED control
  1103. # (skip Still Sands check since we handle it above with local scheduled_pause variable)
  1104. if not (scheduled_pause and state.scheduled_pause_control_wled):
  1105. await start_idle_led_timeout(check_still_sands=False)
  1106. # Remember if we turned off LED controller for scheduled pause
  1107. wled_was_off_for_scheduled = scheduled_pause and state.scheduled_pause_control_wled and not manual_pause
  1108. # Wait until both manual pause is released AND we're outside scheduled pause period
  1109. # Also check for stop/skip requests to allow immediate interruption
  1110. interrupted = False
  1111. while state.pause_requested or is_in_scheduled_pause_period():
  1112. # Check for stop/skip first
  1113. if state.stop_requested:
  1114. logger.info("Stop requested during pause, exiting")
  1115. interrupted = True
  1116. break
  1117. if state.skip_requested:
  1118. logger.info("Skip requested during pause, skipping pattern")
  1119. interrupted = True
  1120. break
  1121. if state.pause_requested:
  1122. # For manual pause, wait on multiple events for immediate response
  1123. # Wake on: resume, stop, skip, or timeout (for flag polling fallback)
  1124. pause_event = get_pause_event()
  1125. stop_event = state.get_stop_event()
  1126. skip_event = state.get_skip_event()
  1127. wait_tasks = [asyncio.create_task(pause_event.wait(), name='pause')]
  1128. if stop_event:
  1129. wait_tasks.append(asyncio.create_task(stop_event.wait(), name='stop'))
  1130. if skip_event:
  1131. wait_tasks.append(asyncio.create_task(skip_event.wait(), name='skip'))
  1132. # Add timeout to ensure we periodically check flags even if events aren't set
  1133. # This handles the case where stop is called from sync context (no event loop)
  1134. timeout_task = asyncio.create_task(asyncio.sleep(1.0), name='timeout')
  1135. wait_tasks.append(timeout_task)
  1136. try:
  1137. done, pending = await asyncio.wait(
  1138. wait_tasks, return_when=asyncio.FIRST_COMPLETED
  1139. )
  1140. finally:
  1141. for task in pending:
  1142. task.cancel()
  1143. for task in pending:
  1144. try:
  1145. await task
  1146. except asyncio.CancelledError:
  1147. pass
  1148. else:
  1149. # For scheduled pause, use wait_for_interrupt for instant response
  1150. result = await state.wait_for_interrupt(timeout=1.0)
  1151. if result in ('stopped', 'skipped'):
  1152. interrupted = True
  1153. break
  1154. total_pause_time += time.time() - pause_start # Add pause duration
  1155. if interrupted:
  1156. # Exit the coordinate loop if we were interrupted
  1157. break
  1158. logger.info("Execution resumed...")
  1159. if state.led_controller:
  1160. # Always power LEDs back on if they were turned off for scheduled pause,
  1161. # regardless of whether a playing effect is configured
  1162. if wled_was_off_for_scheduled and state.led_automation_enabled:
  1163. logger.info("Turning LED lights back on as Still Sands period ended")
  1164. await state.led_controller.set_power_async(1)
  1165. # CRITICAL: Give LED controller time to fully power on before sending more commands
  1166. # Without this delay, rapid-fire requests can crash controllers on resource-constrained Pis
  1167. await asyncio.sleep(0.5)
  1168. # Apply playing effect if configured
  1169. # For WLED: always trigger (uses hardcoded preset 2)
  1170. # For DW_LED: only trigger if effect is configured
  1171. should_trigger_led = state.led_automation_enabled and (state.led_provider == "wled" or state.dw_led_playing_effect)
  1172. if should_trigger_led:
  1173. await state.led_controller.effect_playing_async(state.dw_led_playing_effect)
  1174. # Cancel idle timeout when resuming from pause
  1175. idle_timeout_manager.cancel_timeout()
  1176. # Dynamically determine the speed for each movement
  1177. # Use clear_pattern_speed if it's set and this is a clear file, otherwise use state.speed
  1178. if is_clear_file and state.clear_pattern_speed is not None:
  1179. current_speed = state.clear_pattern_speed
  1180. else:
  1181. current_speed = state.speed
  1182. await move_polar(theta, rho, current_speed)
  1183. # Update progress for all coordinates including the first one
  1184. pbar.update(1)
  1185. elapsed_time = time.time() - start_time
  1186. coords_done = i + 1
  1187. # Track rho-weighted progress for accurate time estimation
  1188. completed_weight += coord_weights[i]
  1189. remaining_weight = total_weight - completed_weight
  1190. # Calculate actual execution time (excluding pauses)
  1191. active_time = elapsed_time - total_pause_time
  1192. # Need minimum samples for stable estimate (at least 100 coords and 10 seconds)
  1193. if coords_done >= 100 and active_time > 10:
  1194. # Rate is time per unit weight (accounts for slower moves near center)
  1195. current_rate = active_time / completed_weight
  1196. # Smooth the RATE for stability
  1197. if smoothed_rate is not None:
  1198. alpha = 0.02 # Very smooth - 2% new, 98% old
  1199. smoothed_rate = alpha * current_rate + (1 - alpha) * smoothed_rate
  1200. else:
  1201. smoothed_rate = current_rate
  1202. # Remaining time based on weighted remaining work
  1203. estimated_remaining_time = smoothed_rate * remaining_weight
  1204. else:
  1205. estimated_remaining_time = None
  1206. state.execution_progress = (coords_done, total_coordinates, estimated_remaining_time, elapsed_time)
  1207. # Add a small delay to allow other async operations
  1208. await asyncio.sleep(0.001)
  1209. # Update progress one last time to show 100%
  1210. elapsed_time = time.time() - start_time
  1211. actual_execution_time = elapsed_time - total_pause_time
  1212. state.execution_progress = (total_coordinates, total_coordinates, 0, elapsed_time)
  1213. # Give WebSocket a chance to send the final update
  1214. await asyncio.sleep(0.1)
  1215. # Log execution time (only for completed patterns, not stopped/skipped)
  1216. was_completed = not state.stop_requested and not state.skip_requested
  1217. pattern_name = os.path.basename(file_path)
  1218. effective_speed = state.clear_pattern_speed if (is_clear_file and state.clear_pattern_speed is not None) else state.speed
  1219. log_execution_time(
  1220. pattern_name=pattern_name,
  1221. table_type=state.table_type,
  1222. speed=effective_speed,
  1223. actual_time=actual_execution_time,
  1224. total_coordinates=total_coordinates,
  1225. was_completed=was_completed
  1226. )
  1227. if not state.conn:
  1228. logger.error("Device is not connected. Stopping pattern execution.")
  1229. return False
  1230. await connection_manager.check_idle_async()
  1231. # Set LED back to idle when pattern completes normally (not stopped early)
  1232. # This also handles Still Sands: turns off LEDs if in scheduled pause period with LED control
  1233. # Skip during clear pattern - the main pattern starts immediately after, so triggering
  1234. # idle LED here would cause a brief flicker (idle effect → playing effect in ~0.3s)
  1235. if not state.stop_requested and not state.is_clearing:
  1236. await start_idle_led_timeout()
  1237. return was_completed
  1238. async def run_theta_rho_file(file_path, is_playlist=False, clear_pattern=None, cache_data=None):
  1239. """Run a theta-rho file with optional pre-execution clear pattern.
  1240. Args:
  1241. file_path: Path to the main .thr file to execute
  1242. is_playlist: True if running as part of a playlist
  1243. clear_pattern: Clear pattern mode ('adaptive', 'clear_from_in', 'clear_from_out', 'none', or None)
  1244. cache_data: Pre-loaded metadata cache for adaptive clear pattern selection
  1245. """
  1246. lock = get_pattern_lock()
  1247. if lock.locked():
  1248. logger.warning("Another pattern is already running. Cannot start a new one.")
  1249. return
  1250. async with lock: # This ensures only one pattern can run at a time
  1251. # Clear any stale pause state from previous playlist
  1252. state.pause_time_remaining = 0
  1253. state.original_pause_time = None
  1254. # Start progress update task only if not part of a playlist
  1255. global progress_update_task
  1256. if not is_playlist and not progress_update_task:
  1257. progress_update_task = asyncio.create_task(broadcast_progress())
  1258. # Run clear pattern first if specified
  1259. if clear_pattern and clear_pattern != 'none':
  1260. clear_file_path = get_clear_pattern_file(clear_pattern, file_path, cache_data)
  1261. if clear_file_path:
  1262. logger.info(f"Running pre-execution clear pattern: {clear_file_path}")
  1263. state.is_clearing = True
  1264. await _execute_pattern_internal(clear_file_path)
  1265. state.is_clearing = False
  1266. # Reset skip flag after clear pattern (if user skipped clear, continue to main)
  1267. state.skip_requested = False
  1268. # Check if stopped during clear pattern
  1269. if state.stop_requested:
  1270. logger.info("Execution stopped during clear pattern")
  1271. if not is_playlist:
  1272. state.current_playing_file = None
  1273. state.execution_progress = None
  1274. return
  1275. # Run the main pattern
  1276. await _execute_pattern_internal(file_path)
  1277. # Only clear state if not part of a playlist
  1278. if not is_playlist:
  1279. state.current_playing_file = None
  1280. state.execution_progress = None
  1281. logger.info("Pattern execution completed and state cleared")
  1282. # Only cancel progress update task if not part of a playlist
  1283. if progress_update_task:
  1284. progress_update_task.cancel()
  1285. try:
  1286. await progress_update_task
  1287. except asyncio.CancelledError:
  1288. pass
  1289. progress_update_task = None
  1290. else:
  1291. logger.info("Pattern execution completed, maintaining state for playlist")
  1292. async def run_theta_rho_files(file_paths, pause_time=0, clear_pattern=None, run_mode="single", shuffle=False):
  1293. """Run multiple .thr files in sequence with options.
  1294. The playlist now stores only main patterns. Clear patterns are executed dynamically
  1295. before each main pattern based on the clear_pattern option.
  1296. """
  1297. state.stop_requested = False
  1298. # Reset LED idle timeout activity time when playlist starts
  1299. import time as time_module
  1300. state.dw_led_last_activity_time = time_module.time()
  1301. # Set initial playlist state only if not already set by caller (playlist_manager).
  1302. # This ensures backward compatibility when this function is called directly.
  1303. if state.playlist_mode is None:
  1304. state.playlist_mode = run_mode
  1305. if state.current_playlist_index is None:
  1306. state.current_playlist_index = 0
  1307. # Start progress update task for the playlist
  1308. global progress_update_task
  1309. if not progress_update_task:
  1310. progress_update_task = asyncio.create_task(broadcast_progress())
  1311. # Shuffle main patterns if requested (before starting)
  1312. if shuffle:
  1313. random.shuffle(file_paths)
  1314. logger.info("Playlist shuffled")
  1315. # Store patterns in state only if not already set by caller.
  1316. # The caller (playlist_manager.run_playlist) sets this before creating the task.
  1317. if state.current_playlist is None:
  1318. state.current_playlist = file_paths
  1319. try:
  1320. while True:
  1321. # Load metadata cache once per playlist iteration (for adaptive clear patterns)
  1322. cache_data = None
  1323. if clear_pattern and clear_pattern in ['adaptive', 'clear_from_in', 'clear_from_out']:
  1324. from modules.core import cache_manager
  1325. cache_data = await asyncio.to_thread(cache_manager.load_metadata_cache)
  1326. logger.info(f"Loaded metadata cache for {len(cache_data.get('data', {}))} patterns")
  1327. # Reset pattern counter at the start of the playlist
  1328. state.patterns_since_last_home = 0
  1329. # Execute main patterns using index-based access
  1330. # This allows the playlist to be reordered during execution
  1331. idx = 0
  1332. while state.current_playlist and idx < len(state.current_playlist):
  1333. state.current_playlist_index = idx
  1334. if state.stop_requested or not state.current_playlist:
  1335. logger.info("Execution stopped")
  1336. return
  1337. # Get the pattern at the current index (may have changed due to reordering)
  1338. file_path = state.current_playlist[idx]
  1339. logger.info(f"Running pattern {idx + 1}/{len(state.current_playlist)}: {file_path}")
  1340. # Clear pause state when starting a new pattern (prevents stale "waiting" UI)
  1341. state.pause_time_remaining = 0
  1342. state.original_pause_time = None
  1343. # Execute the pattern with optional clear pattern
  1344. await run_theta_rho_file(
  1345. file_path,
  1346. is_playlist=True,
  1347. clear_pattern=clear_pattern,
  1348. cache_data=cache_data
  1349. )
  1350. # Increment pattern counter (auto-home check happens after pause time)
  1351. state.patterns_since_last_home += 1
  1352. logger.debug(f"Patterns since last home: {state.patterns_since_last_home}")
  1353. # Check for scheduled pause after pattern completes (when "finish pattern first" is enabled)
  1354. if state.scheduled_pause_finish_pattern and is_in_scheduled_pause_period() and not state.stop_requested and not state.skip_requested:
  1355. logger.info("Pattern completed. Entering Still Sands period (finish pattern first mode)...")
  1356. wled_was_off_for_scheduled = False
  1357. if state.scheduled_pause_control_wled and state.led_controller:
  1358. logger.info("Turning off LED lights during Still Sands period")
  1359. await state.led_controller.set_power_async(0)
  1360. wled_was_off_for_scheduled = True
  1361. else:
  1362. # Show idle effect (WLED control not enabled)
  1363. await start_idle_led_timeout(check_still_sands=False)
  1364. # Wait for scheduled pause to end, but allow stop/skip to interrupt
  1365. result = await wait_with_interrupt(
  1366. is_in_scheduled_pause_period,
  1367. check_stop=True,
  1368. check_skip=True,
  1369. )
  1370. if result == 'completed':
  1371. logger.info("Still Sands period ended. Resuming playlist...")
  1372. if state.led_controller:
  1373. # Always power LEDs back on if they were turned off for scheduled pause,
  1374. # regardless of whether a playing effect is configured
  1375. if wled_was_off_for_scheduled and state.led_automation_enabled:
  1376. logger.info("Turning LED lights back on as Still Sands period ended")
  1377. await state.led_controller.set_power_async(1)
  1378. await asyncio.sleep(0.5)
  1379. # Apply playing effect if configured
  1380. # For WLED: always trigger (uses hardcoded preset 2)
  1381. # For DW_LED: only trigger if effect is configured
  1382. should_trigger_led = state.led_automation_enabled and (state.led_provider == "wled" or state.dw_led_playing_effect)
  1383. if should_trigger_led:
  1384. await state.led_controller.effect_playing_async(state.dw_led_playing_effect)
  1385. idle_timeout_manager.cancel_timeout()
  1386. # Handle pause between patterns
  1387. 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:
  1388. logger.info(f"Pausing for {pause_time} seconds")
  1389. # Clear current_playing_file to report "idle" state to MQTT/HA during pause
  1390. # This will be set again when the next pattern starts
  1391. state.current_playing_file = None
  1392. # Trigger idle LED state during pause between patterns
  1393. await start_idle_led_timeout(check_still_sands=True)
  1394. state.original_pause_time = pause_time
  1395. pause_start = time.time()
  1396. # Track Still Sands state for edge detection during long pauses
  1397. was_in_still_sands = is_in_scheduled_pause_period() and state.scheduled_pause_control_wled
  1398. while time.time() - pause_start < pause_time:
  1399. state.pause_time_remaining = pause_start + pause_time - time.time()
  1400. if state.skip_requested or state.stop_requested:
  1401. if state.stop_requested:
  1402. logger.info("Pause interrupted by stop request")
  1403. else:
  1404. logger.info("Pause interrupted by skip request")
  1405. break
  1406. # Monitor Still Sands transitions during pause
  1407. in_still_sands = is_in_scheduled_pause_period() and state.scheduled_pause_control_wled
  1408. if in_still_sands and not was_in_still_sands:
  1409. # Entering Still Sands period — turn off LEDs
  1410. logger.info("Still Sands period started during pause, turning off LEDs")
  1411. if state.led_controller:
  1412. await state.led_controller.set_power_async(0)
  1413. elif not in_still_sands and was_in_still_sands:
  1414. # Leaving Still Sands period — restore idle effect
  1415. logger.info("Still Sands period ended during pause, restoring idle LED effect")
  1416. await start_idle_led_timeout(check_still_sands=False)
  1417. was_in_still_sands = in_still_sands
  1418. await asyncio.sleep(1)
  1419. # Clear both pause state vars immediately (so UI updates right away)
  1420. state.pause_time_remaining = 0
  1421. state.original_pause_time = None
  1422. # Auto-home after pause time, before next clear pattern starts
  1423. # Only home if there's a next pattern and we haven't been stopped
  1424. if (state.auto_home_enabled and
  1425. state.patterns_since_last_home >= state.auto_home_after_patterns and
  1426. state.current_playlist and idx < len(state.current_playlist) - 1 and
  1427. not state.stop_requested):
  1428. logger.info(f"Auto-homing triggered after {state.patterns_since_last_home} patterns (before next clear pattern)")
  1429. try:
  1430. success = await asyncio.to_thread(connection_manager.home)
  1431. if success:
  1432. logger.info("Auto-homing completed successfully")
  1433. state.patterns_since_last_home = 0
  1434. else:
  1435. logger.warning("Auto-homing failed, continuing with playlist")
  1436. except Exception as e:
  1437. logger.error(f"Error during auto-homing: {e}")
  1438. state.skip_requested = False
  1439. idx += 1
  1440. if run_mode == "indefinite":
  1441. logger.info("Playlist completed. Restarting as per 'indefinite' run mode")
  1442. if pause_time > 0:
  1443. # Clear current_playing_file to report "idle" state to MQTT/HA during pause
  1444. state.current_playing_file = None
  1445. # Trigger idle LED state during pause between playlist cycles
  1446. await start_idle_led_timeout(check_still_sands=True)
  1447. state.original_pause_time = pause_time
  1448. pause_start = time.time()
  1449. # Track Still Sands state for edge detection during long pauses
  1450. was_in_still_sands = is_in_scheduled_pause_period() and state.scheduled_pause_control_wled
  1451. while time.time() - pause_start < pause_time:
  1452. state.pause_time_remaining = pause_start + pause_time - time.time()
  1453. if state.skip_requested or state.stop_requested:
  1454. if state.stop_requested:
  1455. logger.info("Pause interrupted by stop request")
  1456. else:
  1457. logger.info("Pause interrupted by skip request")
  1458. break
  1459. # Monitor Still Sands transitions during pause
  1460. in_still_sands = is_in_scheduled_pause_period() and state.scheduled_pause_control_wled
  1461. if in_still_sands and not was_in_still_sands:
  1462. # Entering Still Sands period — turn off LEDs
  1463. logger.info("Still Sands period started during pause, turning off LEDs")
  1464. if state.led_controller:
  1465. await state.led_controller.set_power_async(0)
  1466. elif not in_still_sands and was_in_still_sands:
  1467. # Leaving Still Sands period — restore idle effect
  1468. logger.info("Still Sands period ended during pause, restoring idle LED effect")
  1469. await start_idle_led_timeout(check_still_sands=False)
  1470. was_in_still_sands = in_still_sands
  1471. await asyncio.sleep(1)
  1472. # Clear both pause state vars immediately (so UI updates right away)
  1473. state.pause_time_remaining = 0
  1474. state.original_pause_time = None
  1475. continue
  1476. else:
  1477. logger.info("Playlist completed")
  1478. break
  1479. except asyncio.CancelledError:
  1480. # Task was cancelled externally (e.g., by TestClient cleanup, or explicit cancellation).
  1481. # Do NOT clear playlist state - preserve what the caller set.
  1482. logger.info("Playlist task was cancelled externally, preserving state")
  1483. if progress_update_task:
  1484. progress_update_task.cancel()
  1485. try:
  1486. await progress_update_task
  1487. except asyncio.CancelledError:
  1488. pass
  1489. progress_update_task = None
  1490. raise # Re-raise to signal cancellation
  1491. finally:
  1492. if progress_update_task:
  1493. progress_update_task.cancel()
  1494. try:
  1495. await progress_update_task
  1496. except asyncio.CancelledError:
  1497. pass
  1498. progress_update_task = None
  1499. # Check if we're exiting due to CancelledError - if so, don't clear state.
  1500. # State should only be cleared when:
  1501. # 1. Task completed normally (all patterns executed)
  1502. # 2. Task was stopped by user request (stop_requested)
  1503. # NOT when task was cancelled externally (CancelledError)
  1504. import sys
  1505. exc_type = sys.exc_info()[0]
  1506. if exc_type is asyncio.CancelledError:
  1507. logger.info("Task exiting due to cancellation, state preserved for caller")
  1508. else:
  1509. # Normal completion or user-requested stop - clear state
  1510. state.current_playing_file = None
  1511. state.execution_progress = None
  1512. state.current_playlist = None
  1513. state.current_playlist_index = None
  1514. state.playlist_mode = None
  1515. state.pause_time_remaining = 0
  1516. # Persist cleared state so server restart won't load stale playlist
  1517. state.save()
  1518. await start_idle_led_timeout()
  1519. logger.info("All requested patterns completed (or stopped) and state cleared")
  1520. async def stop_actions(clear_playlist = True, wait_for_lock = True):
  1521. """Stop all current actions and wait for pattern to fully release.
  1522. Args:
  1523. clear_playlist: Whether to clear playlist state
  1524. wait_for_lock: Whether to wait for pattern_lock to be released. Set to False when
  1525. called from within pattern execution to avoid deadlock.
  1526. Returns:
  1527. True if stopped cleanly, False if timed out waiting for pattern lock
  1528. """
  1529. timed_out = False
  1530. try:
  1531. with state.pause_condition:
  1532. state.pause_requested = False
  1533. state.stop_requested = True
  1534. state.is_clearing = False
  1535. # Always clear pause time between patterns on stop
  1536. state.pause_time_remaining = 0
  1537. state.original_pause_time = None
  1538. if clear_playlist:
  1539. # Clear playlist state
  1540. state.current_playlist = None
  1541. state.current_playlist_index = None
  1542. state.playlist_mode = None
  1543. # Cancel progress update task if we're clearing the playlist
  1544. global progress_update_task
  1545. if progress_update_task and not progress_update_task.done():
  1546. progress_update_task.cancel()
  1547. # Cancel the playlist task itself (late import to avoid circular dependency)
  1548. from modules.core import playlist_manager
  1549. await playlist_manager.cancel_current_playlist()
  1550. state.pause_condition.notify_all()
  1551. # Also set the pause event to wake up any paused patterns
  1552. get_pause_event().set()
  1553. # Send stop command to motion thread to clear its queue
  1554. if motion_controller.running:
  1555. motion_controller.command_queue.put(MotionCommand('stop'))
  1556. # Wait for the pattern lock to be released before continuing
  1557. # This ensures that when stop_actions completes, the pattern has fully stopped
  1558. # Skip this if called from within pattern execution to avoid deadlock
  1559. lock = get_pattern_lock()
  1560. if wait_for_lock and lock.locked():
  1561. logger.info("Waiting for pattern to fully stop...")
  1562. # Use a timeout to prevent hanging forever
  1563. # Use wait_for for Python 3.9 compatibility (asyncio.timeout is 3.11+)
  1564. try:
  1565. async def acquire_stop_lock():
  1566. async with lock:
  1567. logger.info("Pattern lock acquired - pattern has fully stopped")
  1568. await asyncio.wait_for(acquire_stop_lock(), timeout=10.0)
  1569. except asyncio.TimeoutError:
  1570. logger.warning("Timeout waiting for pattern to stop - forcing cleanup")
  1571. timed_out = True
  1572. # Force cleanup of state even if pattern didn't release lock gracefully
  1573. state.current_playing_file = None
  1574. state.execution_progress = None
  1575. state.is_running = False
  1576. # Clear current playing file only when clearing the entire playlist.
  1577. # When clear_playlist=False (called from within pattern execution), the caller
  1578. # will set current_playing_file to the new pattern immediately after.
  1579. if clear_playlist:
  1580. state.current_playing_file = None
  1581. state.execution_progress = None
  1582. # Clear stop_requested now that the pattern has stopped - this allows
  1583. # check_idle_async to work (it exits early if stop_requested is True)
  1584. state.stop_requested = False
  1585. # Wait for hardware to reach idle state before returning
  1586. # This ensures the machine has physically stopped moving
  1587. if not timed_out:
  1588. idle = await connection_manager.check_idle_async(timeout=30.0)
  1589. if not idle:
  1590. logger.warning("Machine did not reach idle after stop")
  1591. # Call async function directly since we're in async context
  1592. await connection_manager.update_machine_position()
  1593. return not timed_out
  1594. except Exception as e:
  1595. logger.error(f"Error during stop_actions: {e}")
  1596. # Force cleanup state on error
  1597. state.current_playing_file = None
  1598. state.execution_progress = None
  1599. state.is_running = False
  1600. # Ensure we still update machine position even if there's an error
  1601. try:
  1602. await connection_manager.update_machine_position()
  1603. except Exception as update_err:
  1604. logger.error(f"Error updating machine position on error: {update_err}")
  1605. return False
  1606. async def move_polar(theta, rho, speed=None):
  1607. """
  1608. Queue a motion command to be executed in the dedicated motion control thread.
  1609. This makes motion control non-blocking for API endpoints.
  1610. Args:
  1611. theta (float): Target theta coordinate
  1612. rho (float): Target rho coordinate
  1613. speed (int, optional): Speed override. If None, uses state.speed
  1614. """
  1615. # Note: stop_requested is cleared once at pattern start (execute_theta_rho_file line 890)
  1616. # Don't clear it here on every coordinate - causes performance issues with event system
  1617. # Ensure motion control thread is running
  1618. if not motion_controller.running:
  1619. motion_controller.start()
  1620. # Create future for async/await pattern
  1621. loop = asyncio.get_event_loop()
  1622. future = loop.create_future()
  1623. # Create and queue motion command
  1624. command = MotionCommand(
  1625. command_type='move',
  1626. theta=theta,
  1627. rho=rho,
  1628. speed=speed,
  1629. future=future
  1630. )
  1631. motion_controller.command_queue.put(command)
  1632. logger.debug(f"Queued motion command: theta={theta}, rho={rho}, speed={speed}")
  1633. # Wait for command completion
  1634. await future
  1635. def pause_execution():
  1636. """Pause pattern execution using asyncio Event."""
  1637. logger.info("Pausing pattern execution")
  1638. state.pause_requested = True
  1639. get_pause_event().clear() # Clear the event to pause execution
  1640. return True
  1641. def resume_execution():
  1642. """Resume pattern execution using asyncio Event."""
  1643. logger.info("Resuming pattern execution")
  1644. state.pause_requested = False
  1645. get_pause_event().set() # Set the event to resume execution
  1646. return True
  1647. async def reset_theta():
  1648. """
  1649. Reset theta to [0, 2π) range and optionally hard reset machine position using $Bye.
  1650. When state.hard_reset_theta is True:
  1651. - $Bye sends a soft reset to FluidNC which resets the controller and clears
  1652. all position counters to 0. This is more reliable than G92 which only sets
  1653. a work coordinate offset without changing the actual machine position (MPos).
  1654. - We wait for machine to be idle before sending $Bye to avoid error:25
  1655. When state.hard_reset_theta is False (default):
  1656. - Only normalizes theta to [0, 2π) range without affecting machine position
  1657. - Faster and doesn't interrupt machine state
  1658. """
  1659. logger.info('Resetting Theta')
  1660. # Always normalize theta to [0, 2π) range
  1661. state.current_theta = state.current_theta % (2 * pi)
  1662. logger.info(f'Theta normalized to {state.current_theta:.4f} radians')
  1663. # Only perform hard reset if enabled
  1664. if state.hard_reset_theta:
  1665. logger.info('Hard reset enabled - performing machine soft reset')
  1666. # Wait for machine to be idle before reset to prevent error:25
  1667. if state.conn and state.conn.is_connected():
  1668. logger.info("Waiting for machine to be idle before reset...")
  1669. idle = await connection_manager.check_idle_async(timeout=30)
  1670. if not idle:
  1671. logger.warning("Machine not idle after 30s, proceeding with reset anyway")
  1672. # Hard reset machine position using $Bye via connection_manager
  1673. success = await connection_manager.perform_soft_reset()
  1674. if not success:
  1675. logger.error("Soft reset failed - theta reset may be unreliable")
  1676. else:
  1677. logger.info('Hard reset disabled - skipping machine soft reset')
  1678. def set_speed(new_speed):
  1679. state.speed = new_speed
  1680. logger.info(f'Set new state.speed {new_speed}')
  1681. def get_status():
  1682. """Get the current status of pattern execution."""
  1683. status = {
  1684. "current_file": state.current_playing_file,
  1685. "is_paused": state.pause_requested or is_in_scheduled_pause_period(),
  1686. "manual_pause": state.pause_requested,
  1687. "scheduled_pause": is_in_scheduled_pause_period(),
  1688. "is_running": bool(state.current_playing_file and not state.stop_requested),
  1689. "is_homing": state.is_homing,
  1690. "sensor_homing_failed": state.sensor_homing_failed,
  1691. "is_clearing": state.is_clearing,
  1692. "progress": None,
  1693. "playlist": None,
  1694. "speed": state.speed,
  1695. "pause_time_remaining": state.pause_time_remaining,
  1696. "original_pause_time": getattr(state, 'original_pause_time', None),
  1697. "connection_status": state.conn.is_connected() if state.conn else False,
  1698. "current_theta": state.current_theta,
  1699. "current_rho": state.current_rho,
  1700. "firmware_version": state.firmware_version,
  1701. "table_type": state.table_type_override or state.table_type
  1702. }
  1703. # Add playlist information if available
  1704. if state.current_playlist and state.current_playlist_index is not None:
  1705. # When a clear pattern is running, the "next" pattern is the current main pattern
  1706. # (since the clear pattern runs before the main pattern at current_playlist_index)
  1707. if state.is_clearing:
  1708. next_file = state.current_playlist[state.current_playlist_index]
  1709. else:
  1710. next_index = state.current_playlist_index + 1
  1711. next_file = state.current_playlist[next_index] if next_index < len(state.current_playlist) else None
  1712. status["playlist"] = {
  1713. "current_index": state.current_playlist_index,
  1714. "total_files": len(state.current_playlist),
  1715. "mode": state.playlist_mode,
  1716. "next_file": next_file,
  1717. "files": state.current_playlist,
  1718. "name": state.current_playlist_name
  1719. }
  1720. if state.execution_progress:
  1721. current, total, remaining_time, elapsed_time = state.execution_progress
  1722. status["progress"] = {
  1723. "current": current,
  1724. "total": total,
  1725. "remaining_time": remaining_time,
  1726. "elapsed_time": elapsed_time,
  1727. "percentage": (current / total * 100) if total > 0 else 0
  1728. }
  1729. # Add historical execution time if available for this pattern at current speed
  1730. if state.current_playing_file:
  1731. pattern_name = os.path.basename(state.current_playing_file)
  1732. historical_time = get_last_completed_execution_time(pattern_name, state.speed)
  1733. if historical_time:
  1734. status["progress"]["last_completed_time"] = historical_time
  1735. return status
  1736. async def broadcast_progress():
  1737. """Background task to broadcast progress updates."""
  1738. from main import broadcast_status_update
  1739. while True:
  1740. # Send status updates regardless of pattern_lock state
  1741. status = get_status()
  1742. # Use the existing broadcast function from main.py
  1743. await broadcast_status_update(status)
  1744. # Check if we should stop broadcasting
  1745. if not state.current_playlist:
  1746. # If no playlist, only stop if no pattern is being executed
  1747. if not get_pattern_lock().locked():
  1748. logger.info("No playlist or pattern running, stopping broadcast")
  1749. break
  1750. # Wait before next update
  1751. await asyncio.sleep(1)