pattern_manager.py 55 KB

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