pattern_manager.py 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594
  1. import os
  2. from zoneinfo import ZoneInfo
  3. import threading
  4. import time
  5. import random
  6. import logging
  7. from datetime import datetime, time as datetime_time
  8. from tqdm import tqdm
  9. from modules.connection import connection_manager
  10. from modules.core.state import state
  11. from math import pi, isnan, isinf
  12. import asyncio
  13. import json
  14. # Import for legacy support, but we'll use LED interface through state
  15. from modules.led.led_controller import effect_playing, effect_idle
  16. from modules.led.idle_timeout_manager import idle_timeout_manager
  17. import queue
  18. from dataclasses import dataclass
  19. from typing import Optional, Callable, Literal
  20. # Configure logging
  21. logger = logging.getLogger(__name__)
  22. # Global state
  23. THETA_RHO_DIR = './patterns'
  24. os.makedirs(THETA_RHO_DIR, exist_ok=True)
  25. # Execution time log file (JSON Lines format - one JSON object per line)
  26. EXECUTION_LOG_FILE = './execution_times.jsonl'
  27. async def wait_with_interrupt(
  28. condition_fn: Callable[[], bool],
  29. check_stop: bool = True,
  30. check_skip: bool = True,
  31. interval: float = 1.0,
  32. ) -> Literal['completed', 'stopped', 'skipped']:
  33. """
  34. Wait while condition_fn() returns True, with instant interrupt support.
  35. Uses asyncio.Event for instant response to stop/skip requests rather than
  36. polling at fixed intervals. This ensures users get immediate feedback when
  37. pressing stop or skip buttons.
  38. Args:
  39. condition_fn: Function that returns True while waiting should continue
  40. check_stop: Whether to respond to stop requests (default True)
  41. check_skip: Whether to respond to skip requests (default True)
  42. interval: How often to re-check condition_fn in seconds (default 1.0)
  43. Returns:
  44. 'completed' - condition_fn() returned False (normal completion)
  45. 'stopped' - stop was requested
  46. 'skipped' - skip was requested
  47. Example:
  48. result = await wait_with_interrupt(
  49. lambda: state.pause_requested or is_in_scheduled_pause_period()
  50. )
  51. if result == 'stopped':
  52. return # Exit pattern execution
  53. if result == 'skipped':
  54. break # Skip to next pattern
  55. """
  56. while condition_fn():
  57. result = await state.wait_for_interrupt(
  58. timeout=interval,
  59. check_stop=check_stop,
  60. check_skip=check_skip,
  61. )
  62. if result == 'stopped':
  63. return 'stopped'
  64. if result == 'skipped':
  65. return 'skipped'
  66. # 'timeout' means we should re-check condition_fn
  67. return 'completed'
  68. def log_execution_time(pattern_name: str, table_type: str, speed: int, actual_time: float,
  69. total_coordinates: int, was_completed: bool):
  70. """Log pattern execution time to JSON Lines file for analysis.
  71. Args:
  72. pattern_name: Name of the pattern file
  73. table_type: Type of table (e.g., 'dune_weaver', 'dune_weaver_mini')
  74. speed: Speed setting used (0-255)
  75. actual_time: Actual execution time in seconds (excluding pauses)
  76. total_coordinates: Total number of coordinates in the pattern
  77. was_completed: Whether the pattern completed normally (not stopped/skipped)
  78. """
  79. # Format time as HH:MM:SS
  80. hours, remainder = divmod(int(actual_time), 3600)
  81. minutes, seconds = divmod(remainder, 60)
  82. time_formatted = f"{hours:02d}:{minutes:02d}:{seconds:02d}"
  83. log_entry = {
  84. "timestamp": datetime.now().isoformat(),
  85. "pattern_name": pattern_name,
  86. "table_type": table_type or "unknown",
  87. "speed": speed,
  88. "actual_time_seconds": round(actual_time, 2),
  89. "actual_time_formatted": time_formatted,
  90. "total_coordinates": total_coordinates,
  91. "completed": was_completed
  92. }
  93. try:
  94. with open(EXECUTION_LOG_FILE, 'a') as f:
  95. f.write(json.dumps(log_entry) + '\n')
  96. logger.info(f"Execution time logged: {pattern_name} - {time_formatted} (speed: {speed}, table: {table_type})")
  97. except Exception as e:
  98. logger.error(f"Failed to log execution time: {e}")
  99. def get_last_completed_execution_time(pattern_name: str, speed: float) -> Optional[dict]:
  100. """Get the last completed execution time for a pattern at a specific speed.
  101. Args:
  102. pattern_name: Name of the pattern file (e.g., 'circle.thr')
  103. speed: Speed setting to match
  104. Returns:
  105. Dict with execution time info if found, None otherwise.
  106. Format: {"actual_time_seconds": float, "actual_time_formatted": str, "timestamp": str}
  107. """
  108. if not os.path.exists(EXECUTION_LOG_FILE):
  109. return None
  110. try:
  111. matching_entry = None
  112. with open(EXECUTION_LOG_FILE, 'r') as f:
  113. for line in f:
  114. line = line.strip()
  115. if not line:
  116. continue
  117. try:
  118. entry = json.loads(line)
  119. # Only consider fully completed patterns (100% finished)
  120. if (entry.get('completed', False) and
  121. entry.get('pattern_name') == pattern_name and
  122. entry.get('speed') == speed):
  123. # Keep the most recent match (last one in file)
  124. matching_entry = entry
  125. except json.JSONDecodeError:
  126. continue
  127. if matching_entry:
  128. return {
  129. "actual_time_seconds": matching_entry.get('actual_time_seconds'),
  130. "actual_time_formatted": matching_entry.get('actual_time_formatted'),
  131. "timestamp": matching_entry.get('timestamp')
  132. }
  133. return None
  134. except Exception as e:
  135. logger.error(f"Failed to read execution time log: {e}")
  136. return None
  137. def get_pattern_execution_history(pattern_name: str) -> Optional[dict]:
  138. """Get the most recent completed execution for a pattern (any speed).
  139. Args:
  140. pattern_name: Name of the pattern file (e.g., 'circle.thr')
  141. Returns:
  142. Dict with execution time info if found, None otherwise.
  143. Format: {"actual_time_seconds": float, "actual_time_formatted": str,
  144. "speed": int, "timestamp": str}
  145. """
  146. if not os.path.exists(EXECUTION_LOG_FILE):
  147. return None
  148. try:
  149. matching_entry = None
  150. with open(EXECUTION_LOG_FILE, 'r') as f:
  151. for line in f:
  152. line = line.strip()
  153. if not line:
  154. continue
  155. try:
  156. entry = json.loads(line)
  157. # Only consider fully completed patterns
  158. if (entry.get('completed', False) and
  159. entry.get('pattern_name') == pattern_name):
  160. # Keep the most recent match (last one in file)
  161. matching_entry = entry
  162. except json.JSONDecodeError:
  163. continue
  164. if matching_entry:
  165. return {
  166. "actual_time_seconds": matching_entry.get('actual_time_seconds'),
  167. "actual_time_formatted": matching_entry.get('actual_time_formatted'),
  168. "speed": matching_entry.get('speed'),
  169. "timestamp": matching_entry.get('timestamp')
  170. }
  171. return None
  172. except Exception as e:
  173. logger.error(f"Failed to read execution time log: {e}")
  174. return None
  175. # Asyncio primitives - initialized lazily to avoid event loop issues
  176. # These must be created in the context of the running event loop
  177. pause_event: Optional[asyncio.Event] = None
  178. pattern_lock: Optional[asyncio.Lock] = None
  179. progress_update_task = None
  180. def get_pause_event() -> asyncio.Event:
  181. """Get or create the pause event in the current event loop."""
  182. global pause_event
  183. if pause_event is None:
  184. pause_event = asyncio.Event()
  185. pause_event.set() # Initially not paused
  186. return pause_event
  187. def get_pattern_lock() -> asyncio.Lock:
  188. """Get or create the pattern lock in the current event loop."""
  189. global pattern_lock
  190. if pattern_lock is None:
  191. pattern_lock = asyncio.Lock()
  192. return pattern_lock
  193. # Cache timezone at module level - read once per session (cleared when user changes timezone)
  194. _cached_timezone = None
  195. _cached_zoneinfo = None
  196. def _get_timezone():
  197. """Get and cache the timezone for Still Sands. Uses user-selected timezone if set, otherwise system timezone."""
  198. global _cached_timezone, _cached_zoneinfo
  199. if _cached_timezone is not None:
  200. return _cached_zoneinfo
  201. user_tz = 'UTC' # Default fallback
  202. # First, check if user has selected a specific timezone in settings
  203. if state.scheduled_pause_timezone:
  204. user_tz = state.scheduled_pause_timezone
  205. logger.info(f"Still Sands using timezone: {user_tz} (user-selected)")
  206. else:
  207. # Fall back to system timezone detection
  208. try:
  209. if os.path.exists('/etc/host-timezone'):
  210. with open('/etc/host-timezone', 'r') as f:
  211. user_tz = f.read().strip()
  212. logger.info(f"Still Sands using timezone: {user_tz} (from host system)")
  213. # Fallback to /etc/timezone if host-timezone doesn't exist
  214. elif os.path.exists('/etc/timezone'):
  215. with open('/etc/timezone', 'r') as f:
  216. user_tz = f.read().strip()
  217. logger.info(f"Still Sands using timezone: {user_tz} (from container)")
  218. # Fallback to TZ environment variable
  219. elif os.environ.get('TZ'):
  220. user_tz = os.environ.get('TZ')
  221. logger.info(f"Still Sands using timezone: {user_tz} (from environment)")
  222. else:
  223. logger.info("Still Sands using timezone: UTC (system default)")
  224. except Exception as e:
  225. logger.debug(f"Could not read timezone: {e}")
  226. # Cache the timezone
  227. _cached_timezone = user_tz
  228. try:
  229. _cached_zoneinfo = ZoneInfo(user_tz)
  230. except Exception as e:
  231. logger.warning(f"Invalid timezone '{user_tz}', falling back to system time: {e}")
  232. _cached_zoneinfo = None
  233. return _cached_zoneinfo
  234. def is_in_scheduled_pause_period():
  235. """Check if current time falls within any scheduled pause period."""
  236. if not state.scheduled_pause_enabled or not state.scheduled_pause_time_slots:
  237. return False
  238. # Get cached timezone (user-selected or system default)
  239. tz_info = _get_timezone()
  240. try:
  241. # Get current time in user's timezone
  242. if tz_info:
  243. now = datetime.now(tz_info)
  244. else:
  245. now = datetime.now()
  246. except Exception as e:
  247. logger.warning(f"Error getting current time: {e}")
  248. now = datetime.now()
  249. current_time = now.time()
  250. current_weekday = now.strftime("%A").lower() # monday, tuesday, etc.
  251. for slot in state.scheduled_pause_time_slots:
  252. # Parse start and end times
  253. try:
  254. start_time = datetime_time.fromisoformat(slot['start_time'])
  255. end_time = datetime_time.fromisoformat(slot['end_time'])
  256. except (ValueError, KeyError):
  257. logger.warning(f"Invalid time format in scheduled pause slot: {slot}")
  258. continue
  259. # Check if this slot applies to today
  260. slot_applies_today = False
  261. days_setting = slot.get('days', 'daily')
  262. if days_setting == 'daily':
  263. slot_applies_today = True
  264. elif days_setting == 'weekdays':
  265. slot_applies_today = current_weekday in ['monday', 'tuesday', 'wednesday', 'thursday', 'friday']
  266. elif days_setting == 'weekends':
  267. slot_applies_today = current_weekday in ['saturday', 'sunday']
  268. elif days_setting == 'custom':
  269. custom_days = slot.get('custom_days', [])
  270. slot_applies_today = current_weekday in custom_days
  271. if not slot_applies_today:
  272. continue
  273. # Check if current time is within the pause period
  274. if start_time <= end_time:
  275. # Normal case: start and end are on the same day
  276. if start_time <= current_time <= end_time:
  277. return True
  278. else:
  279. # Time spans midnight: start is before midnight, end is after midnight
  280. if current_time >= start_time or current_time <= end_time:
  281. return True
  282. return False
  283. async def check_table_is_idle() -> bool:
  284. """
  285. Check if the table is currently idle by querying actual machine status.
  286. Returns True if idle, False if playing/moving.
  287. This checks the real machine state rather than relying on state variables,
  288. making it more reliable for detecting when table is truly idle.
  289. """
  290. # Use the connection_manager's is_machine_idle() function
  291. # Run it in a thread since it's a synchronous function
  292. return await asyncio.to_thread(connection_manager.is_machine_idle)
  293. def start_idle_led_timeout():
  294. """
  295. Start the idle LED timeout if enabled.
  296. Should be called whenever the idle effect is activated.
  297. """
  298. if not state.dw_led_idle_timeout_enabled:
  299. logger.debug("Idle LED timeout not enabled")
  300. return
  301. timeout_minutes = state.dw_led_idle_timeout_minutes
  302. if timeout_minutes <= 0:
  303. logger.debug("Idle LED timeout not configured (timeout <= 0)")
  304. return
  305. logger.debug(f"Starting idle LED timeout: {timeout_minutes} minutes")
  306. idle_timeout_manager.start_idle_timeout(
  307. timeout_minutes=timeout_minutes,
  308. state=state,
  309. check_idle_callback=check_table_is_idle
  310. )
  311. # Motion Control Thread Infrastructure
  312. @dataclass
  313. class MotionCommand:
  314. """Represents a motion command for the motion control thread."""
  315. command_type: str # 'move', 'stop', 'pause', 'resume', 'shutdown'
  316. theta: Optional[float] = None
  317. rho: Optional[float] = None
  318. speed: Optional[float] = None
  319. callback: Optional[Callable] = None
  320. future: Optional[asyncio.Future] = None
  321. class MotionControlThread:
  322. """Dedicated thread for hardware motion control operations."""
  323. def __init__(self):
  324. self.command_queue = queue.Queue()
  325. self.thread = None
  326. self.running = False
  327. self.paused = False
  328. def start(self):
  329. """Start the motion control thread with elevated priority."""
  330. if self.thread and self.thread.is_alive():
  331. return
  332. self.running = True
  333. self.thread = threading.Thread(target=self._motion_loop, daemon=True)
  334. self.thread.start()
  335. logger.info("Motion control thread started")
  336. def stop(self):
  337. """Stop the motion control thread."""
  338. if not self.running:
  339. return
  340. self.running = False
  341. # Send shutdown command
  342. self.command_queue.put(MotionCommand('shutdown'))
  343. if self.thread and self.thread.is_alive():
  344. self.thread.join(timeout=5.0)
  345. logger.info("Motion control thread stopped")
  346. def _motion_loop(self):
  347. """Main loop for the motion control thread."""
  348. # Setup realtime priority from within thread to avoid native_id race
  349. # Motion uses higher priority (60) than LED (40) for CNC reliability
  350. from modules.core import scheduling
  351. scheduling.setup_realtime_thread(priority=60)
  352. logger.info("Motion control thread loop started")
  353. while self.running:
  354. try:
  355. # Get command with timeout to allow periodic checks
  356. command = self.command_queue.get(timeout=1.0)
  357. if command.command_type == 'shutdown':
  358. break
  359. elif command.command_type == 'move':
  360. self._execute_move(command)
  361. elif command.command_type == 'pause':
  362. self.paused = True
  363. elif command.command_type == 'resume':
  364. self.paused = False
  365. elif command.command_type == 'stop':
  366. # Clear any pending commands
  367. while not self.command_queue.empty():
  368. try:
  369. self.command_queue.get_nowait()
  370. except queue.Empty:
  371. break
  372. self.command_queue.task_done()
  373. except queue.Empty:
  374. # Timeout - continue loop for shutdown check
  375. continue
  376. except Exception as e:
  377. logger.error(f"Error in motion control thread: {e}")
  378. logger.info("Motion control thread loop ended")
  379. def _execute_move(self, command: MotionCommand):
  380. """Execute a move command in the motion thread."""
  381. try:
  382. # Wait if paused
  383. while self.paused and self.running:
  384. time.sleep(0.1)
  385. if not self.running:
  386. return
  387. # Execute the actual motion using sync version
  388. self._move_polar_sync(command.theta, command.rho, command.speed)
  389. # Signal completion if future provided
  390. if command.future and not command.future.done():
  391. command.future.get_loop().call_soon_threadsafe(
  392. command.future.set_result, None
  393. )
  394. except Exception as e:
  395. logger.error(f"Error executing move command: {e}")
  396. if command.future and not command.future.done():
  397. command.future.get_loop().call_soon_threadsafe(
  398. command.future.set_exception, e
  399. )
  400. def _move_polar_sync(self, theta: float, rho: float, speed: Optional[float] = None):
  401. """Synchronous version of move_polar for use in motion thread."""
  402. # Check for valid machine position (can be None if homing failed)
  403. if state.machine_x is None or state.machine_y is None:
  404. logger.error("Cannot execute move: machine position unknown (homing may have failed)")
  405. logger.error("Please home the machine before running patterns")
  406. state.stop_requested = True
  407. return
  408. # This is the original sync logic but running in dedicated thread
  409. if state.table_type == 'dune_weaver_mini':
  410. x_scaling_factor = 2
  411. y_scaling_factor = 3.7
  412. else:
  413. x_scaling_factor = 2
  414. y_scaling_factor = 5
  415. delta_theta = theta - state.current_theta
  416. delta_rho = rho - state.current_rho
  417. x_increment = delta_theta * 100 / (2 * pi * x_scaling_factor)
  418. y_increment = delta_rho * 100 / y_scaling_factor
  419. x_total_steps = state.x_steps_per_mm * (100/x_scaling_factor)
  420. y_total_steps = state.y_steps_per_mm * (100/y_scaling_factor)
  421. offset = x_increment * (x_total_steps * x_scaling_factor / (state.gear_ratio * y_total_steps * y_scaling_factor))
  422. if state.table_type == 'dune_weaver_mini' or state.y_steps_per_mm == 546:
  423. y_increment -= offset
  424. else:
  425. y_increment += offset
  426. new_x_abs = state.machine_x + x_increment
  427. new_y_abs = state.machine_y + y_increment
  428. # Use provided speed or fall back to state.speed
  429. actual_speed = speed if speed is not None else state.speed
  430. # Validate coordinates before sending to prevent GRBL error:2
  431. if isnan(new_x_abs) or isnan(new_y_abs) or isinf(new_x_abs) or isinf(new_y_abs):
  432. logger.error(f"Motion thread: Invalid coordinates detected - X:{new_x_abs}, Y:{new_y_abs}")
  433. logger.error(f" theta:{theta}, rho:{rho}, current_theta:{state.current_theta}, current_rho:{state.current_rho}")
  434. 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}")
  435. state.stop_requested = True
  436. return
  437. # Call sync version of send_grbl_coordinates in this thread
  438. self._send_grbl_coordinates_sync(round(new_x_abs, 3), round(new_y_abs, 3), actual_speed)
  439. # Update state
  440. state.current_theta = theta
  441. state.current_rho = rho
  442. state.machine_x = new_x_abs
  443. state.machine_y = new_y_abs
  444. def _send_grbl_coordinates_sync(self, x: float, y: float, speed: int = 600, timeout: int = 2, home: bool = False):
  445. """Synchronous version of send_grbl_coordinates for motion thread.
  446. Waits for 'ok' with a timeout. GRBL sends 'ok' after the move completes,
  447. which can take many seconds at slow speeds. We use a generous timeout
  448. (120 seconds) to handle slow movements, but prevent indefinite hangs.
  449. """
  450. gcode = f"$J=G91 G21 Y{y} F{speed}" if home else f"G1 G53 X{x} Y{y} F{speed}"
  451. max_wait_time = 120 # Maximum seconds to wait for 'ok' response
  452. while True:
  453. # Check stop_requested at the start of each iteration
  454. if state.stop_requested:
  455. logger.debug("Motion thread: Stop requested, aborting command")
  456. return False
  457. try:
  458. logger.debug(f"Motion thread sending G-code: {gcode}")
  459. state.conn.send(gcode + "\n")
  460. # Wait for 'ok' with timeout
  461. wait_start = time.time()
  462. while True:
  463. # Check stop_requested while waiting
  464. if state.stop_requested:
  465. logger.debug("Motion thread: Stop requested while waiting for response")
  466. return False
  467. # Check for timeout
  468. elapsed = time.time() - wait_start
  469. if elapsed > max_wait_time:
  470. logger.error(f"Motion thread: Timeout ({max_wait_time}s) waiting for 'ok' response")
  471. logger.error("Possible serial communication issue - stopping pattern")
  472. state.stop_requested = True
  473. return False
  474. response = state.conn.readline()
  475. if response:
  476. logger.debug(f"Motion thread response: {response}")
  477. if response.lower() == "ok":
  478. logger.debug("Motion thread: Command execution confirmed.")
  479. return True
  480. # Handle GRBL errors - these mean command failed, stop pattern
  481. if response.lower().startswith("error"):
  482. logger.error(f"Motion thread: GRBL error received: {response}")
  483. logger.error(f"Failed command: {gcode}")
  484. logger.error("Stopping pattern due to GRBL error")
  485. state.stop_requested = True
  486. return False
  487. # Handle GRBL alarms - machine needs attention
  488. if "alarm" in response.lower():
  489. logger.error(f"Motion thread: GRBL ALARM: {response}")
  490. logger.error("Machine alarm triggered - stopping pattern")
  491. state.stop_requested = True
  492. return False
  493. # FluidNC may echo commands back before sending 'ok'
  494. # Silently ignore echoed G-code commands (G0, G1, $J, etc.)
  495. if response.startswith(('G0', 'G1', 'G2', 'G3', '$J', 'M')):
  496. logger.debug(f"Motion thread: Ignoring echoed command: {response}")
  497. continue # Read next line to get 'ok'
  498. # Log truly unexpected responses
  499. logger.warning(f"Motion thread: Unexpected response: '{response}'")
  500. else:
  501. # Log periodically when waiting for response (every 30s)
  502. if int(elapsed) > 0 and int(elapsed) % 30 == 0 and elapsed - int(elapsed) < 0.1:
  503. logger.warning(f"Motion thread: Still waiting for 'ok' after {int(elapsed)}s for command: {gcode}")
  504. except Exception as e:
  505. error_str = str(e)
  506. logger.warning(f"Motion thread error sending command: {error_str}")
  507. # Immediately return for device not configured errors
  508. if "Device not configured" in error_str or "Errno 6" in error_str:
  509. logger.error(f"Motion thread: Device configuration error detected: {error_str}")
  510. state.stop_requested = True
  511. state.conn = None
  512. state.is_connected = False
  513. logger.info("Connection marked as disconnected due to device error")
  514. return False
  515. # Only retry on exception (not on timeout)
  516. logger.warning(f"Motion thread: Error sending {gcode}, retrying...")
  517. time.sleep(0.1)
  518. # Global motion control thread instance
  519. motion_controller = MotionControlThread()
  520. async def cleanup_pattern_manager():
  521. """Clean up pattern manager resources"""
  522. global progress_update_task, pattern_lock, pause_event
  523. try:
  524. # Signal stop to allow any running pattern to exit gracefully
  525. state.stop_requested = True
  526. # Stop motion control thread
  527. motion_controller.stop()
  528. # Cancel progress update task if running
  529. if progress_update_task and not progress_update_task.done():
  530. try:
  531. progress_update_task.cancel()
  532. # Wait for task to actually cancel
  533. try:
  534. await progress_update_task
  535. except asyncio.CancelledError:
  536. pass
  537. except Exception as e:
  538. logger.error(f"Error cancelling progress update task: {e}")
  539. # Clean up pattern lock - wait for it to be released naturally, don't force release
  540. # Force releasing an asyncio.Lock can corrupt internal state if held by another coroutine
  541. current_lock = pattern_lock
  542. if current_lock and current_lock.locked():
  543. logger.info("Pattern lock is held, waiting for release (max 5s)...")
  544. try:
  545. # Wait with timeout for the lock to become available
  546. async with asyncio.timeout(5.0):
  547. async with current_lock:
  548. pass # Lock acquired means previous holder released it
  549. logger.info("Pattern lock released normally")
  550. except asyncio.TimeoutError:
  551. logger.warning("Timed out waiting for pattern lock - creating fresh lock")
  552. except Exception as e:
  553. logger.error(f"Error waiting for pattern lock: {e}")
  554. # Clean up pause event - wake up any waiting tasks, then create fresh event
  555. current_event = pause_event
  556. if current_event:
  557. try:
  558. current_event.set() # Wake up any waiting tasks
  559. except Exception as e:
  560. logger.error(f"Error setting pause event: {e}")
  561. # Clean up pause condition from state
  562. if state.pause_condition:
  563. try:
  564. with state.pause_condition:
  565. state.pause_condition.notify_all()
  566. state.pause_condition = threading.Condition()
  567. except Exception as e:
  568. logger.error(f"Error cleaning up pause condition: {e}")
  569. # Clear all state variables
  570. state.current_playing_file = None
  571. state.execution_progress = 0
  572. state.is_running = False
  573. state.pause_requested = False
  574. state.stop_requested = True
  575. state.is_clearing = False
  576. # Reset machine position
  577. await connection_manager.update_machine_position()
  578. logger.info("Pattern manager resources cleaned up")
  579. except Exception as e:
  580. logger.error(f"Error during pattern manager cleanup: {e}")
  581. finally:
  582. # Reset to fresh instances instead of None to allow continued operation
  583. progress_update_task = None
  584. pattern_lock = asyncio.Lock() # Fresh lock instead of None
  585. pause_event = asyncio.Event() # Fresh event instead of None
  586. pause_event.set() # Initially not paused
  587. def list_theta_rho_files():
  588. files = []
  589. for root, dirs, filenames in os.walk(THETA_RHO_DIR):
  590. # Skip cached_images directories to avoid scanning thousands of WebP files
  591. if 'cached_images' in dirs:
  592. dirs.remove('cached_images')
  593. # Filter .thr files during traversal for better performance
  594. thr_files = [f for f in filenames if f.endswith('.thr')]
  595. for file in thr_files:
  596. relative_path = os.path.relpath(os.path.join(root, file), THETA_RHO_DIR)
  597. # Normalize path separators to always use forward slashes for consistency across platforms
  598. relative_path = relative_path.replace(os.sep, '/')
  599. files.append(relative_path)
  600. logger.debug(f"Found {len(files)} theta-rho files")
  601. return files
  602. def parse_theta_rho_file(file_path):
  603. """Parse a theta-rho file and return a list of (theta, rho) pairs."""
  604. coordinates = []
  605. try:
  606. logger.debug(f"Parsing theta-rho file: {file_path}")
  607. with open(file_path, 'r', encoding='utf-8') as file:
  608. for line in file:
  609. line = line.strip()
  610. if not line or line.startswith("#"):
  611. continue
  612. try:
  613. theta, rho = map(float, line.split())
  614. coordinates.append((theta, rho))
  615. except ValueError:
  616. logger.warning(f"Skipping invalid line: {line}")
  617. continue
  618. except Exception as e:
  619. logger.error(f"Error reading file: {e}")
  620. return coordinates
  621. logger.debug(f"Parsed {len(coordinates)} coordinates from {file_path}")
  622. return coordinates
  623. def get_first_rho_from_cache(file_path, cache_data=None):
  624. """Get the first rho value from cached metadata, falling back to file parsing if needed.
  625. Args:
  626. file_path: Path to the pattern file
  627. cache_data: Optional pre-loaded cache data dict to avoid repeated disk I/O
  628. """
  629. try:
  630. # Import cache_manager locally to avoid circular import
  631. from modules.core import cache_manager
  632. # Try to get from metadata cache first
  633. # Use relative path from THETA_RHO_DIR to match cache keys (which include subdirectories)
  634. file_name = os.path.relpath(file_path, THETA_RHO_DIR)
  635. # Use provided cache_data if available, otherwise load from disk
  636. if cache_data is not None:
  637. # Extract metadata directly from provided cache
  638. data_section = cache_data.get('data', {})
  639. if file_name in data_section:
  640. cached_entry = data_section[file_name]
  641. metadata = cached_entry.get('metadata')
  642. # When cache_data is provided, trust it without checking mtime
  643. # This significantly speeds up bulk operations (playlists with 1000+ patterns)
  644. # by avoiding 1000+ os.path.getmtime() calls on slow storage (e.g., Pi SD cards)
  645. if metadata and 'first_coordinate' in metadata:
  646. return metadata['first_coordinate']['y']
  647. else:
  648. # Fall back to loading cache from disk (original behavior)
  649. metadata = cache_manager.get_pattern_metadata(file_name)
  650. if metadata and 'first_coordinate' in metadata:
  651. # In the cache, 'x' is theta and 'y' is rho
  652. return metadata['first_coordinate']['y']
  653. # Fallback to parsing the file if not in cache
  654. logger.debug(f"Metadata not cached for {file_name}, parsing file")
  655. coordinates = parse_theta_rho_file(file_path)
  656. if coordinates:
  657. return coordinates[0][1] # Return rho value
  658. return None
  659. except Exception as e:
  660. logger.warning(f"Error getting first rho from cache for {file_path}: {str(e)}")
  661. return None
  662. def get_clear_pattern_file(clear_pattern_mode, path=None, cache_data=None):
  663. """Return a .thr file path based on pattern_name and table type.
  664. Args:
  665. clear_pattern_mode: The clear pattern mode to use
  666. path: Optional path to the pattern file for adaptive mode
  667. cache_data: Optional pre-loaded cache data dict to avoid repeated disk I/O
  668. """
  669. if not clear_pattern_mode or clear_pattern_mode == 'none':
  670. return
  671. # Define patterns for each table type
  672. clear_patterns = {
  673. 'dune_weaver': {
  674. 'clear_from_out': './patterns/clear_from_out.thr',
  675. 'clear_from_in': './patterns/clear_from_in.thr',
  676. 'clear_sideway': './patterns/clear_sideway.thr'
  677. },
  678. 'dune_weaver_mini': {
  679. 'clear_from_out': './patterns/clear_from_out_mini.thr',
  680. 'clear_from_in': './patterns/clear_from_in_mini.thr',
  681. 'clear_sideway': './patterns/clear_sideway_mini.thr'
  682. },
  683. 'dune_weaver_mini_pro': {
  684. 'clear_from_out': './patterns/clear_from_out_mini.thr',
  685. 'clear_from_in': './patterns/clear_from_in_mini.thr',
  686. 'clear_sideway': './patterns/clear_sideway_mini.thr'
  687. },
  688. 'dune_weaver_pro': {
  689. 'clear_from_out': './patterns/clear_from_out_pro.thr',
  690. 'clear_from_out_Ultra': './patterns/clear_from_out_Ultra.thr',
  691. 'clear_from_in': './patterns/clear_from_in_pro.thr',
  692. 'clear_from_in_Ultra': './patterns/clear_from_in_Ultra.thr',
  693. 'clear_sideway': './patterns/clear_sideway_pro.thr'
  694. }
  695. }
  696. # Get patterns for current table type, fallback to standard patterns if type not found
  697. table_patterns = clear_patterns.get(state.table_type, clear_patterns['dune_weaver'])
  698. # Check for custom patterns first
  699. if state.custom_clear_from_out and clear_pattern_mode in ['clear_from_out', 'adaptive']:
  700. if clear_pattern_mode == 'adaptive':
  701. # For adaptive mode, use cached metadata to check first rho
  702. if path:
  703. first_rho = get_first_rho_from_cache(path, cache_data)
  704. if first_rho is not None and first_rho < 0.5:
  705. # Use custom clear_from_out if set
  706. custom_path = os.path.join('./patterns', state.custom_clear_from_out)
  707. if os.path.exists(custom_path):
  708. logger.debug(f"Using custom clear_from_out: {custom_path}")
  709. return custom_path
  710. elif clear_pattern_mode == 'clear_from_out':
  711. custom_path = os.path.join('./patterns', state.custom_clear_from_out)
  712. if os.path.exists(custom_path):
  713. logger.debug(f"Using custom clear_from_out: {custom_path}")
  714. return custom_path
  715. if state.custom_clear_from_in and clear_pattern_mode in ['clear_from_in', 'adaptive']:
  716. if clear_pattern_mode == 'adaptive':
  717. # For adaptive mode, use cached metadata to check first rho
  718. if path:
  719. first_rho = get_first_rho_from_cache(path, cache_data)
  720. if first_rho is not None and first_rho >= 0.5:
  721. # Use custom clear_from_in if set
  722. custom_path = os.path.join('./patterns', state.custom_clear_from_in)
  723. if os.path.exists(custom_path):
  724. logger.debug(f"Using custom clear_from_in: {custom_path}")
  725. return custom_path
  726. elif clear_pattern_mode == 'clear_from_in':
  727. custom_path = os.path.join('./patterns', state.custom_clear_from_in)
  728. if os.path.exists(custom_path):
  729. logger.debug(f"Using custom clear_from_in: {custom_path}")
  730. return custom_path
  731. logger.debug(f"Clear pattern mode: {clear_pattern_mode} for table type: {state.table_type}")
  732. if clear_pattern_mode == "random":
  733. return random.choice(list(table_patterns.values()))
  734. if clear_pattern_mode == 'adaptive':
  735. if not path:
  736. logger.warning("No path provided for adaptive clear pattern")
  737. return random.choice(list(table_patterns.values()))
  738. # Use cached metadata to get first rho value
  739. first_rho = get_first_rho_from_cache(path, cache_data)
  740. if first_rho is None:
  741. logger.warning("Could not determine first rho value for adaptive clear pattern")
  742. return random.choice(list(table_patterns.values()))
  743. if first_rho < 0.5:
  744. return table_patterns['clear_from_out']
  745. else:
  746. return table_patterns['clear_from_in']
  747. else:
  748. if clear_pattern_mode not in table_patterns:
  749. return False
  750. return table_patterns[clear_pattern_mode]
  751. def is_clear_pattern(file_path):
  752. """Check if a file path is a clear pattern file."""
  753. # Get all possible clear pattern files for all table types
  754. clear_patterns = []
  755. for table_type in ['dune_weaver', 'dune_weaver_mini', 'dune_weaver_pro']:
  756. clear_patterns.extend([
  757. f'./patterns/clear_from_out{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr',
  758. f'./patterns/clear_from_in{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr',
  759. f'./patterns/clear_sideway{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr'
  760. ])
  761. # Normalize paths for comparison
  762. normalized_path = os.path.normpath(file_path)
  763. normalized_clear_patterns = [os.path.normpath(p) for p in clear_patterns]
  764. # Check if the file path matches any clear pattern path
  765. return normalized_path in normalized_clear_patterns
  766. async def _execute_pattern_internal(file_path):
  767. """Internal function to execute a pattern file. Must be called with lock already held.
  768. Args:
  769. file_path: Path to the .thr file to execute
  770. Returns:
  771. True if pattern completed successfully, False if stopped/skipped
  772. """
  773. # Run file parsing in thread to avoid blocking the event loop
  774. coordinates = await asyncio.to_thread(parse_theta_rho_file, file_path)
  775. total_coordinates = len(coordinates)
  776. # Cache coordinates in state for frontend preview (avoids re-parsing large files)
  777. state._current_coordinates = coordinates
  778. if total_coordinates < 2:
  779. logger.warning("Not enough coordinates for interpolation")
  780. return False
  781. # Determine if this is a clearing pattern
  782. is_clear_file = is_clear_pattern(file_path)
  783. if is_clear_file:
  784. initial_speed = state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  785. logger.info(f"Running clearing pattern at initial speed {initial_speed}")
  786. else:
  787. logger.info(f"Running normal pattern at initial speed {state.speed}")
  788. state.execution_progress = (0, total_coordinates, None, 0)
  789. # stop actions without resetting the playlist, and don't wait for lock (we already have it)
  790. # Preserve is_clearing flag since stop_actions resets it
  791. was_clearing = state.is_clearing
  792. await stop_actions(clear_playlist=False, wait_for_lock=False)
  793. state.is_clearing = was_clearing
  794. state.current_playing_file = file_path
  795. state.stop_requested = False
  796. # Reset LED idle timeout activity time when pattern starts
  797. import time as time_module
  798. state.dw_led_last_activity_time = time_module.time()
  799. logger.info(f"Starting pattern execution: {file_path}")
  800. logger.info(f"t: {state.current_theta}, r: {state.current_rho}")
  801. await reset_theta()
  802. start_time = time.time()
  803. total_pause_time = 0 # Track total time spent paused (manual + scheduled)
  804. if state.led_controller:
  805. logger.info(f"Setting LED to playing effect: {state.dw_led_playing_effect}")
  806. await state.led_controller.effect_playing_async(state.dw_led_playing_effect)
  807. # Cancel idle timeout when playing starts
  808. idle_timeout_manager.cancel_timeout()
  809. with tqdm(
  810. total=total_coordinates,
  811. unit="coords",
  812. desc=f"Executing Pattern {file_path}",
  813. dynamic_ncols=True,
  814. disable=False,
  815. mininterval=1.0
  816. ) as pbar:
  817. for i, coordinate in enumerate(coordinates):
  818. theta, rho = coordinate
  819. if state.stop_requested:
  820. logger.info("Execution stopped by user")
  821. if state.led_controller:
  822. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  823. start_idle_led_timeout()
  824. break
  825. if state.skip_requested:
  826. logger.info("Skipping pattern...")
  827. await connection_manager.check_idle_async()
  828. if state.led_controller:
  829. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  830. start_idle_led_timeout()
  831. break
  832. # Wait for resume if paused (manual or scheduled)
  833. manual_pause = state.pause_requested
  834. # Only check scheduled pause during pattern if "finish pattern first" is NOT enabled
  835. scheduled_pause = is_in_scheduled_pause_period() if not state.scheduled_pause_finish_pattern else False
  836. if manual_pause or scheduled_pause:
  837. pause_start = time.time() # Track when pause started
  838. if manual_pause and scheduled_pause:
  839. logger.info("Execution paused (manual + scheduled pause active)...")
  840. elif manual_pause:
  841. logger.info("Execution paused (manual)...")
  842. else:
  843. logger.info("Execution paused (scheduled pause period)...")
  844. # Turn off LED controller if scheduled pause and control_wled is enabled
  845. if state.scheduled_pause_control_wled and state.led_controller:
  846. logger.info("Turning off LED lights during Still Sands period")
  847. await state.led_controller.set_power_async(0)
  848. # Only show idle effect if NOT in scheduled pause with LED control
  849. # (manual pause always shows idle effect)
  850. if state.led_controller and not (scheduled_pause and state.scheduled_pause_control_wled):
  851. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  852. start_idle_led_timeout()
  853. # Remember if we turned off LED controller for scheduled pause
  854. wled_was_off_for_scheduled = scheduled_pause and state.scheduled_pause_control_wled and not manual_pause
  855. # Wait until both manual pause is released AND we're outside scheduled pause period
  856. # Also check for stop/skip requests to allow immediate interruption
  857. interrupted = False
  858. while state.pause_requested or is_in_scheduled_pause_period():
  859. # Check for stop/skip first
  860. if state.stop_requested:
  861. logger.info("Stop requested during pause, exiting")
  862. interrupted = True
  863. break
  864. if state.skip_requested:
  865. logger.info("Skip requested during pause, skipping pattern")
  866. interrupted = True
  867. break
  868. if state.pause_requested:
  869. # For manual pause, wait on multiple events for immediate response
  870. # Wake on: resume, stop, skip, or timeout (for flag polling fallback)
  871. pause_event = get_pause_event()
  872. stop_event = state.get_stop_event()
  873. skip_event = state.get_skip_event()
  874. wait_tasks = [asyncio.create_task(pause_event.wait(), name='pause')]
  875. if stop_event:
  876. wait_tasks.append(asyncio.create_task(stop_event.wait(), name='stop'))
  877. if skip_event:
  878. wait_tasks.append(asyncio.create_task(skip_event.wait(), name='skip'))
  879. # Add timeout to ensure we periodically check flags even if events aren't set
  880. # This handles the case where stop is called from sync context (no event loop)
  881. timeout_task = asyncio.create_task(asyncio.sleep(1.0), name='timeout')
  882. wait_tasks.append(timeout_task)
  883. try:
  884. done, pending = await asyncio.wait(
  885. wait_tasks, return_when=asyncio.FIRST_COMPLETED
  886. )
  887. finally:
  888. for task in pending:
  889. task.cancel()
  890. for task in pending:
  891. try:
  892. await task
  893. except asyncio.CancelledError:
  894. pass
  895. else:
  896. # For scheduled pause, use wait_for_interrupt for instant response
  897. result = await state.wait_for_interrupt(timeout=1.0)
  898. if result in ('stopped', 'skipped'):
  899. interrupted = True
  900. break
  901. total_pause_time += time.time() - pause_start # Add pause duration
  902. if interrupted:
  903. # Exit the coordinate loop if we were interrupted
  904. break
  905. logger.info("Execution resumed...")
  906. if state.led_controller:
  907. # Turn LED controller back on if it was turned off for scheduled pause
  908. if wled_was_off_for_scheduled:
  909. logger.info("Turning LED lights back on as Still Sands period ended")
  910. await state.led_controller.set_power_async(1)
  911. # CRITICAL: Give LED controller time to fully power on before sending more commands
  912. # Without this delay, rapid-fire requests can crash controllers on resource-constrained Pis
  913. await asyncio.sleep(0.5)
  914. await state.led_controller.effect_playing_async(state.dw_led_playing_effect)
  915. # Cancel idle timeout when resuming from pause
  916. idle_timeout_manager.cancel_timeout()
  917. # Dynamically determine the speed for each movement
  918. # Use clear_pattern_speed if it's set and this is a clear file, otherwise use state.speed
  919. if is_clear_file and state.clear_pattern_speed is not None:
  920. current_speed = state.clear_pattern_speed
  921. else:
  922. current_speed = state.speed
  923. await move_polar(theta, rho, current_speed)
  924. # Update progress for all coordinates including the first one
  925. pbar.update(1)
  926. elapsed_time = time.time() - start_time
  927. estimated_remaining_time = (total_coordinates - (i + 1)) / pbar.format_dict['rate'] if pbar.format_dict['rate'] and total_coordinates else 0
  928. state.execution_progress = (i + 1, total_coordinates, estimated_remaining_time, elapsed_time)
  929. # Add a small delay to allow other async operations
  930. await asyncio.sleep(0.001)
  931. # Update progress one last time to show 100%
  932. elapsed_time = time.time() - start_time
  933. actual_execution_time = elapsed_time - total_pause_time
  934. state.execution_progress = (total_coordinates, total_coordinates, 0, elapsed_time)
  935. # Give WebSocket a chance to send the final update
  936. await asyncio.sleep(0.1)
  937. # Log execution time (only for completed patterns, not stopped/skipped)
  938. was_completed = not state.stop_requested and not state.skip_requested
  939. pattern_name = os.path.basename(file_path)
  940. effective_speed = state.clear_pattern_speed if (is_clear_file and state.clear_pattern_speed is not None) else state.speed
  941. log_execution_time(
  942. pattern_name=pattern_name,
  943. table_type=state.table_type,
  944. speed=effective_speed,
  945. actual_time=actual_execution_time,
  946. total_coordinates=total_coordinates,
  947. was_completed=was_completed
  948. )
  949. if not state.conn:
  950. logger.error("Device is not connected. Stopping pattern execution.")
  951. return False
  952. await connection_manager.check_idle_async()
  953. # Set LED back to idle when pattern completes normally (not stopped early)
  954. if state.led_controller and not state.stop_requested:
  955. logger.info(f"Setting LED to idle effect: {state.dw_led_idle_effect}")
  956. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  957. start_idle_led_timeout()
  958. logger.debug("LED effect set to idle after pattern completion")
  959. return was_completed
  960. async def run_theta_rho_file(file_path, is_playlist=False, clear_pattern=None, cache_data=None):
  961. """Run a theta-rho file with optional pre-execution clear pattern.
  962. Args:
  963. file_path: Path to the main .thr file to execute
  964. is_playlist: True if running as part of a playlist
  965. clear_pattern: Clear pattern mode ('adaptive', 'clear_from_in', 'clear_from_out', 'none', or None)
  966. cache_data: Pre-loaded metadata cache for adaptive clear pattern selection
  967. """
  968. lock = get_pattern_lock()
  969. if lock.locked():
  970. logger.warning("Another pattern is already running. Cannot start a new one.")
  971. return
  972. async with lock: # This ensures only one pattern can run at a time
  973. # Clear any stale pause state from previous playlist
  974. state.pause_time_remaining = 0
  975. state.original_pause_time = None
  976. # Start progress update task only if not part of a playlist
  977. global progress_update_task
  978. if not is_playlist and not progress_update_task:
  979. progress_update_task = asyncio.create_task(broadcast_progress())
  980. # Run clear pattern first if specified
  981. if clear_pattern and clear_pattern != 'none':
  982. clear_file_path = get_clear_pattern_file(clear_pattern, file_path, cache_data)
  983. if clear_file_path:
  984. logger.info(f"Running pre-execution clear pattern: {clear_file_path}")
  985. state.is_clearing = True
  986. await _execute_pattern_internal(clear_file_path)
  987. state.is_clearing = False
  988. # Reset skip flag after clear pattern (if user skipped clear, continue to main)
  989. state.skip_requested = False
  990. # Check if stopped during clear pattern
  991. if state.stop_requested:
  992. logger.info("Execution stopped during clear pattern")
  993. if not is_playlist:
  994. state.current_playing_file = None
  995. state.execution_progress = None
  996. return
  997. # Run the main pattern
  998. completed = await _execute_pattern_internal(file_path)
  999. # Only clear state if not part of a playlist
  1000. if not is_playlist:
  1001. state.current_playing_file = None
  1002. state.execution_progress = None
  1003. logger.info("Pattern execution completed and state cleared")
  1004. # Only cancel progress update task if not part of a playlist
  1005. if progress_update_task:
  1006. progress_update_task.cancel()
  1007. try:
  1008. await progress_update_task
  1009. except asyncio.CancelledError:
  1010. pass
  1011. progress_update_task = None
  1012. else:
  1013. logger.info("Pattern execution completed, maintaining state for playlist")
  1014. async def run_theta_rho_files(file_paths, pause_time=0, clear_pattern=None, run_mode="single", shuffle=False):
  1015. """Run multiple .thr files in sequence with options.
  1016. The playlist now stores only main patterns. Clear patterns are executed dynamically
  1017. before each main pattern based on the clear_pattern option.
  1018. """
  1019. state.stop_requested = False
  1020. # Reset LED idle timeout activity time when playlist starts
  1021. import time as time_module
  1022. state.dw_led_last_activity_time = time_module.time()
  1023. # Set initial playlist state
  1024. state.playlist_mode = run_mode
  1025. state.current_playlist_index = 0
  1026. # Start progress update task for the playlist
  1027. global progress_update_task
  1028. if not progress_update_task:
  1029. progress_update_task = asyncio.create_task(broadcast_progress())
  1030. # Shuffle main patterns if requested (before starting)
  1031. if shuffle:
  1032. random.shuffle(file_paths)
  1033. logger.info("Playlist shuffled")
  1034. # Store only main patterns in the playlist
  1035. state.current_playlist = file_paths
  1036. try:
  1037. while True:
  1038. # Load metadata cache once per playlist iteration (for adaptive clear patterns)
  1039. cache_data = None
  1040. if clear_pattern and clear_pattern in ['adaptive', 'clear_from_in', 'clear_from_out']:
  1041. from modules.core import cache_manager
  1042. cache_data = await asyncio.to_thread(cache_manager.load_metadata_cache)
  1043. logger.info(f"Loaded metadata cache for {len(cache_data.get('data', {}))} patterns")
  1044. # Reset pattern counter at the start of the playlist
  1045. state.patterns_since_last_home = 0
  1046. # Execute main patterns using index-based access
  1047. # This allows the playlist to be reordered during execution
  1048. idx = 0
  1049. while state.current_playlist and idx < len(state.current_playlist):
  1050. state.current_playlist_index = idx
  1051. if state.stop_requested or not state.current_playlist:
  1052. logger.info("Execution stopped")
  1053. return
  1054. # Get the pattern at the current index (may have changed due to reordering)
  1055. file_path = state.current_playlist[idx]
  1056. logger.info(f"Running pattern {idx + 1}/{len(state.current_playlist)}: {file_path}")
  1057. # Clear pause state when starting a new pattern (prevents stale "waiting" UI)
  1058. state.pause_time_remaining = 0
  1059. state.original_pause_time = None
  1060. # Execute the pattern with optional clear pattern
  1061. await run_theta_rho_file(
  1062. file_path,
  1063. is_playlist=True,
  1064. clear_pattern=clear_pattern,
  1065. cache_data=cache_data
  1066. )
  1067. # Increment pattern counter (auto-home check happens after pause time)
  1068. state.patterns_since_last_home += 1
  1069. logger.debug(f"Patterns since last home: {state.patterns_since_last_home}")
  1070. # Check for scheduled pause after pattern completes (when "finish pattern first" is enabled)
  1071. if state.scheduled_pause_finish_pattern and is_in_scheduled_pause_period() and not state.stop_requested and not state.skip_requested:
  1072. logger.info("Pattern completed. Entering Still Sands period (finish pattern first mode)...")
  1073. wled_was_off_for_scheduled = False
  1074. if state.scheduled_pause_control_wled and state.led_controller:
  1075. logger.info("Turning off LED lights during Still Sands period")
  1076. await state.led_controller.set_power_async(0)
  1077. wled_was_off_for_scheduled = True
  1078. elif state.led_controller:
  1079. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  1080. start_idle_led_timeout()
  1081. # Wait for scheduled pause to end, but allow stop/skip to interrupt
  1082. result = await wait_with_interrupt(
  1083. is_in_scheduled_pause_period,
  1084. check_stop=True,
  1085. check_skip=True,
  1086. )
  1087. if result == 'completed':
  1088. logger.info("Still Sands period ended. Resuming playlist...")
  1089. if state.led_controller:
  1090. if wled_was_off_for_scheduled:
  1091. logger.info("Turning LED lights back on as Still Sands period ended")
  1092. await state.led_controller.set_power_async(1)
  1093. await asyncio.sleep(0.5)
  1094. await state.led_controller.effect_playing_async(state.dw_led_playing_effect)
  1095. idle_timeout_manager.cancel_timeout()
  1096. # Handle pause between patterns
  1097. if state.current_playlist and idx < len(state.current_playlist) - 1 and not state.stop_requested and pause_time > 0 and not state.skip_requested:
  1098. logger.info(f"Pausing for {pause_time} seconds")
  1099. state.original_pause_time = pause_time
  1100. pause_start = time.time()
  1101. while time.time() - pause_start < pause_time:
  1102. state.pause_time_remaining = pause_start + pause_time - time.time()
  1103. if state.skip_requested:
  1104. logger.info("Pause interrupted by skip request")
  1105. break
  1106. await asyncio.sleep(1)
  1107. # Clear both pause state vars immediately (so UI updates right away)
  1108. state.pause_time_remaining = 0
  1109. state.original_pause_time = None
  1110. # Auto-home after pause time, before next clear pattern starts
  1111. # Only home if there's a next pattern and we haven't been stopped
  1112. if (state.auto_home_enabled and
  1113. state.patterns_since_last_home >= state.auto_home_after_patterns and
  1114. state.current_playlist and idx < len(state.current_playlist) - 1 and
  1115. not state.stop_requested):
  1116. logger.info(f"Auto-homing triggered after {state.patterns_since_last_home} patterns (before next clear pattern)")
  1117. try:
  1118. success = await asyncio.to_thread(connection_manager.home)
  1119. if success:
  1120. logger.info("Auto-homing completed successfully")
  1121. state.patterns_since_last_home = 0
  1122. else:
  1123. logger.warning("Auto-homing failed, continuing with playlist")
  1124. except Exception as e:
  1125. logger.error(f"Error during auto-homing: {e}")
  1126. state.skip_requested = False
  1127. idx += 1
  1128. if run_mode == "indefinite":
  1129. logger.info("Playlist completed. Restarting as per 'indefinite' run mode")
  1130. if pause_time > 0:
  1131. pause_start = time.time()
  1132. while time.time() - pause_start < pause_time:
  1133. state.pause_time_remaining = pause_start + pause_time - time.time()
  1134. if state.skip_requested:
  1135. logger.info("Pause interrupted by skip request")
  1136. break
  1137. await asyncio.sleep(1)
  1138. # Clear both pause state vars immediately (so UI updates right away)
  1139. state.pause_time_remaining = 0
  1140. state.original_pause_time = None
  1141. continue
  1142. else:
  1143. logger.info("Playlist completed")
  1144. break
  1145. finally:
  1146. if progress_update_task:
  1147. progress_update_task.cancel()
  1148. try:
  1149. await progress_update_task
  1150. except asyncio.CancelledError:
  1151. pass
  1152. progress_update_task = None
  1153. state.current_playing_file = None
  1154. state.execution_progress = None
  1155. state.current_playlist = None
  1156. state.current_playlist_index = None
  1157. state.playlist_mode = None
  1158. state.pause_time_remaining = 0
  1159. if state.led_controller:
  1160. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  1161. start_idle_led_timeout()
  1162. logger.info("All requested patterns completed (or stopped) and state cleared")
  1163. async def stop_actions(clear_playlist = True, wait_for_lock = True):
  1164. """Stop all current actions and wait for pattern to fully release.
  1165. Args:
  1166. clear_playlist: Whether to clear playlist state
  1167. wait_for_lock: Whether to wait for pattern_lock to be released. Set to False when
  1168. called from within pattern execution to avoid deadlock.
  1169. Returns:
  1170. True if stopped cleanly, False if timed out waiting for pattern lock
  1171. """
  1172. timed_out = False
  1173. try:
  1174. with state.pause_condition:
  1175. state.pause_requested = False
  1176. state.stop_requested = True
  1177. state.is_clearing = False
  1178. # Always clear pause time between patterns on stop
  1179. state.pause_time_remaining = 0
  1180. state.original_pause_time = None
  1181. if clear_playlist:
  1182. # Clear playlist state
  1183. state.current_playlist = None
  1184. state.current_playlist_index = None
  1185. state.playlist_mode = None
  1186. # Cancel progress update task if we're clearing the playlist
  1187. global progress_update_task
  1188. if progress_update_task and not progress_update_task.done():
  1189. progress_update_task.cancel()
  1190. # Cancel the playlist task itself (late import to avoid circular dependency)
  1191. from modules.core import playlist_manager
  1192. await playlist_manager.cancel_current_playlist()
  1193. state.pause_condition.notify_all()
  1194. # Also set the pause event to wake up any paused patterns
  1195. get_pause_event().set()
  1196. # Send stop command to motion thread to clear its queue
  1197. if motion_controller.running:
  1198. motion_controller.command_queue.put(MotionCommand('stop'))
  1199. # Wait for the pattern lock to be released before continuing
  1200. # This ensures that when stop_actions completes, the pattern has fully stopped
  1201. # Skip this if called from within pattern execution to avoid deadlock
  1202. lock = get_pattern_lock()
  1203. if wait_for_lock and lock.locked():
  1204. logger.info("Waiting for pattern to fully stop...")
  1205. # Use a timeout to prevent hanging forever
  1206. try:
  1207. async with asyncio.timeout(10.0):
  1208. async with lock:
  1209. logger.info("Pattern lock acquired - pattern has fully stopped")
  1210. except asyncio.TimeoutError:
  1211. logger.warning("Timeout waiting for pattern to stop - forcing cleanup")
  1212. timed_out = True
  1213. # Force cleanup of state even if pattern didn't release lock gracefully
  1214. state.current_playing_file = None
  1215. state.execution_progress = None
  1216. state.is_running = False
  1217. # Always clear the current playing file after stop
  1218. state.current_playing_file = None
  1219. state.execution_progress = None
  1220. # Call async function directly since we're in async context
  1221. await connection_manager.update_machine_position()
  1222. return not timed_out
  1223. except Exception as e:
  1224. logger.error(f"Error during stop_actions: {e}")
  1225. # Force cleanup state on error
  1226. state.current_playing_file = None
  1227. state.execution_progress = None
  1228. state.is_running = False
  1229. # Ensure we still update machine position even if there's an error
  1230. try:
  1231. await connection_manager.update_machine_position()
  1232. except Exception as update_err:
  1233. logger.error(f"Error updating machine position on error: {update_err}")
  1234. return False
  1235. async def move_polar(theta, rho, speed=None):
  1236. """
  1237. Queue a motion command to be executed in the dedicated motion control thread.
  1238. This makes motion control non-blocking for API endpoints.
  1239. Args:
  1240. theta (float): Target theta coordinate
  1241. rho (float): Target rho coordinate
  1242. speed (int, optional): Speed override. If None, uses state.speed
  1243. """
  1244. # Note: stop_requested is cleared once at pattern start (execute_theta_rho_file line 890)
  1245. # Don't clear it here on every coordinate - causes performance issues with event system
  1246. # Ensure motion control thread is running
  1247. if not motion_controller.running:
  1248. motion_controller.start()
  1249. # Create future for async/await pattern
  1250. loop = asyncio.get_event_loop()
  1251. future = loop.create_future()
  1252. # Create and queue motion command
  1253. command = MotionCommand(
  1254. command_type='move',
  1255. theta=theta,
  1256. rho=rho,
  1257. speed=speed,
  1258. future=future
  1259. )
  1260. motion_controller.command_queue.put(command)
  1261. logger.debug(f"Queued motion command: theta={theta}, rho={rho}, speed={speed}")
  1262. # Wait for command completion
  1263. await future
  1264. def pause_execution():
  1265. """Pause pattern execution using asyncio Event."""
  1266. logger.info("Pausing pattern execution")
  1267. state.pause_requested = True
  1268. get_pause_event().clear() # Clear the event to pause execution
  1269. return True
  1270. def resume_execution():
  1271. """Resume pattern execution using asyncio Event."""
  1272. logger.info("Resuming pattern execution")
  1273. state.pause_requested = False
  1274. get_pause_event().set() # Set the event to resume execution
  1275. return True
  1276. async def reset_theta():
  1277. logger.info('Resetting Theta')
  1278. state.current_theta = state.current_theta % (2 * pi)
  1279. # Call async function directly since we're in async context
  1280. await connection_manager.update_machine_position()
  1281. def set_speed(new_speed):
  1282. state.speed = new_speed
  1283. logger.info(f'Set new state.speed {new_speed}')
  1284. def get_status():
  1285. """Get the current status of pattern execution."""
  1286. status = {
  1287. "current_file": state.current_playing_file,
  1288. "is_paused": state.pause_requested or is_in_scheduled_pause_period(),
  1289. "manual_pause": state.pause_requested,
  1290. "scheduled_pause": is_in_scheduled_pause_period(),
  1291. "is_running": bool(state.current_playing_file and not state.stop_requested),
  1292. "is_homing": state.is_homing,
  1293. "is_clearing": state.is_clearing,
  1294. "progress": None,
  1295. "playlist": None,
  1296. "speed": state.speed,
  1297. "pause_time_remaining": state.pause_time_remaining,
  1298. "original_pause_time": getattr(state, 'original_pause_time', None),
  1299. "connection_status": state.conn.is_connected() if state.conn else False,
  1300. "current_theta": state.current_theta,
  1301. "current_rho": state.current_rho
  1302. }
  1303. # Add playlist information if available
  1304. if state.current_playlist and state.current_playlist_index is not None:
  1305. # When a clear pattern is running, the "next" pattern is the current main pattern
  1306. # (since the clear pattern runs before the main pattern at current_playlist_index)
  1307. if state.is_clearing:
  1308. next_file = state.current_playlist[state.current_playlist_index]
  1309. else:
  1310. next_index = state.current_playlist_index + 1
  1311. next_file = state.current_playlist[next_index] if next_index < len(state.current_playlist) else None
  1312. status["playlist"] = {
  1313. "current_index": state.current_playlist_index,
  1314. "total_files": len(state.current_playlist),
  1315. "mode": state.playlist_mode,
  1316. "next_file": next_file,
  1317. "files": state.current_playlist,
  1318. "name": state.current_playlist_name
  1319. }
  1320. if state.execution_progress:
  1321. current, total, remaining_time, elapsed_time = state.execution_progress
  1322. status["progress"] = {
  1323. "current": current,
  1324. "total": total,
  1325. "remaining_time": remaining_time,
  1326. "elapsed_time": elapsed_time,
  1327. "percentage": (current / total * 100) if total > 0 else 0
  1328. }
  1329. # Add historical execution time if available for this pattern at current speed
  1330. if state.current_playing_file:
  1331. pattern_name = os.path.basename(state.current_playing_file)
  1332. historical_time = get_last_completed_execution_time(pattern_name, state.speed)
  1333. if historical_time:
  1334. status["progress"]["last_completed_time"] = historical_time
  1335. return status
  1336. async def broadcast_progress():
  1337. """Background task to broadcast progress updates."""
  1338. from main import broadcast_status_update
  1339. while True:
  1340. # Send status updates regardless of pattern_lock state
  1341. status = get_status()
  1342. # Use the existing broadcast function from main.py
  1343. await broadcast_status_update(status)
  1344. # Check if we should stop broadcasting
  1345. if not state.current_playlist:
  1346. # If no playlist, only stop if no pattern is being executed
  1347. if not get_pattern_lock().locked():
  1348. logger.info("No playlist or pattern running, stopping broadcast")
  1349. break
  1350. # Wait before next update
  1351. await asyncio.sleep(1)