pattern_manager.py 57 KB

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