pattern_manager.py 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717
  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. Includes retry logic for serial corruption errors (common on Pi 3B+).
  450. """
  451. gcode = f"$J=G91 G21 Y{y} F{speed}" if home else f"G1 G53 X{x} Y{y} F{speed}"
  452. max_wait_time = 120 # Maximum seconds to wait for 'ok' response
  453. max_corruption_retries = 3 # Max retries for corruption-type errors
  454. max_timeout_retries = 2 # Max retries for timeout (lost 'ok' response)
  455. corruption_retry_count = 0
  456. timeout_retry_count = 0
  457. # GRBL error codes that indicate likely serial corruption (syntax errors)
  458. # These are recoverable by resending the command
  459. corruption_error_codes = {
  460. 'error:1', # Expected command letter
  461. 'error:2', # Bad number format
  462. 'error:20', # Invalid gcode ID (e.g., G5s instead of G53)
  463. 'error:21', # Invalid gcode command value
  464. 'error:22', # Invalid gcode command value in negative
  465. 'error:23', # Invalid gcode command value in decimal
  466. }
  467. while True:
  468. # Check stop_requested at the start of each iteration
  469. if state.stop_requested:
  470. logger.debug("Motion thread: Stop requested, aborting command")
  471. return False
  472. try:
  473. # Clear any stale input data before sending to prevent interleaving
  474. # This helps with timing issues on slower UARTs like Pi 3B+
  475. if hasattr(state.conn, 'reset_input_buffer'):
  476. state.conn.reset_input_buffer()
  477. logger.debug(f"Motion thread sending G-code: {gcode}")
  478. state.conn.send(gcode + "\n")
  479. # Small delay for serial buffer to stabilize on slower UARTs
  480. # Prevents timing-related corruption on Pi 3B+
  481. time.sleep(0.005)
  482. # Wait for 'ok' with timeout
  483. wait_start = time.time()
  484. while True:
  485. # Check stop_requested while waiting
  486. if state.stop_requested:
  487. logger.debug("Motion thread: Stop requested while waiting for response")
  488. return False
  489. # Check for timeout
  490. elapsed = time.time() - wait_start
  491. if elapsed > max_wait_time:
  492. logger.warning(f"Motion thread: Timeout ({max_wait_time}s) waiting for 'ok' response")
  493. # Attempt to recover by checking machine status
  494. # The 'ok' might have been lost but command may have executed
  495. logger.info("Motion thread: Attempting timeout recovery - checking machine status")
  496. try:
  497. # Clear buffer first
  498. if hasattr(state.conn, 'reset_input_buffer'):
  499. state.conn.reset_input_buffer()
  500. # Send status query
  501. state.conn.send("?\n")
  502. time.sleep(0.2)
  503. # Try to read status response
  504. status_response = None
  505. for _ in range(10):
  506. resp = state.conn.readline()
  507. if resp:
  508. logger.debug(f"Motion thread: Status query response: {resp}")
  509. if '<' in resp or 'Idle' in resp or 'Run' in resp:
  510. status_response = resp
  511. break
  512. # Also check for 'ok' that might have been delayed
  513. if resp.lower() == 'ok':
  514. logger.info("Motion thread: Received delayed 'ok' during recovery")
  515. return True
  516. time.sleep(0.05)
  517. if status_response:
  518. if 'Idle' in status_response:
  519. # Machine is idle - command likely completed, 'ok' was lost
  520. logger.info("Motion thread: Machine is Idle - assuming command completed (ok was lost)")
  521. return True
  522. elif 'Run' in status_response:
  523. # Machine still running - extend timeout
  524. logger.info("Motion thread: Machine still running, extending wait time")
  525. wait_start = time.time() # Reset timeout
  526. continue
  527. else:
  528. logger.warning(f"Motion thread: Unknown status: {status_response}")
  529. # No valid status response - connection may be dead
  530. timeout_retry_count += 1
  531. if timeout_retry_count <= max_timeout_retries:
  532. logger.warning(f"Motion thread: No response, retrying command ({timeout_retry_count}/{max_timeout_retries})")
  533. time.sleep(0.1)
  534. break # Break inner loop to resend command
  535. except Exception as e:
  536. logger.error(f"Motion thread: Error during timeout recovery: {e}")
  537. # Max retries exceeded or recovery failed
  538. logger.error("Motion thread: Timeout recovery failed - stopping pattern")
  539. logger.error("Possible serial communication issue")
  540. state.stop_requested = True
  541. return False
  542. response = state.conn.readline()
  543. if response:
  544. logger.debug(f"Motion thread response: {response}")
  545. if response.lower() == "ok":
  546. logger.debug("Motion thread: Command execution confirmed.")
  547. # Reset corruption retry count on success
  548. if corruption_retry_count > 0:
  549. logger.info(f"Motion thread: Command succeeded after {corruption_retry_count} corruption retry(ies)")
  550. return True
  551. # Handle GRBL errors
  552. if response.lower().startswith("error"):
  553. error_code = response.lower().split()[0] if response else ""
  554. # Check if this is a corruption-type error (recoverable)
  555. if error_code in corruption_error_codes:
  556. corruption_retry_count += 1
  557. if corruption_retry_count <= max_corruption_retries:
  558. logger.warning(f"Motion thread: Likely serial corruption detected ({response})")
  559. logger.warning(f"Motion thread: Retrying command ({corruption_retry_count}/{max_corruption_retries}): {gcode}")
  560. # Clear buffer and wait longer before retry
  561. if hasattr(state.conn, 'reset_input_buffer'):
  562. state.conn.reset_input_buffer()
  563. time.sleep(0.02) # 20ms delay before retry
  564. break # Break inner loop to retry send
  565. else:
  566. logger.error(f"Motion thread: Max corruption retries ({max_corruption_retries}) exceeded")
  567. logger.error(f"Motion thread: GRBL error received: {response}")
  568. logger.error(f"Failed command: {gcode}")
  569. logger.error("Stopping pattern due to persistent serial corruption")
  570. state.stop_requested = True
  571. return False
  572. else:
  573. # Non-corruption error - stop immediately
  574. logger.error(f"Motion thread: GRBL error received: {response}")
  575. logger.error(f"Failed command: {gcode}")
  576. logger.error("Stopping pattern due to GRBL error")
  577. state.stop_requested = True
  578. return False
  579. # Handle GRBL alarms - machine needs attention
  580. if "alarm" in response.lower():
  581. logger.error(f"Motion thread: GRBL ALARM: {response}")
  582. logger.error("Machine alarm triggered - stopping pattern")
  583. state.stop_requested = True
  584. return False
  585. # FluidNC may echo commands back before sending 'ok'
  586. # Silently ignore echoed G-code commands (G0, G1, $J, etc.)
  587. if response.startswith(('G0', 'G1', 'G2', 'G3', '$J', 'M')):
  588. logger.debug(f"Motion thread: Ignoring echoed command: {response}")
  589. continue # Read next line to get 'ok'
  590. # Check for corruption indicator in MSG:ERR responses
  591. if 'MSG:ERR' in response and 'Bad GCode' in response:
  592. corruption_retry_count += 1
  593. if corruption_retry_count <= max_corruption_retries:
  594. logger.warning(f"Motion thread: Corrupted command detected: {response}")
  595. logger.warning(f"Motion thread: Retrying command ({corruption_retry_count}/{max_corruption_retries}): {gcode}")
  596. # Don't break yet - wait for the error:XX that follows
  597. continue
  598. # If we've exceeded retries, the error:XX handler above will catch it
  599. # Log truly unexpected responses
  600. logger.warning(f"Motion thread: Unexpected response: '{response}'")
  601. else:
  602. # Log periodically when waiting for response (every 30s)
  603. if int(elapsed) > 0 and int(elapsed) % 30 == 0 and elapsed - int(elapsed) < 0.1:
  604. logger.warning(f"Motion thread: Still waiting for 'ok' after {int(elapsed)}s for command: {gcode}")
  605. else:
  606. # Inner while loop completed without break - shouldn't happen normally
  607. # This means we hit timeout, which is handled above
  608. continue
  609. except Exception as e:
  610. error_str = str(e)
  611. logger.warning(f"Motion thread error sending command: {error_str}")
  612. # Immediately return for device not configured errors
  613. if "Device not configured" in error_str or "Errno 6" in error_str:
  614. logger.error(f"Motion thread: Device configuration error detected: {error_str}")
  615. state.stop_requested = True
  616. state.conn = None
  617. state.is_connected = False
  618. logger.info("Connection marked as disconnected due to device error")
  619. return False
  620. # Retry on exception or corruption error
  621. logger.warning(f"Motion thread: Retrying {gcode}...")
  622. time.sleep(0.1)
  623. # Global motion control thread instance
  624. motion_controller = MotionControlThread()
  625. async def cleanup_pattern_manager():
  626. """Clean up pattern manager resources"""
  627. global progress_update_task, pattern_lock, pause_event
  628. try:
  629. # Signal stop to allow any running pattern to exit gracefully
  630. state.stop_requested = True
  631. # Stop motion control thread
  632. motion_controller.stop()
  633. # Cancel progress update task if running
  634. if progress_update_task and not progress_update_task.done():
  635. try:
  636. progress_update_task.cancel()
  637. # Wait for task to actually cancel
  638. try:
  639. await progress_update_task
  640. except asyncio.CancelledError:
  641. pass
  642. except Exception as e:
  643. logger.error(f"Error cancelling progress update task: {e}")
  644. # Clean up pattern lock - wait for it to be released naturally, don't force release
  645. # Force releasing an asyncio.Lock can corrupt internal state if held by another coroutine
  646. current_lock = pattern_lock
  647. if current_lock and current_lock.locked():
  648. logger.info("Pattern lock is held, waiting for release (max 5s)...")
  649. try:
  650. # Wait with timeout for the lock to become available
  651. async with asyncio.timeout(5.0):
  652. async with current_lock:
  653. pass # Lock acquired means previous holder released it
  654. logger.info("Pattern lock released normally")
  655. except asyncio.TimeoutError:
  656. logger.warning("Timed out waiting for pattern lock - creating fresh lock")
  657. except Exception as e:
  658. logger.error(f"Error waiting for pattern lock: {e}")
  659. # Clean up pause event - wake up any waiting tasks, then create fresh event
  660. current_event = pause_event
  661. if current_event:
  662. try:
  663. current_event.set() # Wake up any waiting tasks
  664. except Exception as e:
  665. logger.error(f"Error setting pause event: {e}")
  666. # Clean up pause condition from state
  667. if state.pause_condition:
  668. try:
  669. with state.pause_condition:
  670. state.pause_condition.notify_all()
  671. state.pause_condition = threading.Condition()
  672. except Exception as e:
  673. logger.error(f"Error cleaning up pause condition: {e}")
  674. # Clear all state variables
  675. state.current_playing_file = None
  676. state.execution_progress = 0
  677. state.is_running = False
  678. state.pause_requested = False
  679. state.stop_requested = True
  680. state.is_clearing = False
  681. # Reset machine position
  682. await connection_manager.update_machine_position()
  683. logger.info("Pattern manager resources cleaned up")
  684. except Exception as e:
  685. logger.error(f"Error during pattern manager cleanup: {e}")
  686. finally:
  687. # Reset to fresh instances instead of None to allow continued operation
  688. progress_update_task = None
  689. pattern_lock = asyncio.Lock() # Fresh lock instead of None
  690. pause_event = asyncio.Event() # Fresh event instead of None
  691. pause_event.set() # Initially not paused
  692. def list_theta_rho_files():
  693. files = []
  694. for root, dirs, filenames in os.walk(THETA_RHO_DIR):
  695. # Skip cached_images directories to avoid scanning thousands of WebP files
  696. if 'cached_images' in dirs:
  697. dirs.remove('cached_images')
  698. # Filter .thr files during traversal for better performance
  699. thr_files = [f for f in filenames if f.endswith('.thr')]
  700. for file in thr_files:
  701. relative_path = os.path.relpath(os.path.join(root, file), THETA_RHO_DIR)
  702. # Normalize path separators to always use forward slashes for consistency across platforms
  703. relative_path = relative_path.replace(os.sep, '/')
  704. files.append(relative_path)
  705. logger.debug(f"Found {len(files)} theta-rho files")
  706. return files
  707. def parse_theta_rho_file(file_path):
  708. """Parse a theta-rho file and return a list of (theta, rho) pairs."""
  709. coordinates = []
  710. try:
  711. logger.debug(f"Parsing theta-rho file: {file_path}")
  712. with open(file_path, 'r', encoding='utf-8') as file:
  713. for line in file:
  714. line = line.strip()
  715. if not line or line.startswith("#"):
  716. continue
  717. try:
  718. theta, rho = map(float, line.split())
  719. coordinates.append((theta, rho))
  720. except ValueError:
  721. logger.warning(f"Skipping invalid line: {line}")
  722. continue
  723. except Exception as e:
  724. logger.error(f"Error reading file: {e}")
  725. return coordinates
  726. logger.debug(f"Parsed {len(coordinates)} coordinates from {file_path}")
  727. return coordinates
  728. def get_first_rho_from_cache(file_path, cache_data=None):
  729. """Get the first rho value from cached metadata, falling back to file parsing if needed.
  730. Args:
  731. file_path: Path to the pattern file
  732. cache_data: Optional pre-loaded cache data dict to avoid repeated disk I/O
  733. """
  734. try:
  735. # Import cache_manager locally to avoid circular import
  736. from modules.core import cache_manager
  737. # Try to get from metadata cache first
  738. # Use relative path from THETA_RHO_DIR to match cache keys (which include subdirectories)
  739. file_name = os.path.relpath(file_path, THETA_RHO_DIR)
  740. # Use provided cache_data if available, otherwise load from disk
  741. if cache_data is not None:
  742. # Extract metadata directly from provided cache
  743. data_section = cache_data.get('data', {})
  744. if file_name in data_section:
  745. cached_entry = data_section[file_name]
  746. metadata = cached_entry.get('metadata')
  747. # When cache_data is provided, trust it without checking mtime
  748. # This significantly speeds up bulk operations (playlists with 1000+ patterns)
  749. # by avoiding 1000+ os.path.getmtime() calls on slow storage (e.g., Pi SD cards)
  750. if metadata and 'first_coordinate' in metadata:
  751. return metadata['first_coordinate']['y']
  752. else:
  753. # Fall back to loading cache from disk (original behavior)
  754. metadata = cache_manager.get_pattern_metadata(file_name)
  755. if metadata and 'first_coordinate' in metadata:
  756. # In the cache, 'x' is theta and 'y' is rho
  757. return metadata['first_coordinate']['y']
  758. # Fallback to parsing the file if not in cache
  759. logger.debug(f"Metadata not cached for {file_name}, parsing file")
  760. coordinates = parse_theta_rho_file(file_path)
  761. if coordinates:
  762. return coordinates[0][1] # Return rho value
  763. return None
  764. except Exception as e:
  765. logger.warning(f"Error getting first rho from cache for {file_path}: {str(e)}")
  766. return None
  767. def get_clear_pattern_file(clear_pattern_mode, path=None, cache_data=None):
  768. """Return a .thr file path based on pattern_name and table type.
  769. Args:
  770. clear_pattern_mode: The clear pattern mode to use
  771. path: Optional path to the pattern file for adaptive mode
  772. cache_data: Optional pre-loaded cache data dict to avoid repeated disk I/O
  773. """
  774. if not clear_pattern_mode or clear_pattern_mode == 'none':
  775. return
  776. # Define patterns for each table type
  777. clear_patterns = {
  778. 'dune_weaver': {
  779. 'clear_from_out': './patterns/clear_from_out.thr',
  780. 'clear_from_in': './patterns/clear_from_in.thr',
  781. 'clear_sideway': './patterns/clear_sideway.thr'
  782. },
  783. 'dune_weaver_mini': {
  784. 'clear_from_out': './patterns/clear_from_out_mini.thr',
  785. 'clear_from_in': './patterns/clear_from_in_mini.thr',
  786. 'clear_sideway': './patterns/clear_sideway_mini.thr'
  787. },
  788. 'dune_weaver_mini_pro': {
  789. 'clear_from_out': './patterns/clear_from_out_mini.thr',
  790. 'clear_from_in': './patterns/clear_from_in_mini.thr',
  791. 'clear_sideway': './patterns/clear_sideway_mini.thr'
  792. },
  793. 'dune_weaver_pro': {
  794. 'clear_from_out': './patterns/clear_from_out_pro.thr',
  795. 'clear_from_out_Ultra': './patterns/clear_from_out_Ultra.thr',
  796. 'clear_from_in': './patterns/clear_from_in_pro.thr',
  797. 'clear_from_in_Ultra': './patterns/clear_from_in_Ultra.thr',
  798. 'clear_sideway': './patterns/clear_sideway_pro.thr'
  799. }
  800. }
  801. # Get patterns for current table type, fallback to standard patterns if type not found
  802. table_patterns = clear_patterns.get(state.table_type, clear_patterns['dune_weaver'])
  803. # Check for custom patterns first
  804. if state.custom_clear_from_out and clear_pattern_mode in ['clear_from_out', 'adaptive']:
  805. if clear_pattern_mode == 'adaptive':
  806. # For adaptive mode, use cached metadata to check first rho
  807. if path:
  808. first_rho = get_first_rho_from_cache(path, cache_data)
  809. if first_rho is not None and first_rho < 0.5:
  810. # Use custom clear_from_out if set
  811. custom_path = os.path.join('./patterns', state.custom_clear_from_out)
  812. if os.path.exists(custom_path):
  813. logger.debug(f"Using custom clear_from_out: {custom_path}")
  814. return custom_path
  815. elif clear_pattern_mode == 'clear_from_out':
  816. custom_path = os.path.join('./patterns', state.custom_clear_from_out)
  817. if os.path.exists(custom_path):
  818. logger.debug(f"Using custom clear_from_out: {custom_path}")
  819. return custom_path
  820. if state.custom_clear_from_in and clear_pattern_mode in ['clear_from_in', 'adaptive']:
  821. if clear_pattern_mode == 'adaptive':
  822. # For adaptive mode, use cached metadata to check first rho
  823. if path:
  824. first_rho = get_first_rho_from_cache(path, cache_data)
  825. if first_rho is not None and first_rho >= 0.5:
  826. # Use custom clear_from_in if set
  827. custom_path = os.path.join('./patterns', state.custom_clear_from_in)
  828. if os.path.exists(custom_path):
  829. logger.debug(f"Using custom clear_from_in: {custom_path}")
  830. return custom_path
  831. elif clear_pattern_mode == 'clear_from_in':
  832. custom_path = os.path.join('./patterns', state.custom_clear_from_in)
  833. if os.path.exists(custom_path):
  834. logger.debug(f"Using custom clear_from_in: {custom_path}")
  835. return custom_path
  836. logger.debug(f"Clear pattern mode: {clear_pattern_mode} for table type: {state.table_type}")
  837. if clear_pattern_mode == "random":
  838. return random.choice(list(table_patterns.values()))
  839. if clear_pattern_mode == 'adaptive':
  840. if not path:
  841. logger.warning("No path provided for adaptive clear pattern")
  842. return random.choice(list(table_patterns.values()))
  843. # Use cached metadata to get first rho value
  844. first_rho = get_first_rho_from_cache(path, cache_data)
  845. if first_rho is None:
  846. logger.warning("Could not determine first rho value for adaptive clear pattern")
  847. return random.choice(list(table_patterns.values()))
  848. if first_rho < 0.5:
  849. return table_patterns['clear_from_out']
  850. else:
  851. return table_patterns['clear_from_in']
  852. else:
  853. if clear_pattern_mode not in table_patterns:
  854. return False
  855. return table_patterns[clear_pattern_mode]
  856. def is_clear_pattern(file_path):
  857. """Check if a file path is a clear pattern file."""
  858. # Get all possible clear pattern files for all table types
  859. clear_patterns = []
  860. for table_type in ['dune_weaver', 'dune_weaver_mini', 'dune_weaver_pro']:
  861. clear_patterns.extend([
  862. f'./patterns/clear_from_out{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr',
  863. f'./patterns/clear_from_in{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr',
  864. f'./patterns/clear_sideway{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr'
  865. ])
  866. # Normalize paths for comparison
  867. normalized_path = os.path.normpath(file_path)
  868. normalized_clear_patterns = [os.path.normpath(p) for p in clear_patterns]
  869. # Check if the file path matches any clear pattern path
  870. return normalized_path in normalized_clear_patterns
  871. async def _execute_pattern_internal(file_path):
  872. """Internal function to execute a pattern file. Must be called with lock already held.
  873. Args:
  874. file_path: Path to the .thr file to execute
  875. Returns:
  876. True if pattern completed successfully, False if stopped/skipped
  877. """
  878. # Run file parsing in thread to avoid blocking the event loop
  879. coordinates = await asyncio.to_thread(parse_theta_rho_file, file_path)
  880. total_coordinates = len(coordinates)
  881. # Cache coordinates in state for frontend preview (avoids re-parsing large files)
  882. state._current_coordinates = coordinates
  883. if total_coordinates < 2:
  884. logger.warning("Not enough coordinates for interpolation")
  885. return False
  886. # Determine if this is a clearing pattern
  887. is_clear_file = is_clear_pattern(file_path)
  888. if is_clear_file:
  889. initial_speed = state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  890. logger.info(f"Running clearing pattern at initial speed {initial_speed}")
  891. else:
  892. logger.info(f"Running normal pattern at initial speed {state.speed}")
  893. state.execution_progress = (0, total_coordinates, None, 0)
  894. # stop actions without resetting the playlist, and don't wait for lock (we already have it)
  895. # Preserve is_clearing flag since stop_actions resets it
  896. was_clearing = state.is_clearing
  897. await stop_actions(clear_playlist=False, wait_for_lock=False)
  898. state.is_clearing = was_clearing
  899. state.current_playing_file = file_path
  900. state.stop_requested = False
  901. # Reset LED idle timeout activity time when pattern starts
  902. import time as time_module
  903. state.dw_led_last_activity_time = time_module.time()
  904. logger.info(f"Starting pattern execution: {file_path}")
  905. logger.info(f"t: {state.current_theta}, r: {state.current_rho}")
  906. await reset_theta()
  907. start_time = time.time()
  908. total_pause_time = 0 # Track total time spent paused (manual + scheduled)
  909. if state.led_controller:
  910. logger.info(f"Setting LED to playing effect: {state.dw_led_playing_effect}")
  911. await state.led_controller.effect_playing_async(state.dw_led_playing_effect)
  912. # Cancel idle timeout when playing starts
  913. idle_timeout_manager.cancel_timeout()
  914. with tqdm(
  915. total=total_coordinates,
  916. unit="coords",
  917. desc=f"Executing Pattern {file_path}",
  918. dynamic_ncols=True,
  919. disable=False,
  920. mininterval=1.0
  921. ) as pbar:
  922. for i, coordinate in enumerate(coordinates):
  923. theta, rho = coordinate
  924. if state.stop_requested:
  925. logger.info("Execution stopped by user")
  926. if state.led_controller:
  927. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  928. start_idle_led_timeout()
  929. break
  930. if state.skip_requested:
  931. logger.info("Skipping pattern...")
  932. await connection_manager.check_idle_async()
  933. if state.led_controller:
  934. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  935. start_idle_led_timeout()
  936. break
  937. # Wait for resume if paused (manual or scheduled)
  938. manual_pause = state.pause_requested
  939. # Only check scheduled pause during pattern if "finish pattern first" is NOT enabled
  940. scheduled_pause = is_in_scheduled_pause_period() if not state.scheduled_pause_finish_pattern else False
  941. if manual_pause or scheduled_pause:
  942. pause_start = time.time() # Track when pause started
  943. if manual_pause and scheduled_pause:
  944. logger.info("Execution paused (manual + scheduled pause active)...")
  945. elif manual_pause:
  946. logger.info("Execution paused (manual)...")
  947. else:
  948. logger.info("Execution paused (scheduled pause period)...")
  949. # Turn off LED controller if scheduled pause and control_wled is enabled
  950. if state.scheduled_pause_control_wled and state.led_controller:
  951. logger.info("Turning off LED lights during Still Sands period")
  952. await state.led_controller.set_power_async(0)
  953. # Only show idle effect if NOT in scheduled pause with LED control
  954. # (manual pause always shows idle effect)
  955. if state.led_controller and not (scheduled_pause and state.scheduled_pause_control_wled):
  956. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  957. start_idle_led_timeout()
  958. # Remember if we turned off LED controller for scheduled pause
  959. wled_was_off_for_scheduled = scheduled_pause and state.scheduled_pause_control_wled and not manual_pause
  960. # Wait until both manual pause is released AND we're outside scheduled pause period
  961. # Also check for stop/skip requests to allow immediate interruption
  962. interrupted = False
  963. while state.pause_requested or is_in_scheduled_pause_period():
  964. # Check for stop/skip first
  965. if state.stop_requested:
  966. logger.info("Stop requested during pause, exiting")
  967. interrupted = True
  968. break
  969. if state.skip_requested:
  970. logger.info("Skip requested during pause, skipping pattern")
  971. interrupted = True
  972. break
  973. if state.pause_requested:
  974. # For manual pause, wait on multiple events for immediate response
  975. # Wake on: resume, stop, skip, or timeout (for flag polling fallback)
  976. pause_event = get_pause_event()
  977. stop_event = state.get_stop_event()
  978. skip_event = state.get_skip_event()
  979. wait_tasks = [asyncio.create_task(pause_event.wait(), name='pause')]
  980. if stop_event:
  981. wait_tasks.append(asyncio.create_task(stop_event.wait(), name='stop'))
  982. if skip_event:
  983. wait_tasks.append(asyncio.create_task(skip_event.wait(), name='skip'))
  984. # Add timeout to ensure we periodically check flags even if events aren't set
  985. # This handles the case where stop is called from sync context (no event loop)
  986. timeout_task = asyncio.create_task(asyncio.sleep(1.0), name='timeout')
  987. wait_tasks.append(timeout_task)
  988. try:
  989. done, pending = await asyncio.wait(
  990. wait_tasks, return_when=asyncio.FIRST_COMPLETED
  991. )
  992. finally:
  993. for task in pending:
  994. task.cancel()
  995. for task in pending:
  996. try:
  997. await task
  998. except asyncio.CancelledError:
  999. pass
  1000. else:
  1001. # For scheduled pause, use wait_for_interrupt for instant response
  1002. result = await state.wait_for_interrupt(timeout=1.0)
  1003. if result in ('stopped', 'skipped'):
  1004. interrupted = True
  1005. break
  1006. total_pause_time += time.time() - pause_start # Add pause duration
  1007. if interrupted:
  1008. # Exit the coordinate loop if we were interrupted
  1009. break
  1010. logger.info("Execution resumed...")
  1011. if state.led_controller:
  1012. # Turn LED controller back on if it was turned off for scheduled pause
  1013. if wled_was_off_for_scheduled:
  1014. logger.info("Turning LED lights back on as Still Sands period ended")
  1015. await state.led_controller.set_power_async(1)
  1016. # CRITICAL: Give LED controller time to fully power on before sending more commands
  1017. # Without this delay, rapid-fire requests can crash controllers on resource-constrained Pis
  1018. await asyncio.sleep(0.5)
  1019. await state.led_controller.effect_playing_async(state.dw_led_playing_effect)
  1020. # Cancel idle timeout when resuming from pause
  1021. idle_timeout_manager.cancel_timeout()
  1022. # Dynamically determine the speed for each movement
  1023. # Use clear_pattern_speed if it's set and this is a clear file, otherwise use state.speed
  1024. if is_clear_file and state.clear_pattern_speed is not None:
  1025. current_speed = state.clear_pattern_speed
  1026. else:
  1027. current_speed = state.speed
  1028. await move_polar(theta, rho, current_speed)
  1029. # Update progress for all coordinates including the first one
  1030. pbar.update(1)
  1031. elapsed_time = time.time() - start_time
  1032. estimated_remaining_time = (total_coordinates - (i + 1)) / pbar.format_dict['rate'] if pbar.format_dict['rate'] and total_coordinates else 0
  1033. state.execution_progress = (i + 1, total_coordinates, estimated_remaining_time, elapsed_time)
  1034. # Add a small delay to allow other async operations
  1035. await asyncio.sleep(0.001)
  1036. # Update progress one last time to show 100%
  1037. elapsed_time = time.time() - start_time
  1038. actual_execution_time = elapsed_time - total_pause_time
  1039. state.execution_progress = (total_coordinates, total_coordinates, 0, elapsed_time)
  1040. # Give WebSocket a chance to send the final update
  1041. await asyncio.sleep(0.1)
  1042. # Log execution time (only for completed patterns, not stopped/skipped)
  1043. was_completed = not state.stop_requested and not state.skip_requested
  1044. pattern_name = os.path.basename(file_path)
  1045. effective_speed = state.clear_pattern_speed if (is_clear_file and state.clear_pattern_speed is not None) else state.speed
  1046. log_execution_time(
  1047. pattern_name=pattern_name,
  1048. table_type=state.table_type,
  1049. speed=effective_speed,
  1050. actual_time=actual_execution_time,
  1051. total_coordinates=total_coordinates,
  1052. was_completed=was_completed
  1053. )
  1054. if not state.conn:
  1055. logger.error("Device is not connected. Stopping pattern execution.")
  1056. return False
  1057. await connection_manager.check_idle_async()
  1058. # Set LED back to idle when pattern completes normally (not stopped early)
  1059. if state.led_controller and not state.stop_requested:
  1060. logger.info(f"Setting LED to idle effect: {state.dw_led_idle_effect}")
  1061. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  1062. start_idle_led_timeout()
  1063. logger.debug("LED effect set to idle after pattern completion")
  1064. return was_completed
  1065. async def run_theta_rho_file(file_path, is_playlist=False, clear_pattern=None, cache_data=None):
  1066. """Run a theta-rho file with optional pre-execution clear pattern.
  1067. Args:
  1068. file_path: Path to the main .thr file to execute
  1069. is_playlist: True if running as part of a playlist
  1070. clear_pattern: Clear pattern mode ('adaptive', 'clear_from_in', 'clear_from_out', 'none', or None)
  1071. cache_data: Pre-loaded metadata cache for adaptive clear pattern selection
  1072. """
  1073. lock = get_pattern_lock()
  1074. if lock.locked():
  1075. logger.warning("Another pattern is already running. Cannot start a new one.")
  1076. return
  1077. async with lock: # This ensures only one pattern can run at a time
  1078. # Clear any stale pause state from previous playlist
  1079. state.pause_time_remaining = 0
  1080. state.original_pause_time = None
  1081. # Start progress update task only if not part of a playlist
  1082. global progress_update_task
  1083. if not is_playlist and not progress_update_task:
  1084. progress_update_task = asyncio.create_task(broadcast_progress())
  1085. # Run clear pattern first if specified
  1086. if clear_pattern and clear_pattern != 'none':
  1087. clear_file_path = get_clear_pattern_file(clear_pattern, file_path, cache_data)
  1088. if clear_file_path:
  1089. logger.info(f"Running pre-execution clear pattern: {clear_file_path}")
  1090. state.is_clearing = True
  1091. await _execute_pattern_internal(clear_file_path)
  1092. state.is_clearing = False
  1093. # Reset skip flag after clear pattern (if user skipped clear, continue to main)
  1094. state.skip_requested = False
  1095. # Check if stopped during clear pattern
  1096. if state.stop_requested:
  1097. logger.info("Execution stopped during clear pattern")
  1098. if not is_playlist:
  1099. state.current_playing_file = None
  1100. state.execution_progress = None
  1101. return
  1102. # Run the main pattern
  1103. completed = await _execute_pattern_internal(file_path)
  1104. # Only clear state if not part of a playlist
  1105. if not is_playlist:
  1106. state.current_playing_file = None
  1107. state.execution_progress = None
  1108. logger.info("Pattern execution completed and state cleared")
  1109. # Only cancel progress update task if not part of a playlist
  1110. if progress_update_task:
  1111. progress_update_task.cancel()
  1112. try:
  1113. await progress_update_task
  1114. except asyncio.CancelledError:
  1115. pass
  1116. progress_update_task = None
  1117. else:
  1118. logger.info("Pattern execution completed, maintaining state for playlist")
  1119. async def run_theta_rho_files(file_paths, pause_time=0, clear_pattern=None, run_mode="single", shuffle=False):
  1120. """Run multiple .thr files in sequence with options.
  1121. The playlist now stores only main patterns. Clear patterns are executed dynamically
  1122. before each main pattern based on the clear_pattern option.
  1123. """
  1124. state.stop_requested = False
  1125. # Reset LED idle timeout activity time when playlist starts
  1126. import time as time_module
  1127. state.dw_led_last_activity_time = time_module.time()
  1128. # Set initial playlist state
  1129. state.playlist_mode = run_mode
  1130. state.current_playlist_index = 0
  1131. # Start progress update task for the playlist
  1132. global progress_update_task
  1133. if not progress_update_task:
  1134. progress_update_task = asyncio.create_task(broadcast_progress())
  1135. # Shuffle main patterns if requested (before starting)
  1136. if shuffle:
  1137. random.shuffle(file_paths)
  1138. logger.info("Playlist shuffled")
  1139. # Store only main patterns in the playlist
  1140. state.current_playlist = file_paths
  1141. try:
  1142. while True:
  1143. # Load metadata cache once per playlist iteration (for adaptive clear patterns)
  1144. cache_data = None
  1145. if clear_pattern and clear_pattern in ['adaptive', 'clear_from_in', 'clear_from_out']:
  1146. from modules.core import cache_manager
  1147. cache_data = await asyncio.to_thread(cache_manager.load_metadata_cache)
  1148. logger.info(f"Loaded metadata cache for {len(cache_data.get('data', {}))} patterns")
  1149. # Reset pattern counter at the start of the playlist
  1150. state.patterns_since_last_home = 0
  1151. # Execute main patterns using index-based access
  1152. # This allows the playlist to be reordered during execution
  1153. idx = 0
  1154. while state.current_playlist and idx < len(state.current_playlist):
  1155. state.current_playlist_index = idx
  1156. if state.stop_requested or not state.current_playlist:
  1157. logger.info("Execution stopped")
  1158. return
  1159. # Get the pattern at the current index (may have changed due to reordering)
  1160. file_path = state.current_playlist[idx]
  1161. logger.info(f"Running pattern {idx + 1}/{len(state.current_playlist)}: {file_path}")
  1162. # Clear pause state when starting a new pattern (prevents stale "waiting" UI)
  1163. state.pause_time_remaining = 0
  1164. state.original_pause_time = None
  1165. # Execute the pattern with optional clear pattern
  1166. await run_theta_rho_file(
  1167. file_path,
  1168. is_playlist=True,
  1169. clear_pattern=clear_pattern,
  1170. cache_data=cache_data
  1171. )
  1172. # Increment pattern counter (auto-home check happens after pause time)
  1173. state.patterns_since_last_home += 1
  1174. logger.debug(f"Patterns since last home: {state.patterns_since_last_home}")
  1175. # Check for scheduled pause after pattern completes (when "finish pattern first" is enabled)
  1176. if state.scheduled_pause_finish_pattern and is_in_scheduled_pause_period() and not state.stop_requested and not state.skip_requested:
  1177. logger.info("Pattern completed. Entering Still Sands period (finish pattern first mode)...")
  1178. wled_was_off_for_scheduled = False
  1179. if state.scheduled_pause_control_wled and state.led_controller:
  1180. logger.info("Turning off LED lights during Still Sands period")
  1181. await state.led_controller.set_power_async(0)
  1182. wled_was_off_for_scheduled = True
  1183. elif state.led_controller:
  1184. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  1185. start_idle_led_timeout()
  1186. # Wait for scheduled pause to end, but allow stop/skip to interrupt
  1187. result = await wait_with_interrupt(
  1188. is_in_scheduled_pause_period,
  1189. check_stop=True,
  1190. check_skip=True,
  1191. )
  1192. if result == 'completed':
  1193. logger.info("Still Sands period ended. Resuming playlist...")
  1194. if state.led_controller:
  1195. if wled_was_off_for_scheduled:
  1196. logger.info("Turning LED lights back on as Still Sands period ended")
  1197. await state.led_controller.set_power_async(1)
  1198. await asyncio.sleep(0.5)
  1199. await state.led_controller.effect_playing_async(state.dw_led_playing_effect)
  1200. idle_timeout_manager.cancel_timeout()
  1201. # Handle pause between patterns
  1202. 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:
  1203. logger.info(f"Pausing for {pause_time} seconds")
  1204. state.original_pause_time = pause_time
  1205. pause_start = time.time()
  1206. while time.time() - pause_start < pause_time:
  1207. state.pause_time_remaining = pause_start + pause_time - time.time()
  1208. if state.skip_requested:
  1209. logger.info("Pause interrupted by skip request")
  1210. break
  1211. await asyncio.sleep(1)
  1212. # Clear both pause state vars immediately (so UI updates right away)
  1213. state.pause_time_remaining = 0
  1214. state.original_pause_time = None
  1215. # Auto-home after pause time, before next clear pattern starts
  1216. # Only home if there's a next pattern and we haven't been stopped
  1217. if (state.auto_home_enabled and
  1218. state.patterns_since_last_home >= state.auto_home_after_patterns and
  1219. state.current_playlist and idx < len(state.current_playlist) - 1 and
  1220. not state.stop_requested):
  1221. logger.info(f"Auto-homing triggered after {state.patterns_since_last_home} patterns (before next clear pattern)")
  1222. try:
  1223. success = await asyncio.to_thread(connection_manager.home)
  1224. if success:
  1225. logger.info("Auto-homing completed successfully")
  1226. state.patterns_since_last_home = 0
  1227. else:
  1228. logger.warning("Auto-homing failed, continuing with playlist")
  1229. except Exception as e:
  1230. logger.error(f"Error during auto-homing: {e}")
  1231. state.skip_requested = False
  1232. idx += 1
  1233. if run_mode == "indefinite":
  1234. logger.info("Playlist completed. Restarting as per 'indefinite' run mode")
  1235. if pause_time > 0:
  1236. pause_start = time.time()
  1237. while time.time() - pause_start < pause_time:
  1238. state.pause_time_remaining = pause_start + pause_time - time.time()
  1239. if state.skip_requested:
  1240. logger.info("Pause interrupted by skip request")
  1241. break
  1242. await asyncio.sleep(1)
  1243. # Clear both pause state vars immediately (so UI updates right away)
  1244. state.pause_time_remaining = 0
  1245. state.original_pause_time = None
  1246. continue
  1247. else:
  1248. logger.info("Playlist completed")
  1249. break
  1250. finally:
  1251. if progress_update_task:
  1252. progress_update_task.cancel()
  1253. try:
  1254. await progress_update_task
  1255. except asyncio.CancelledError:
  1256. pass
  1257. progress_update_task = None
  1258. state.current_playing_file = None
  1259. state.execution_progress = None
  1260. state.current_playlist = None
  1261. state.current_playlist_index = None
  1262. state.playlist_mode = None
  1263. state.pause_time_remaining = 0
  1264. if state.led_controller:
  1265. await state.led_controller.effect_idle_async(state.dw_led_idle_effect)
  1266. start_idle_led_timeout()
  1267. logger.info("All requested patterns completed (or stopped) and state cleared")
  1268. async def stop_actions(clear_playlist = True, wait_for_lock = True):
  1269. """Stop all current actions and wait for pattern to fully release.
  1270. Args:
  1271. clear_playlist: Whether to clear playlist state
  1272. wait_for_lock: Whether to wait for pattern_lock to be released. Set to False when
  1273. called from within pattern execution to avoid deadlock.
  1274. Returns:
  1275. True if stopped cleanly, False if timed out waiting for pattern lock
  1276. """
  1277. timed_out = False
  1278. try:
  1279. with state.pause_condition:
  1280. state.pause_requested = False
  1281. state.stop_requested = True
  1282. state.is_clearing = False
  1283. # Always clear pause time between patterns on stop
  1284. state.pause_time_remaining = 0
  1285. state.original_pause_time = None
  1286. if clear_playlist:
  1287. # Clear playlist state
  1288. state.current_playlist = None
  1289. state.current_playlist_index = None
  1290. state.playlist_mode = None
  1291. # Cancel progress update task if we're clearing the playlist
  1292. global progress_update_task
  1293. if progress_update_task and not progress_update_task.done():
  1294. progress_update_task.cancel()
  1295. # Cancel the playlist task itself (late import to avoid circular dependency)
  1296. from modules.core import playlist_manager
  1297. await playlist_manager.cancel_current_playlist()
  1298. state.pause_condition.notify_all()
  1299. # Also set the pause event to wake up any paused patterns
  1300. get_pause_event().set()
  1301. # Send stop command to motion thread to clear its queue
  1302. if motion_controller.running:
  1303. motion_controller.command_queue.put(MotionCommand('stop'))
  1304. # Wait for the pattern lock to be released before continuing
  1305. # This ensures that when stop_actions completes, the pattern has fully stopped
  1306. # Skip this if called from within pattern execution to avoid deadlock
  1307. lock = get_pattern_lock()
  1308. if wait_for_lock and lock.locked():
  1309. logger.info("Waiting for pattern to fully stop...")
  1310. # Use a timeout to prevent hanging forever
  1311. try:
  1312. async with asyncio.timeout(10.0):
  1313. async with lock:
  1314. logger.info("Pattern lock acquired - pattern has fully stopped")
  1315. except asyncio.TimeoutError:
  1316. logger.warning("Timeout waiting for pattern to stop - forcing cleanup")
  1317. timed_out = True
  1318. # Force cleanup of state even if pattern didn't release lock gracefully
  1319. state.current_playing_file = None
  1320. state.execution_progress = None
  1321. state.is_running = False
  1322. # Always clear the current playing file after stop
  1323. state.current_playing_file = None
  1324. state.execution_progress = None
  1325. # Call async function directly since we're in async context
  1326. await connection_manager.update_machine_position()
  1327. return not timed_out
  1328. except Exception as e:
  1329. logger.error(f"Error during stop_actions: {e}")
  1330. # Force cleanup state on error
  1331. state.current_playing_file = None
  1332. state.execution_progress = None
  1333. state.is_running = False
  1334. # Ensure we still update machine position even if there's an error
  1335. try:
  1336. await connection_manager.update_machine_position()
  1337. except Exception as update_err:
  1338. logger.error(f"Error updating machine position on error: {update_err}")
  1339. return False
  1340. async def move_polar(theta, rho, speed=None):
  1341. """
  1342. Queue a motion command to be executed in the dedicated motion control thread.
  1343. This makes motion control non-blocking for API endpoints.
  1344. Args:
  1345. theta (float): Target theta coordinate
  1346. rho (float): Target rho coordinate
  1347. speed (int, optional): Speed override. If None, uses state.speed
  1348. """
  1349. # Note: stop_requested is cleared once at pattern start (execute_theta_rho_file line 890)
  1350. # Don't clear it here on every coordinate - causes performance issues with event system
  1351. # Ensure motion control thread is running
  1352. if not motion_controller.running:
  1353. motion_controller.start()
  1354. # Create future for async/await pattern
  1355. loop = asyncio.get_event_loop()
  1356. future = loop.create_future()
  1357. # Create and queue motion command
  1358. command = MotionCommand(
  1359. command_type='move',
  1360. theta=theta,
  1361. rho=rho,
  1362. speed=speed,
  1363. future=future
  1364. )
  1365. motion_controller.command_queue.put(command)
  1366. logger.debug(f"Queued motion command: theta={theta}, rho={rho}, speed={speed}")
  1367. # Wait for command completion
  1368. await future
  1369. def pause_execution():
  1370. """Pause pattern execution using asyncio Event."""
  1371. logger.info("Pausing pattern execution")
  1372. state.pause_requested = True
  1373. get_pause_event().clear() # Clear the event to pause execution
  1374. return True
  1375. def resume_execution():
  1376. """Resume pattern execution using asyncio Event."""
  1377. logger.info("Resuming pattern execution")
  1378. state.pause_requested = False
  1379. get_pause_event().set() # Set the event to resume execution
  1380. return True
  1381. async def reset_theta():
  1382. logger.info('Resetting Theta')
  1383. state.current_theta = state.current_theta % (2 * pi)
  1384. # Call async function directly since we're in async context
  1385. await connection_manager.update_machine_position()
  1386. def set_speed(new_speed):
  1387. state.speed = new_speed
  1388. logger.info(f'Set new state.speed {new_speed}')
  1389. def get_status():
  1390. """Get the current status of pattern execution."""
  1391. status = {
  1392. "current_file": state.current_playing_file,
  1393. "is_paused": state.pause_requested or is_in_scheduled_pause_period(),
  1394. "manual_pause": state.pause_requested,
  1395. "scheduled_pause": is_in_scheduled_pause_period(),
  1396. "is_running": bool(state.current_playing_file and not state.stop_requested),
  1397. "is_homing": state.is_homing,
  1398. "is_clearing": state.is_clearing,
  1399. "progress": None,
  1400. "playlist": None,
  1401. "speed": state.speed,
  1402. "pause_time_remaining": state.pause_time_remaining,
  1403. "original_pause_time": getattr(state, 'original_pause_time', None),
  1404. "connection_status": state.conn.is_connected() if state.conn else False,
  1405. "current_theta": state.current_theta,
  1406. "current_rho": state.current_rho
  1407. }
  1408. # Add playlist information if available
  1409. if state.current_playlist and state.current_playlist_index is not None:
  1410. # When a clear pattern is running, the "next" pattern is the current main pattern
  1411. # (since the clear pattern runs before the main pattern at current_playlist_index)
  1412. if state.is_clearing:
  1413. next_file = state.current_playlist[state.current_playlist_index]
  1414. else:
  1415. next_index = state.current_playlist_index + 1
  1416. next_file = state.current_playlist[next_index] if next_index < len(state.current_playlist) else None
  1417. status["playlist"] = {
  1418. "current_index": state.current_playlist_index,
  1419. "total_files": len(state.current_playlist),
  1420. "mode": state.playlist_mode,
  1421. "next_file": next_file,
  1422. "files": state.current_playlist,
  1423. "name": state.current_playlist_name
  1424. }
  1425. if state.execution_progress:
  1426. current, total, remaining_time, elapsed_time = state.execution_progress
  1427. status["progress"] = {
  1428. "current": current,
  1429. "total": total,
  1430. "remaining_time": remaining_time,
  1431. "elapsed_time": elapsed_time,
  1432. "percentage": (current / total * 100) if total > 0 else 0
  1433. }
  1434. # Add historical execution time if available for this pattern at current speed
  1435. if state.current_playing_file:
  1436. pattern_name = os.path.basename(state.current_playing_file)
  1437. historical_time = get_last_completed_execution_time(pattern_name, state.speed)
  1438. if historical_time:
  1439. status["progress"]["last_completed_time"] = historical_time
  1440. return status
  1441. async def broadcast_progress():
  1442. """Background task to broadcast progress updates."""
  1443. from main import broadcast_status_update
  1444. while True:
  1445. # Send status updates regardless of pattern_lock state
  1446. status = get_status()
  1447. # Use the existing broadcast function from main.py
  1448. await broadcast_status_update(status)
  1449. # Check if we should stop broadcasting
  1450. if not state.current_playlist:
  1451. # If no playlist, only stop if no pattern is being executed
  1452. if not get_pattern_lock().locked():
  1453. logger.info("No playlist or pattern running, stopping broadcast")
  1454. break
  1455. # Wait before next update
  1456. await asyncio.sleep(1)