pattern_manager.py 96 KB

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