1
0

pattern_manager.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039
  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. import queue
  17. from dataclasses import dataclass
  18. from typing import Optional, Callable
  19. # Configure logging
  20. logger = logging.getLogger(__name__)
  21. # Global state
  22. THETA_RHO_DIR = './patterns'
  23. os.makedirs(THETA_RHO_DIR, exist_ok=True)
  24. # Create an asyncio Event for pause/resume
  25. pause_event = asyncio.Event()
  26. pause_event.set() # Initially not paused
  27. # Create an asyncio Lock for pattern execution
  28. pattern_lock = asyncio.Lock()
  29. # Progress update task
  30. progress_update_task = None
  31. # Cache timezone at module level - read once per session
  32. _cached_timezone = None
  33. _cached_zoneinfo = None
  34. def _get_system_timezone():
  35. """Get and cache the system timezone. Called once per session."""
  36. global _cached_timezone, _cached_zoneinfo
  37. if _cached_timezone is not None:
  38. return _cached_zoneinfo
  39. user_tz = 'UTC' # Default fallback
  40. # Try to read timezone from /etc/host-timezone (mounted from host)
  41. try:
  42. if os.path.exists('/etc/host-timezone'):
  43. with open('/etc/host-timezone', 'r') as f:
  44. user_tz = f.read().strip()
  45. logger.info(f"Still Sands using timezone: {user_tz} (from host system)")
  46. # Fallback to /etc/timezone if host-timezone doesn't exist
  47. elif os.path.exists('/etc/timezone'):
  48. with open('/etc/timezone', 'r') as f:
  49. user_tz = f.read().strip()
  50. logger.info(f"Still Sands using timezone: {user_tz} (from container)")
  51. # Fallback to TZ environment variable
  52. elif os.environ.get('TZ'):
  53. user_tz = os.environ.get('TZ')
  54. logger.info(f"Still Sands using timezone: {user_tz} (from environment)")
  55. else:
  56. logger.info("Still Sands using timezone: UTC (default)")
  57. except Exception as e:
  58. logger.debug(f"Could not read timezone: {e}")
  59. # Cache the timezone
  60. _cached_timezone = user_tz
  61. try:
  62. _cached_zoneinfo = ZoneInfo(user_tz)
  63. except Exception as e:
  64. logger.warning(f"Invalid timezone '{user_tz}', falling back to system time: {e}")
  65. _cached_zoneinfo = None
  66. return _cached_zoneinfo
  67. def is_in_scheduled_pause_period():
  68. """Check if current time falls within any scheduled pause period."""
  69. if not state.scheduled_pause_enabled or not state.scheduled_pause_time_slots:
  70. return False
  71. # Get cached timezone
  72. tz_info = _get_system_timezone()
  73. try:
  74. # Get current time in user's timezone
  75. if tz_info:
  76. now = datetime.now(tz_info)
  77. else:
  78. now = datetime.now()
  79. except Exception as e:
  80. logger.warning(f"Error getting current time: {e}")
  81. now = datetime.now()
  82. current_time = now.time()
  83. current_weekday = now.strftime("%A").lower() # monday, tuesday, etc.
  84. for slot in state.scheduled_pause_time_slots:
  85. # Parse start and end times
  86. try:
  87. start_time = datetime_time.fromisoformat(slot['start_time'])
  88. end_time = datetime_time.fromisoformat(slot['end_time'])
  89. except (ValueError, KeyError):
  90. logger.warning(f"Invalid time format in scheduled pause slot: {slot}")
  91. continue
  92. # Check if this slot applies to today
  93. slot_applies_today = False
  94. days_setting = slot.get('days', 'daily')
  95. if days_setting == 'daily':
  96. slot_applies_today = True
  97. elif days_setting == 'weekdays':
  98. slot_applies_today = current_weekday in ['monday', 'tuesday', 'wednesday', 'thursday', 'friday']
  99. elif days_setting == 'weekends':
  100. slot_applies_today = current_weekday in ['saturday', 'sunday']
  101. elif days_setting == 'custom':
  102. custom_days = slot.get('custom_days', [])
  103. slot_applies_today = current_weekday in custom_days
  104. if not slot_applies_today:
  105. continue
  106. # Check if current time is within the pause period
  107. if start_time <= end_time:
  108. # Normal case: start and end are on the same day
  109. if start_time <= current_time <= end_time:
  110. return True
  111. else:
  112. # Time spans midnight: start is before midnight, end is after midnight
  113. if current_time >= start_time or current_time <= end_time:
  114. return True
  115. return False
  116. # Motion Control Thread Infrastructure
  117. @dataclass
  118. class MotionCommand:
  119. """Represents a motion command for the motion control thread."""
  120. command_type: str # 'move', 'stop', 'pause', 'resume', 'shutdown'
  121. theta: Optional[float] = None
  122. rho: Optional[float] = None
  123. speed: Optional[float] = None
  124. callback: Optional[Callable] = None
  125. future: Optional[asyncio.Future] = None
  126. class MotionControlThread:
  127. """Dedicated thread for hardware motion control operations."""
  128. def __init__(self):
  129. self.command_queue = queue.Queue()
  130. self.thread = None
  131. self.running = False
  132. self.paused = False
  133. def start(self):
  134. """Start the motion control thread."""
  135. if self.thread and self.thread.is_alive():
  136. return
  137. self.running = True
  138. self.thread = threading.Thread(target=self._motion_loop, daemon=True)
  139. self.thread.start()
  140. logger.info("Motion control thread started")
  141. def stop(self):
  142. """Stop the motion control thread."""
  143. if not self.running:
  144. return
  145. self.running = False
  146. # Send shutdown command
  147. self.command_queue.put(MotionCommand('shutdown'))
  148. if self.thread and self.thread.is_alive():
  149. self.thread.join(timeout=5.0)
  150. logger.info("Motion control thread stopped")
  151. def _motion_loop(self):
  152. """Main loop for the motion control thread."""
  153. logger.info("Motion control thread loop started")
  154. while self.running:
  155. try:
  156. # Get command with timeout to allow periodic checks
  157. command = self.command_queue.get(timeout=1.0)
  158. if command.command_type == 'shutdown':
  159. break
  160. elif command.command_type == 'move':
  161. self._execute_move(command)
  162. elif command.command_type == 'pause':
  163. self.paused = True
  164. elif command.command_type == 'resume':
  165. self.paused = False
  166. elif command.command_type == 'stop':
  167. # Clear any pending commands
  168. while not self.command_queue.empty():
  169. try:
  170. self.command_queue.get_nowait()
  171. except queue.Empty:
  172. break
  173. self.command_queue.task_done()
  174. except queue.Empty:
  175. # Timeout - continue loop for shutdown check
  176. continue
  177. except Exception as e:
  178. logger.error(f"Error in motion control thread: {e}")
  179. logger.info("Motion control thread loop ended")
  180. def _execute_move(self, command: MotionCommand):
  181. """Execute a move command in the motion thread."""
  182. try:
  183. # Wait if paused
  184. while self.paused and self.running:
  185. time.sleep(0.1)
  186. if not self.running:
  187. return
  188. # Execute the actual motion using sync version
  189. self._move_polar_sync(command.theta, command.rho, command.speed)
  190. # Signal completion if future provided
  191. if command.future and not command.future.done():
  192. command.future.get_loop().call_soon_threadsafe(
  193. command.future.set_result, None
  194. )
  195. except Exception as e:
  196. logger.error(f"Error executing move command: {e}")
  197. if command.future and not command.future.done():
  198. command.future.get_loop().call_soon_threadsafe(
  199. command.future.set_exception, e
  200. )
  201. def _move_polar_sync(self, theta: float, rho: float, speed: Optional[float] = None):
  202. """Synchronous version of move_polar for use in motion thread."""
  203. # This is the original sync logic but running in dedicated thread
  204. if state.table_type == 'dune_weaver_mini':
  205. x_scaling_factor = 2
  206. y_scaling_factor = 3.7
  207. else:
  208. x_scaling_factor = 2
  209. y_scaling_factor = 5
  210. delta_theta = theta - state.current_theta
  211. delta_rho = rho - state.current_rho
  212. x_increment = delta_theta * 100 / (2 * pi * x_scaling_factor)
  213. y_increment = delta_rho * 100 / y_scaling_factor
  214. x_total_steps = state.x_steps_per_mm * (100/x_scaling_factor)
  215. y_total_steps = state.y_steps_per_mm * (100/y_scaling_factor)
  216. offset = x_increment * (x_total_steps * x_scaling_factor / (state.gear_ratio * y_total_steps * y_scaling_factor))
  217. if state.table_type == 'dune_weaver_mini' or state.y_steps_per_mm == 546:
  218. y_increment -= offset
  219. else:
  220. y_increment += offset
  221. new_x_abs = state.machine_x + x_increment
  222. new_y_abs = state.machine_y + y_increment
  223. # Use provided speed or fall back to state.speed
  224. actual_speed = speed if speed is not None else state.speed
  225. # Call sync version of send_grbl_coordinates in this thread
  226. self._send_grbl_coordinates_sync(round(new_x_abs, 3), round(new_y_abs, 3), actual_speed)
  227. # Update state
  228. state.current_theta = theta
  229. state.current_rho = rho
  230. state.machine_x = new_x_abs
  231. state.machine_y = new_y_abs
  232. def _send_grbl_coordinates_sync(self, x: float, y: float, speed: int = 600, timeout: int = 2, home: bool = False):
  233. """Synchronous version of send_grbl_coordinates for motion thread."""
  234. logger.debug(f"Motion thread sending G-code: X{x} Y{y} at F{speed}")
  235. # Track overall attempt time
  236. overall_start_time = time.time()
  237. while True:
  238. try:
  239. gcode = f"$J=G91 G21 Y{y} F{speed}" if home else f"G1 X{x} Y{y} F{speed}"
  240. state.conn.send(gcode + "\n")
  241. logger.debug(f"Motion thread sent command: {gcode}")
  242. start_time = time.time()
  243. while True:
  244. response = state.conn.readline()
  245. logger.debug(f"Motion thread response: {response}")
  246. if response.lower() == "ok":
  247. logger.debug("Motion thread: Command execution confirmed.")
  248. return
  249. except Exception as e:
  250. error_str = str(e)
  251. logger.warning(f"Motion thread error sending command: {error_str}")
  252. # Immediately return for device not configured errors
  253. if "Device not configured" in error_str or "Errno 6" in error_str:
  254. logger.error(f"Motion thread: Device configuration error detected: {error_str}")
  255. state.stop_requested = True
  256. state.conn = None
  257. state.is_connected = False
  258. logger.info("Connection marked as disconnected due to device error")
  259. return False
  260. logger.warning(f"Motion thread: No 'ok' received for X{x} Y{y}, speed {speed}. Retrying...")
  261. time.sleep(0.1)
  262. # Global motion control thread instance
  263. motion_controller = MotionControlThread()
  264. async def cleanup_pattern_manager():
  265. """Clean up pattern manager resources"""
  266. global progress_update_task, pattern_lock, pause_event
  267. try:
  268. # Stop motion control thread
  269. motion_controller.stop()
  270. # Cancel progress update task if running
  271. if progress_update_task and not progress_update_task.done():
  272. try:
  273. progress_update_task.cancel()
  274. # Wait for task to actually cancel
  275. try:
  276. await progress_update_task
  277. except asyncio.CancelledError:
  278. pass
  279. except Exception as e:
  280. logger.error(f"Error cancelling progress update task: {e}")
  281. # Clean up pattern lock
  282. if pattern_lock:
  283. try:
  284. if pattern_lock.locked():
  285. pattern_lock.release()
  286. pattern_lock = None
  287. except Exception as e:
  288. logger.error(f"Error cleaning up pattern lock: {e}")
  289. # Clean up pause event
  290. if pause_event:
  291. try:
  292. pause_event.set() # Wake up any waiting tasks
  293. pause_event = None
  294. except Exception as e:
  295. logger.error(f"Error cleaning up pause event: {e}")
  296. # Clean up pause condition from state
  297. if state.pause_condition:
  298. try:
  299. with state.pause_condition:
  300. state.pause_condition.notify_all()
  301. state.pause_condition = threading.Condition()
  302. except Exception as e:
  303. logger.error(f"Error cleaning up pause condition: {e}")
  304. # Clear all state variables
  305. state.current_playing_file = None
  306. state.execution_progress = 0
  307. state.is_running = False
  308. state.pause_requested = False
  309. state.stop_requested = True
  310. state.is_clearing = False
  311. # Reset machine position
  312. await connection_manager.update_machine_position()
  313. logger.info("Pattern manager resources cleaned up")
  314. except Exception as e:
  315. logger.error(f"Error during pattern manager cleanup: {e}")
  316. finally:
  317. # Ensure we always reset these
  318. progress_update_task = None
  319. pattern_lock = None
  320. pause_event = None
  321. def list_theta_rho_files():
  322. files = []
  323. for root, dirs, filenames in os.walk(THETA_RHO_DIR):
  324. # Skip cached_images directories to avoid scanning thousands of WebP files
  325. if 'cached_images' in dirs:
  326. dirs.remove('cached_images')
  327. # Filter .thr files during traversal for better performance
  328. thr_files = [f for f in filenames if f.endswith('.thr')]
  329. for file in thr_files:
  330. relative_path = os.path.relpath(os.path.join(root, file), THETA_RHO_DIR)
  331. # Normalize path separators to always use forward slashes for consistency across platforms
  332. relative_path = relative_path.replace(os.sep, '/')
  333. files.append(relative_path)
  334. logger.debug(f"Found {len(files)} theta-rho files")
  335. return files
  336. def parse_theta_rho_file(file_path):
  337. """Parse a theta-rho file and return a list of (theta, rho) pairs."""
  338. coordinates = []
  339. try:
  340. logger.debug(f"Parsing theta-rho file: {file_path}")
  341. with open(file_path, 'r', encoding='utf-8') as file:
  342. for line in file:
  343. line = line.strip()
  344. if not line or line.startswith("#"):
  345. continue
  346. try:
  347. theta, rho = map(float, line.split())
  348. coordinates.append((theta, rho))
  349. except ValueError:
  350. logger.warning(f"Skipping invalid line: {line}")
  351. continue
  352. except Exception as e:
  353. logger.error(f"Error reading file: {e}")
  354. return coordinates
  355. logger.debug(f"Parsed {len(coordinates)} coordinates from {file_path}")
  356. return coordinates
  357. def get_first_rho_from_cache(file_path, cache_data=None):
  358. """Get the first rho value from cached metadata, falling back to file parsing if needed.
  359. Args:
  360. file_path: Path to the pattern file
  361. cache_data: Optional pre-loaded cache data dict to avoid repeated disk I/O
  362. """
  363. try:
  364. # Import cache_manager locally to avoid circular import
  365. from modules.core import cache_manager
  366. # Try to get from metadata cache first
  367. # Use relative path from THETA_RHO_DIR to match cache keys (which include subdirectories)
  368. file_name = os.path.relpath(file_path, THETA_RHO_DIR)
  369. # Use provided cache_data if available, otherwise load from disk
  370. if cache_data is not None:
  371. # Extract metadata directly from provided cache
  372. data_section = cache_data.get('data', {})
  373. if file_name in data_section:
  374. cached_entry = data_section[file_name]
  375. metadata = cached_entry.get('metadata')
  376. # When cache_data is provided, trust it without checking mtime
  377. # This significantly speeds up bulk operations (playlists with 1000+ patterns)
  378. # by avoiding 1000+ os.path.getmtime() calls on slow storage (e.g., Pi SD cards)
  379. if metadata and 'first_coordinate' in metadata:
  380. return metadata['first_coordinate']['y']
  381. else:
  382. # Fall back to loading cache from disk (original behavior)
  383. metadata = cache_manager.get_pattern_metadata(file_name)
  384. if metadata and 'first_coordinate' in metadata:
  385. # In the cache, 'x' is theta and 'y' is rho
  386. return metadata['first_coordinate']['y']
  387. # Fallback to parsing the file if not in cache
  388. logger.debug(f"Metadata not cached for {file_name}, parsing file")
  389. coordinates = parse_theta_rho_file(file_path)
  390. if coordinates:
  391. return coordinates[0][1] # Return rho value
  392. return None
  393. except Exception as e:
  394. logger.warning(f"Error getting first rho from cache for {file_path}: {str(e)}")
  395. return None
  396. def get_clear_pattern_file(clear_pattern_mode, path=None, cache_data=None):
  397. """Return a .thr file path based on pattern_name and table type.
  398. Args:
  399. clear_pattern_mode: The clear pattern mode to use
  400. path: Optional path to the pattern file for adaptive mode
  401. cache_data: Optional pre-loaded cache data dict to avoid repeated disk I/O
  402. """
  403. if not clear_pattern_mode or clear_pattern_mode == 'none':
  404. return
  405. # Define patterns for each table type
  406. clear_patterns = {
  407. 'dune_weaver': {
  408. 'clear_from_out': './patterns/clear_from_out.thr',
  409. 'clear_from_in': './patterns/clear_from_in.thr',
  410. 'clear_sideway': './patterns/clear_sideway.thr'
  411. },
  412. 'dune_weaver_mini': {
  413. 'clear_from_out': './patterns/clear_from_out_mini.thr',
  414. 'clear_from_in': './patterns/clear_from_in_mini.thr',
  415. 'clear_sideway': './patterns/clear_sideway_mini.thr'
  416. },
  417. 'dune_weaver_pro': {
  418. 'clear_from_out': './patterns/clear_from_out_pro.thr',
  419. 'clear_from_out_Ultra': './patterns/clear_from_out_Ultra.thr',
  420. 'clear_from_in': './patterns/clear_from_in_pro.thr',
  421. 'clear_from_in_Ultra': './patterns/clear_from_in_Ultra.thr',
  422. 'clear_sideway': './patterns/clear_sideway_pro.thr'
  423. }
  424. }
  425. # Get patterns for current table type, fallback to standard patterns if type not found
  426. table_patterns = clear_patterns.get(state.table_type, clear_patterns['dune_weaver'])
  427. # Check for custom patterns first
  428. if state.custom_clear_from_out and clear_pattern_mode in ['clear_from_out', 'adaptive']:
  429. if clear_pattern_mode == 'adaptive':
  430. # For adaptive mode, use cached metadata to check first rho
  431. if path:
  432. first_rho = get_first_rho_from_cache(path, cache_data)
  433. if first_rho is not None and first_rho < 0.5:
  434. # Use custom clear_from_out if set
  435. custom_path = os.path.join('./patterns', state.custom_clear_from_out)
  436. if os.path.exists(custom_path):
  437. logger.debug(f"Using custom clear_from_out: {custom_path}")
  438. return custom_path
  439. elif clear_pattern_mode == 'clear_from_out':
  440. custom_path = os.path.join('./patterns', state.custom_clear_from_out)
  441. if os.path.exists(custom_path):
  442. logger.debug(f"Using custom clear_from_out: {custom_path}")
  443. return custom_path
  444. if state.custom_clear_from_in and clear_pattern_mode in ['clear_from_in', 'adaptive']:
  445. if clear_pattern_mode == 'adaptive':
  446. # For adaptive mode, use cached metadata to check first rho
  447. if path:
  448. first_rho = get_first_rho_from_cache(path, cache_data)
  449. if first_rho is not None and first_rho >= 0.5:
  450. # Use custom clear_from_in if set
  451. custom_path = os.path.join('./patterns', state.custom_clear_from_in)
  452. if os.path.exists(custom_path):
  453. logger.debug(f"Using custom clear_from_in: {custom_path}")
  454. return custom_path
  455. elif clear_pattern_mode == 'clear_from_in':
  456. custom_path = os.path.join('./patterns', state.custom_clear_from_in)
  457. if os.path.exists(custom_path):
  458. logger.debug(f"Using custom clear_from_in: {custom_path}")
  459. return custom_path
  460. logger.debug(f"Clear pattern mode: {clear_pattern_mode} for table type: {state.table_type}")
  461. if clear_pattern_mode == "random":
  462. return random.choice(list(table_patterns.values()))
  463. if clear_pattern_mode == 'adaptive':
  464. if not path:
  465. logger.warning("No path provided for adaptive clear pattern")
  466. return random.choice(list(table_patterns.values()))
  467. # Use cached metadata to get first rho value
  468. first_rho = get_first_rho_from_cache(path, cache_data)
  469. if first_rho is None:
  470. logger.warning("Could not determine first rho value for adaptive clear pattern")
  471. return random.choice(list(table_patterns.values()))
  472. if first_rho < 0.5:
  473. return table_patterns['clear_from_out']
  474. else:
  475. return table_patterns['clear_from_in']
  476. else:
  477. if clear_pattern_mode not in table_patterns:
  478. return False
  479. return table_patterns[clear_pattern_mode]
  480. def is_clear_pattern(file_path):
  481. """Check if a file path is a clear pattern file."""
  482. # Get all possible clear pattern files for all table types
  483. clear_patterns = []
  484. for table_type in ['dune_weaver', 'dune_weaver_mini', 'dune_weaver_pro']:
  485. clear_patterns.extend([
  486. f'./patterns/clear_from_out{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr',
  487. f'./patterns/clear_from_in{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr',
  488. f'./patterns/clear_sideway{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr'
  489. ])
  490. # Normalize paths for comparison
  491. normalized_path = os.path.normpath(file_path)
  492. normalized_clear_patterns = [os.path.normpath(p) for p in clear_patterns]
  493. # Check if the file path matches any clear pattern path
  494. return normalized_path in normalized_clear_patterns
  495. async def run_theta_rho_file(file_path, is_playlist=False):
  496. """Run a theta-rho file by sending data in optimized batches with tqdm ETA tracking."""
  497. if pattern_lock.locked():
  498. logger.warning("Another pattern is already running. Cannot start a new one.")
  499. return
  500. async with pattern_lock: # This ensures only one pattern can run at a time
  501. # Start progress update task only if not part of a playlist
  502. global progress_update_task
  503. if not is_playlist and not progress_update_task:
  504. progress_update_task = asyncio.create_task(broadcast_progress())
  505. coordinates = parse_theta_rho_file(file_path)
  506. total_coordinates = len(coordinates)
  507. if total_coordinates < 2:
  508. logger.warning("Not enough coordinates for interpolation")
  509. if not is_playlist:
  510. state.current_playing_file = None
  511. state.execution_progress = None
  512. return
  513. # Determine if this is a clearing pattern
  514. is_clear_file = is_clear_pattern(file_path)
  515. if is_clear_file:
  516. initial_speed = state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  517. logger.info(f"Running clearing pattern at initial speed {initial_speed}")
  518. else:
  519. logger.info(f"Running normal pattern at initial speed {state.speed}")
  520. state.execution_progress = (0, total_coordinates, None, 0)
  521. # stop actions without resetting the playlist, and don't wait for lock (we already have it)
  522. await stop_actions(clear_playlist=False, wait_for_lock=False)
  523. state.current_playing_file = file_path
  524. state.stop_requested = False
  525. logger.info(f"Starting pattern execution: {file_path}")
  526. logger.info(f"t: {state.current_theta}, r: {state.current_rho}")
  527. await reset_theta()
  528. start_time = time.time()
  529. if state.led_controller:
  530. state.led_controller.effect_playing(state.hyperion_playing_effect)
  531. with tqdm(
  532. total=total_coordinates,
  533. unit="coords",
  534. desc=f"Executing Pattern {file_path}",
  535. dynamic_ncols=True,
  536. disable=False,
  537. mininterval=1.0
  538. ) as pbar:
  539. for i, coordinate in enumerate(coordinates):
  540. theta, rho = coordinate
  541. if state.stop_requested:
  542. logger.info("Execution stopped by user")
  543. if state.led_controller:
  544. state.led_controller.effect_idle(state.hyperion_idle_effect)
  545. break
  546. if state.skip_requested:
  547. logger.info("Skipping pattern...")
  548. await connection_manager.check_idle_async()
  549. if state.led_controller:
  550. state.led_controller.effect_idle(state.hyperion_idle_effect)
  551. break
  552. # Wait for resume if paused (manual or scheduled)
  553. manual_pause = state.pause_requested
  554. scheduled_pause = is_in_scheduled_pause_period()
  555. if manual_pause or scheduled_pause:
  556. if manual_pause and scheduled_pause:
  557. logger.info("Execution paused (manual + scheduled pause active)...")
  558. elif manual_pause:
  559. logger.info("Execution paused (manual)...")
  560. else:
  561. logger.info("Execution paused (scheduled pause period)...")
  562. # Turn off LED controller if scheduled pause and control_wled is enabled
  563. if state.scheduled_pause_control_wled and state.led_controller:
  564. logger.info("Turning off LED lights during Still Sands period")
  565. state.led_controller.set_power(0)
  566. # Only show idle effect if NOT in scheduled pause with LED control
  567. # (manual pause always shows idle effect)
  568. if state.led_controller and not (scheduled_pause and state.scheduled_pause_control_wled):
  569. state.led_controller.effect_idle(state.hyperion_idle_effect)
  570. # Remember if we turned off LED controller for scheduled pause
  571. wled_was_off_for_scheduled = scheduled_pause and state.scheduled_pause_control_wled and not manual_pause
  572. # Wait until both manual pause is released AND we're outside scheduled pause period
  573. while state.pause_requested or is_in_scheduled_pause_period():
  574. await asyncio.sleep(1) # Check every second
  575. # Also wait for the pause event in case of manual pause
  576. if state.pause_requested:
  577. await pause_event.wait()
  578. logger.info("Execution resumed...")
  579. if state.led_controller:
  580. # Turn LED controller back on if it was turned off for scheduled pause
  581. if wled_was_off_for_scheduled:
  582. logger.info("Turning LED lights back on as Still Sands period ended")
  583. state.led_controller.set_power(1)
  584. state.led_controller.effect_playing(state.hyperion_playing_effect)
  585. # Dynamically determine the speed for each movement
  586. # Use clear_pattern_speed if it's set and this is a clear file, otherwise use state.speed
  587. if is_clear_file and state.clear_pattern_speed is not None:
  588. current_speed = state.clear_pattern_speed
  589. else:
  590. current_speed = state.speed
  591. await move_polar(theta, rho, current_speed)
  592. # Update progress for all coordinates including the first one
  593. pbar.update(1)
  594. elapsed_time = time.time() - start_time
  595. estimated_remaining_time = (total_coordinates - (i + 1)) / pbar.format_dict['rate'] if pbar.format_dict['rate'] and total_coordinates else 0
  596. state.execution_progress = (i + 1, total_coordinates, estimated_remaining_time, elapsed_time)
  597. # Add a small delay to allow other async operations
  598. await asyncio.sleep(0.001)
  599. # Update progress one last time to show 100%
  600. elapsed_time = time.time() - start_time
  601. state.execution_progress = (total_coordinates, total_coordinates, 0, elapsed_time)
  602. # Give WebSocket a chance to send the final update
  603. await asyncio.sleep(0.1)
  604. if not state.conn:
  605. logger.error("Device is not connected. Stopping pattern execution.")
  606. return
  607. await connection_manager.check_idle_async()
  608. # Set LED back to idle when pattern completes normally (not stopped early)
  609. if state.led_controller and not state.stop_requested:
  610. state.led_controller.effect_idle(state.hyperion_idle_effect)
  611. logger.debug("LED effect set to idle after pattern completion")
  612. # Only clear state if not part of a playlist
  613. if not is_playlist:
  614. state.current_playing_file = None
  615. state.execution_progress = None
  616. logger.info("Pattern execution completed and state cleared")
  617. else:
  618. logger.info("Pattern execution completed, maintaining state for playlist")
  619. # Only cancel progress update task if not part of a playlist
  620. if not is_playlist and progress_update_task:
  621. progress_update_task.cancel()
  622. try:
  623. await progress_update_task
  624. except asyncio.CancelledError:
  625. pass
  626. progress_update_task = None
  627. async def run_theta_rho_files(file_paths, pause_time=0, clear_pattern=None, run_mode="single", shuffle=False):
  628. """Run multiple .thr files in sequence with options."""
  629. state.stop_requested = False
  630. # Set initial playlist state
  631. state.playlist_mode = run_mode
  632. state.current_playlist_index = 0
  633. # Start progress update task for the playlist
  634. global progress_update_task
  635. if not progress_update_task:
  636. progress_update_task = asyncio.create_task(broadcast_progress())
  637. if shuffle:
  638. random.shuffle(file_paths)
  639. logger.info("Playlist shuffled")
  640. try:
  641. while True:
  642. # Load metadata cache once for all patterns (significant performance improvement)
  643. # This avoids reading the cache file from disk for every pattern
  644. cache_data = None
  645. if clear_pattern and clear_pattern in ['adaptive', 'clear_from_in', 'clear_from_out']:
  646. from modules.core import cache_manager
  647. cache_data = cache_manager.load_metadata_cache()
  648. logger.info(f"Loaded metadata cache for {len(cache_data.get('data', {}))} patterns")
  649. # Construct the complete pattern sequence
  650. pattern_sequence = []
  651. for path in file_paths:
  652. # Add clear pattern if specified
  653. if clear_pattern and clear_pattern != 'none':
  654. clear_file_path = get_clear_pattern_file(clear_pattern, path, cache_data)
  655. if clear_file_path:
  656. pattern_sequence.append(clear_file_path)
  657. # Add main pattern
  658. pattern_sequence.append(path)
  659. # Shuffle if requested
  660. if shuffle:
  661. # Get pairs of patterns (clear + main) to keep them together
  662. pairs = [pattern_sequence[i:i+2] for i in range(0, len(pattern_sequence), 2)]
  663. random.shuffle(pairs)
  664. # Flatten the pairs back into a single list
  665. pattern_sequence = [pattern for pair in pairs for pattern in pair]
  666. logger.info("Playlist shuffled")
  667. # Set the playlist to the first pattern
  668. state.current_playlist = pattern_sequence
  669. # Execute the pattern sequence
  670. for idx, file_path in enumerate(pattern_sequence):
  671. state.current_playlist_index = idx
  672. if state.stop_requested:
  673. logger.info("Execution stopped")
  674. return
  675. # Update state for main patterns only
  676. logger.info(f"Running pattern {file_path}")
  677. # Execute the pattern
  678. await run_theta_rho_file(file_path, is_playlist=True)
  679. # Handle pause between patterns
  680. if idx < len(pattern_sequence) - 1 and not state.stop_requested and pause_time > 0 and not state.skip_requested:
  681. # Check if current pattern is a clear pattern
  682. if is_clear_pattern(file_path):
  683. logger.info("Skipping pause after clear pattern")
  684. else:
  685. logger.info(f"Pausing for {pause_time} seconds")
  686. state.original_pause_time = pause_time
  687. pause_start = time.time()
  688. while time.time() - pause_start < pause_time:
  689. state.pause_time_remaining = pause_start + pause_time - time.time()
  690. if state.skip_requested:
  691. logger.info("Pause interrupted by stop/skip request")
  692. break
  693. await asyncio.sleep(1)
  694. state.pause_time_remaining = 0
  695. state.skip_requested = False
  696. if run_mode == "indefinite":
  697. logger.info("Playlist completed. Restarting as per 'indefinite' run mode")
  698. if pause_time > 0:
  699. logger.debug(f"Pausing for {pause_time} seconds before restarting")
  700. pause_start = time.time()
  701. while time.time() - pause_start < pause_time:
  702. state.pause_time_remaining = pause_start + pause_time - time.time()
  703. if state.skip_requested:
  704. logger.info("Pause interrupted by stop/skip request")
  705. break
  706. await asyncio.sleep(1)
  707. state.pause_time_remaining = 0
  708. continue
  709. else:
  710. logger.info("Playlist completed")
  711. break
  712. finally:
  713. # Clean up progress update task
  714. if progress_update_task:
  715. progress_update_task.cancel()
  716. try:
  717. await progress_update_task
  718. except asyncio.CancelledError:
  719. pass
  720. progress_update_task = None
  721. # Clear all state variables
  722. state.current_playing_file = None
  723. state.execution_progress = None
  724. state.current_playlist = None
  725. state.current_playlist_index = None
  726. state.playlist_mode = None
  727. if state.led_controller:
  728. state.led_controller.effect_idle(state.hyperion_idle_effect)
  729. logger.info("All requested patterns completed (or stopped) and state cleared")
  730. async def stop_actions(clear_playlist = True, wait_for_lock = True):
  731. """Stop all current actions and wait for pattern to fully release.
  732. Args:
  733. clear_playlist: Whether to clear playlist state
  734. wait_for_lock: Whether to wait for pattern_lock to be released. Set to False when
  735. called from within pattern execution to avoid deadlock.
  736. """
  737. try:
  738. with state.pause_condition:
  739. state.pause_requested = False
  740. state.stop_requested = True
  741. state.current_playing_file = None
  742. state.execution_progress = None
  743. state.is_clearing = False
  744. if clear_playlist:
  745. # Clear playlist state
  746. state.current_playlist = None
  747. state.current_playlist_index = None
  748. state.playlist_mode = None
  749. # Cancel progress update task if we're clearing the playlist
  750. global progress_update_task
  751. if progress_update_task and not progress_update_task.done():
  752. progress_update_task.cancel()
  753. state.pause_condition.notify_all()
  754. # Wait for the pattern lock to be released before continuing
  755. # This ensures that when stop_actions completes, the pattern has fully stopped
  756. # Skip this if called from within pattern execution to avoid deadlock
  757. if wait_for_lock and pattern_lock.locked():
  758. logger.info("Waiting for pattern to fully stop...")
  759. # Acquire and immediately release the lock to ensure the pattern has exited
  760. async with pattern_lock:
  761. logger.info("Pattern lock acquired - pattern has fully stopped")
  762. # Call async function directly since we're in async context
  763. await connection_manager.update_machine_position()
  764. except Exception as e:
  765. logger.error(f"Error during stop_actions: {e}")
  766. # Ensure we still update machine position even if there's an error
  767. try:
  768. await connection_manager.update_machine_position()
  769. except Exception as update_err:
  770. logger.error(f"Error updating machine position on error: {update_err}")
  771. async def move_polar(theta, rho, speed=None):
  772. """
  773. Queue a motion command to be executed in the dedicated motion control thread.
  774. This makes motion control non-blocking for API endpoints.
  775. Args:
  776. theta (float): Target theta coordinate
  777. rho (float): Target rho coordinate
  778. speed (int, optional): Speed override. If None, uses state.speed
  779. """
  780. # Ensure motion control thread is running
  781. if not motion_controller.running:
  782. motion_controller.start()
  783. # Create future for async/await pattern
  784. loop = asyncio.get_event_loop()
  785. future = loop.create_future()
  786. # Create and queue motion command
  787. command = MotionCommand(
  788. command_type='move',
  789. theta=theta,
  790. rho=rho,
  791. speed=speed,
  792. future=future
  793. )
  794. motion_controller.command_queue.put(command)
  795. logger.debug(f"Queued motion command: theta={theta}, rho={rho}, speed={speed}")
  796. # Wait for command completion
  797. await future
  798. def pause_execution():
  799. """Pause pattern execution using asyncio Event."""
  800. logger.info("Pausing pattern execution")
  801. state.pause_requested = True
  802. pause_event.clear() # Clear the event to pause execution
  803. return True
  804. def resume_execution():
  805. """Resume pattern execution using asyncio Event."""
  806. logger.info("Resuming pattern execution")
  807. state.pause_requested = False
  808. pause_event.set() # Set the event to resume execution
  809. return True
  810. async def reset_theta():
  811. logger.info('Resetting Theta')
  812. state.current_theta = state.current_theta % (2 * pi)
  813. # Call async function directly since we're in async context
  814. await connection_manager.update_machine_position()
  815. def set_speed(new_speed):
  816. state.speed = new_speed
  817. logger.info(f'Set new state.speed {new_speed}')
  818. def get_status():
  819. """Get the current status of pattern execution."""
  820. status = {
  821. "current_file": state.current_playing_file,
  822. "is_paused": state.pause_requested or is_in_scheduled_pause_period(),
  823. "manual_pause": state.pause_requested,
  824. "scheduled_pause": is_in_scheduled_pause_period(),
  825. "is_running": bool(state.current_playing_file and not state.stop_requested),
  826. "progress": None,
  827. "playlist": None,
  828. "speed": state.speed,
  829. "pause_time_remaining": state.pause_time_remaining,
  830. "original_pause_time": getattr(state, 'original_pause_time', None),
  831. "connection_status": state.conn.is_connected() if state.conn else False,
  832. "current_theta": state.current_theta,
  833. "current_rho": state.current_rho
  834. }
  835. # Add playlist information if available
  836. if state.current_playlist and state.current_playlist_index is not None:
  837. next_index = state.current_playlist_index + 1
  838. status["playlist"] = {
  839. "current_index": state.current_playlist_index,
  840. "total_files": len(state.current_playlist),
  841. "mode": state.playlist_mode,
  842. "next_file": state.current_playlist[next_index] if next_index < len(state.current_playlist) else None
  843. }
  844. if state.execution_progress:
  845. current, total, remaining_time, elapsed_time = state.execution_progress
  846. status["progress"] = {
  847. "current": current,
  848. "total": total,
  849. "remaining_time": remaining_time,
  850. "elapsed_time": elapsed_time,
  851. "percentage": (current / total * 100) if total > 0 else 0
  852. }
  853. return status
  854. async def broadcast_progress():
  855. """Background task to broadcast progress updates."""
  856. from main import broadcast_status_update
  857. while True:
  858. # Send status updates regardless of pattern_lock state
  859. status = get_status()
  860. # Use the existing broadcast function from main.py
  861. await broadcast_status_update(status)
  862. # Check if we should stop broadcasting
  863. if not state.current_playlist:
  864. # If no playlist, only stop if no pattern is being executed
  865. if not pattern_lock.locked():
  866. logger.info("No playlist or pattern running, stopping broadcast")
  867. break
  868. # Wait before next update
  869. await asyncio.sleep(1)