pattern_manager.py 54 KB

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