pattern_manager.py 90 KB

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