pattern_manager.py 48 KB

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