1
0

pattern_manager.py 59 KB

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