pattern_manager.py 64 KB

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