1
0

pattern_manager.py 96 KB

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