pattern_manager.py 56 KB

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