pattern_manager.py 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  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_pro': {
  447. 'clear_from_out': './patterns/clear_from_out_pro.thr',
  448. 'clear_from_out_Ultra': './patterns/clear_from_out_Ultra.thr',
  449. 'clear_from_in': './patterns/clear_from_in_pro.thr',
  450. 'clear_from_in_Ultra': './patterns/clear_from_in_Ultra.thr',
  451. 'clear_sideway': './patterns/clear_sideway_pro.thr'
  452. }
  453. }
  454. # Get patterns for current table type, fallback to standard patterns if type not found
  455. table_patterns = clear_patterns.get(state.table_type, clear_patterns['dune_weaver'])
  456. # Check for custom patterns first
  457. if state.custom_clear_from_out and clear_pattern_mode in ['clear_from_out', 'adaptive']:
  458. if clear_pattern_mode == 'adaptive':
  459. # For adaptive mode, use cached metadata to check first rho
  460. if path:
  461. first_rho = get_first_rho_from_cache(path, cache_data)
  462. if first_rho is not None and first_rho < 0.5:
  463. # Use custom clear_from_out if set
  464. custom_path = os.path.join('./patterns', state.custom_clear_from_out)
  465. if os.path.exists(custom_path):
  466. logger.debug(f"Using custom clear_from_out: {custom_path}")
  467. return custom_path
  468. elif clear_pattern_mode == 'clear_from_out':
  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. if state.custom_clear_from_in and clear_pattern_mode in ['clear_from_in', 'adaptive']:
  474. if clear_pattern_mode == 'adaptive':
  475. # For adaptive mode, use cached metadata to check first rho
  476. if path:
  477. first_rho = get_first_rho_from_cache(path, cache_data)
  478. if first_rho is not None and first_rho >= 0.5:
  479. # Use custom clear_from_in if set
  480. custom_path = os.path.join('./patterns', state.custom_clear_from_in)
  481. if os.path.exists(custom_path):
  482. logger.debug(f"Using custom clear_from_in: {custom_path}")
  483. return custom_path
  484. elif clear_pattern_mode == 'clear_from_in':
  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. logger.debug(f"Clear pattern mode: {clear_pattern_mode} for table type: {state.table_type}")
  490. if clear_pattern_mode == "random":
  491. return random.choice(list(table_patterns.values()))
  492. if clear_pattern_mode == 'adaptive':
  493. if not path:
  494. logger.warning("No path provided for adaptive clear pattern")
  495. return random.choice(list(table_patterns.values()))
  496. # Use cached metadata to get first rho value
  497. first_rho = get_first_rho_from_cache(path, cache_data)
  498. if first_rho is None:
  499. logger.warning("Could not determine first rho value for adaptive clear pattern")
  500. return random.choice(list(table_patterns.values()))
  501. if first_rho < 0.5:
  502. return table_patterns['clear_from_out']
  503. else:
  504. return table_patterns['clear_from_in']
  505. else:
  506. if clear_pattern_mode not in table_patterns:
  507. return False
  508. return table_patterns[clear_pattern_mode]
  509. def is_clear_pattern(file_path):
  510. """Check if a file path is a clear pattern file."""
  511. # Get all possible clear pattern files for all table types
  512. clear_patterns = []
  513. for table_type in ['dune_weaver', 'dune_weaver_mini', 'dune_weaver_pro']:
  514. clear_patterns.extend([
  515. f'./patterns/clear_from_out{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr',
  516. f'./patterns/clear_from_in{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr',
  517. f'./patterns/clear_sideway{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr'
  518. ])
  519. # Normalize paths for comparison
  520. normalized_path = os.path.normpath(file_path)
  521. normalized_clear_patterns = [os.path.normpath(p) for p in clear_patterns]
  522. # Check if the file path matches any clear pattern path
  523. return normalized_path in normalized_clear_patterns
  524. async def run_theta_rho_file(file_path, is_playlist=False):
  525. """Run a theta-rho file by sending data in optimized batches with tqdm ETA tracking."""
  526. if pattern_lock.locked():
  527. logger.warning("Another pattern is already running. Cannot start a new one.")
  528. return
  529. async with pattern_lock: # This ensures only one pattern can run at a time
  530. # Start progress update task only if not part of a playlist
  531. global progress_update_task
  532. if not is_playlist and not progress_update_task:
  533. progress_update_task = asyncio.create_task(broadcast_progress())
  534. coordinates = parse_theta_rho_file(file_path)
  535. total_coordinates = len(coordinates)
  536. if total_coordinates < 2:
  537. logger.warning("Not enough coordinates for interpolation")
  538. if not is_playlist:
  539. state.current_playing_file = None
  540. state.execution_progress = None
  541. return
  542. # Determine if this is a clearing pattern
  543. is_clear_file = is_clear_pattern(file_path)
  544. if is_clear_file:
  545. initial_speed = state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  546. logger.info(f"Running clearing pattern at initial speed {initial_speed}")
  547. else:
  548. logger.info(f"Running normal pattern at initial speed {state.speed}")
  549. state.execution_progress = (0, total_coordinates, None, 0)
  550. # stop actions without resetting the playlist, and don't wait for lock (we already have it)
  551. await stop_actions(clear_playlist=False, wait_for_lock=False)
  552. state.current_playing_file = file_path
  553. state.stop_requested = False
  554. # Reset LED idle timeout activity time when pattern starts
  555. import time as time_module
  556. state.dw_led_last_activity_time = time_module.time()
  557. logger.info(f"Starting pattern execution: {file_path}")
  558. logger.info(f"t: {state.current_theta}, r: {state.current_rho}")
  559. await reset_theta()
  560. start_time = time.time()
  561. if state.led_controller:
  562. logger.info(f"Setting LED to playing effect: {state.dw_led_playing_effect}")
  563. state.led_controller.effect_playing(state.dw_led_playing_effect)
  564. # Cancel idle timeout when playing starts
  565. idle_timeout_manager.cancel_timeout()
  566. with tqdm(
  567. total=total_coordinates,
  568. unit="coords",
  569. desc=f"Executing Pattern {file_path}",
  570. dynamic_ncols=True,
  571. disable=False,
  572. mininterval=1.0
  573. ) as pbar:
  574. for i, coordinate in enumerate(coordinates):
  575. theta, rho = coordinate
  576. if state.stop_requested:
  577. logger.info("Execution stopped by user")
  578. if state.led_controller:
  579. state.led_controller.effect_idle(state.dw_led_idle_effect)
  580. start_idle_led_timeout()
  581. break
  582. if state.skip_requested:
  583. logger.info("Skipping pattern...")
  584. await connection_manager.check_idle_async()
  585. if state.led_controller:
  586. state.led_controller.effect_idle(state.dw_led_idle_effect)
  587. start_idle_led_timeout()
  588. break
  589. # Wait for resume if paused (manual or scheduled)
  590. manual_pause = state.pause_requested
  591. scheduled_pause = is_in_scheduled_pause_period()
  592. if manual_pause or scheduled_pause:
  593. if manual_pause and scheduled_pause:
  594. logger.info("Execution paused (manual + scheduled pause active)...")
  595. elif manual_pause:
  596. logger.info("Execution paused (manual)...")
  597. else:
  598. logger.info("Execution paused (scheduled pause period)...")
  599. # Turn off LED controller if scheduled pause and control_wled is enabled
  600. if state.scheduled_pause_control_wled and state.led_controller:
  601. logger.info("Turning off LED lights during Still Sands period")
  602. state.led_controller.set_power(0)
  603. # Only show idle effect if NOT in scheduled pause with LED control
  604. # (manual pause always shows idle effect)
  605. if state.led_controller and not (scheduled_pause and state.scheduled_pause_control_wled):
  606. state.led_controller.effect_idle(state.dw_led_idle_effect)
  607. start_idle_led_timeout()
  608. # Remember if we turned off LED controller for scheduled pause
  609. wled_was_off_for_scheduled = scheduled_pause and state.scheduled_pause_control_wled and not manual_pause
  610. # Wait until both manual pause is released AND we're outside scheduled pause period
  611. while state.pause_requested or is_in_scheduled_pause_period():
  612. await asyncio.sleep(1) # Check every second
  613. # Also wait for the pause event in case of manual pause
  614. if state.pause_requested:
  615. await pause_event.wait()
  616. logger.info("Execution resumed...")
  617. if state.led_controller:
  618. # Turn LED controller back on if it was turned off for scheduled pause
  619. if wled_was_off_for_scheduled:
  620. logger.info("Turning LED lights back on as Still Sands period ended")
  621. state.led_controller.set_power(1)
  622. # CRITICAL: Give LED controller time to fully power on before sending more commands
  623. # Without this delay, rapid-fire requests can crash controllers on resource-constrained Pis
  624. await asyncio.sleep(0.5)
  625. state.led_controller.effect_playing(state.dw_led_playing_effect)
  626. # Cancel idle timeout when resuming from pause
  627. idle_timeout_manager.cancel_timeout()
  628. # Dynamically determine the speed for each movement
  629. # Use clear_pattern_speed if it's set and this is a clear file, otherwise use state.speed
  630. if is_clear_file and state.clear_pattern_speed is not None:
  631. current_speed = state.clear_pattern_speed
  632. else:
  633. current_speed = state.speed
  634. await move_polar(theta, rho, current_speed)
  635. # Update progress for all coordinates including the first one
  636. pbar.update(1)
  637. elapsed_time = time.time() - start_time
  638. estimated_remaining_time = (total_coordinates - (i + 1)) / pbar.format_dict['rate'] if pbar.format_dict['rate'] and total_coordinates else 0
  639. state.execution_progress = (i + 1, total_coordinates, estimated_remaining_time, elapsed_time)
  640. # Add a small delay to allow other async operations
  641. await asyncio.sleep(0.001)
  642. # Update progress one last time to show 100%
  643. elapsed_time = time.time() - start_time
  644. state.execution_progress = (total_coordinates, total_coordinates, 0, elapsed_time)
  645. # Give WebSocket a chance to send the final update
  646. await asyncio.sleep(0.1)
  647. if not state.conn:
  648. logger.error("Device is not connected. Stopping pattern execution.")
  649. return
  650. await connection_manager.check_idle_async()
  651. # Set LED back to idle when pattern completes normally (not stopped early)
  652. if state.led_controller and not state.stop_requested:
  653. logger.info(f"Setting LED to idle effect: {state.dw_led_idle_effect}")
  654. state.led_controller.effect_idle(state.dw_led_idle_effect)
  655. start_idle_led_timeout()
  656. logger.debug("LED effect set to idle after pattern completion")
  657. # Only clear state if not part of a playlist
  658. if not is_playlist:
  659. state.current_playing_file = None
  660. state.execution_progress = None
  661. logger.info("Pattern execution completed and state cleared")
  662. else:
  663. logger.info("Pattern execution completed, maintaining state for playlist")
  664. # Only cancel progress update task if not part of a playlist
  665. if not is_playlist and progress_update_task:
  666. progress_update_task.cancel()
  667. try:
  668. await progress_update_task
  669. except asyncio.CancelledError:
  670. pass
  671. progress_update_task = None
  672. async def run_theta_rho_files(file_paths, pause_time=0, clear_pattern=None, run_mode="single", shuffle=False):
  673. """Run multiple .thr files in sequence with options."""
  674. state.stop_requested = False
  675. # Reset LED idle timeout activity time when playlist starts
  676. import time as time_module
  677. state.dw_led_last_activity_time = time_module.time()
  678. # Set initial playlist state
  679. state.playlist_mode = run_mode
  680. state.current_playlist_index = 0
  681. # Start progress update task for the playlist
  682. global progress_update_task
  683. if not progress_update_task:
  684. progress_update_task = asyncio.create_task(broadcast_progress())
  685. if shuffle:
  686. random.shuffle(file_paths)
  687. logger.info("Playlist shuffled")
  688. try:
  689. while True:
  690. # Load metadata cache once for all patterns (significant performance improvement)
  691. # This avoids reading the cache file from disk for every pattern
  692. cache_data = None
  693. if clear_pattern and clear_pattern in ['adaptive', 'clear_from_in', 'clear_from_out']:
  694. from modules.core import cache_manager
  695. cache_data = cache_manager.load_metadata_cache()
  696. logger.info(f"Loaded metadata cache for {len(cache_data.get('data', {}))} patterns")
  697. # Construct the complete pattern sequence
  698. pattern_sequence = []
  699. for path in file_paths:
  700. # Add clear pattern if specified
  701. if clear_pattern and clear_pattern != 'none':
  702. clear_file_path = get_clear_pattern_file(clear_pattern, path, cache_data)
  703. if clear_file_path:
  704. pattern_sequence.append(clear_file_path)
  705. # Add main pattern
  706. pattern_sequence.append(path)
  707. # Shuffle if requested
  708. if shuffle:
  709. # Get pairs of patterns (clear + main) to keep them together
  710. pairs = [pattern_sequence[i:i+2] for i in range(0, len(pattern_sequence), 2)]
  711. random.shuffle(pairs)
  712. # Flatten the pairs back into a single list
  713. pattern_sequence = [pattern for pair in pairs for pattern in pair]
  714. logger.info("Playlist shuffled")
  715. # Set the playlist to the first pattern
  716. state.current_playlist = pattern_sequence
  717. # Execute the pattern sequence
  718. for idx, file_path in enumerate(pattern_sequence):
  719. state.current_playlist_index = idx
  720. if state.stop_requested:
  721. logger.info("Execution stopped")
  722. return
  723. # Update state for main patterns only
  724. logger.info(f"Running pattern {file_path}")
  725. # Execute the pattern
  726. await run_theta_rho_file(file_path, is_playlist=True)
  727. # Handle pause between patterns
  728. if idx < len(pattern_sequence) - 1 and not state.stop_requested and pause_time > 0 and not state.skip_requested:
  729. # Check if current pattern is a clear pattern
  730. if is_clear_pattern(file_path):
  731. logger.info("Skipping pause after clear pattern")
  732. else:
  733. logger.info(f"Pausing for {pause_time} seconds")
  734. state.original_pause_time = pause_time
  735. pause_start = time.time()
  736. while time.time() - pause_start < pause_time:
  737. state.pause_time_remaining = pause_start + pause_time - time.time()
  738. if state.skip_requested:
  739. logger.info("Pause interrupted by stop/skip request")
  740. break
  741. await asyncio.sleep(1)
  742. state.pause_time_remaining = 0
  743. state.skip_requested = False
  744. if run_mode == "indefinite":
  745. logger.info("Playlist completed. Restarting as per 'indefinite' run mode")
  746. if pause_time > 0:
  747. logger.debug(f"Pausing for {pause_time} seconds before restarting")
  748. pause_start = time.time()
  749. while time.time() - pause_start < pause_time:
  750. state.pause_time_remaining = pause_start + pause_time - time.time()
  751. if state.skip_requested:
  752. logger.info("Pause interrupted by stop/skip request")
  753. break
  754. await asyncio.sleep(1)
  755. state.pause_time_remaining = 0
  756. continue
  757. else:
  758. logger.info("Playlist completed")
  759. break
  760. finally:
  761. # Clean up progress update task
  762. if progress_update_task:
  763. progress_update_task.cancel()
  764. try:
  765. await progress_update_task
  766. except asyncio.CancelledError:
  767. pass
  768. progress_update_task = None
  769. # Clear all state variables
  770. state.current_playing_file = None
  771. state.execution_progress = None
  772. state.current_playlist = None
  773. state.current_playlist_index = None
  774. state.playlist_mode = None
  775. if state.led_controller:
  776. state.led_controller.effect_idle(state.dw_led_idle_effect)
  777. start_idle_led_timeout()
  778. logger.info("All requested patterns completed (or stopped) and state cleared")
  779. async def stop_actions(clear_playlist = True, wait_for_lock = True):
  780. """Stop all current actions and wait for pattern to fully release.
  781. Args:
  782. clear_playlist: Whether to clear playlist state
  783. wait_for_lock: Whether to wait for pattern_lock to be released. Set to False when
  784. called from within pattern execution to avoid deadlock.
  785. """
  786. try:
  787. with state.pause_condition:
  788. state.pause_requested = False
  789. state.stop_requested = True
  790. state.current_playing_file = None
  791. state.execution_progress = None
  792. state.is_clearing = False
  793. if clear_playlist:
  794. # Clear playlist state
  795. state.current_playlist = None
  796. state.current_playlist_index = None
  797. state.playlist_mode = None
  798. # Cancel progress update task if we're clearing the playlist
  799. global progress_update_task
  800. if progress_update_task and not progress_update_task.done():
  801. progress_update_task.cancel()
  802. state.pause_condition.notify_all()
  803. # Wait for the pattern lock to be released before continuing
  804. # This ensures that when stop_actions completes, the pattern has fully stopped
  805. # Skip this if called from within pattern execution to avoid deadlock
  806. if wait_for_lock and pattern_lock.locked():
  807. logger.info("Waiting for pattern to fully stop...")
  808. # Acquire and immediately release the lock to ensure the pattern has exited
  809. async with pattern_lock:
  810. logger.info("Pattern lock acquired - pattern has fully stopped")
  811. # Call async function directly since we're in async context
  812. await connection_manager.update_machine_position()
  813. except Exception as e:
  814. logger.error(f"Error during stop_actions: {e}")
  815. # Ensure we still update machine position even if there's an error
  816. try:
  817. await connection_manager.update_machine_position()
  818. except Exception as update_err:
  819. logger.error(f"Error updating machine position on error: {update_err}")
  820. async def move_polar(theta, rho, speed=None):
  821. """
  822. Queue a motion command to be executed in the dedicated motion control thread.
  823. This makes motion control non-blocking for API endpoints.
  824. Args:
  825. theta (float): Target theta coordinate
  826. rho (float): Target rho coordinate
  827. speed (int, optional): Speed override. If None, uses state.speed
  828. """
  829. # Ensure motion control thread is running
  830. if not motion_controller.running:
  831. motion_controller.start()
  832. # Create future for async/await pattern
  833. loop = asyncio.get_event_loop()
  834. future = loop.create_future()
  835. # Create and queue motion command
  836. command = MotionCommand(
  837. command_type='move',
  838. theta=theta,
  839. rho=rho,
  840. speed=speed,
  841. future=future
  842. )
  843. motion_controller.command_queue.put(command)
  844. logger.debug(f"Queued motion command: theta={theta}, rho={rho}, speed={speed}")
  845. # Wait for command completion
  846. await future
  847. def pause_execution():
  848. """Pause pattern execution using asyncio Event."""
  849. logger.info("Pausing pattern execution")
  850. state.pause_requested = True
  851. pause_event.clear() # Clear the event to pause execution
  852. return True
  853. def resume_execution():
  854. """Resume pattern execution using asyncio Event."""
  855. logger.info("Resuming pattern execution")
  856. state.pause_requested = False
  857. pause_event.set() # Set the event to resume execution
  858. return True
  859. async def reset_theta():
  860. logger.info('Resetting Theta')
  861. state.current_theta = state.current_theta % (2 * pi)
  862. # Call async function directly since we're in async context
  863. await connection_manager.update_machine_position()
  864. def set_speed(new_speed):
  865. state.speed = new_speed
  866. logger.info(f'Set new state.speed {new_speed}')
  867. def get_status():
  868. """Get the current status of pattern execution."""
  869. status = {
  870. "current_file": state.current_playing_file,
  871. "is_paused": state.pause_requested or is_in_scheduled_pause_period(),
  872. "manual_pause": state.pause_requested,
  873. "scheduled_pause": is_in_scheduled_pause_period(),
  874. "is_running": bool(state.current_playing_file and not state.stop_requested),
  875. "progress": None,
  876. "playlist": None,
  877. "speed": state.speed,
  878. "pause_time_remaining": state.pause_time_remaining,
  879. "original_pause_time": getattr(state, 'original_pause_time', None),
  880. "connection_status": state.conn.is_connected() if state.conn else False,
  881. "current_theta": state.current_theta,
  882. "current_rho": state.current_rho
  883. }
  884. # Add playlist information if available
  885. if state.current_playlist and state.current_playlist_index is not None:
  886. next_index = state.current_playlist_index + 1
  887. status["playlist"] = {
  888. "current_index": state.current_playlist_index,
  889. "total_files": len(state.current_playlist),
  890. "mode": state.playlist_mode,
  891. "next_file": state.current_playlist[next_index] if next_index < len(state.current_playlist) else None
  892. }
  893. if state.execution_progress:
  894. current, total, remaining_time, elapsed_time = state.execution_progress
  895. status["progress"] = {
  896. "current": current,
  897. "total": total,
  898. "remaining_time": remaining_time,
  899. "elapsed_time": elapsed_time,
  900. "percentage": (current / total * 100) if total > 0 else 0
  901. }
  902. return status
  903. async def broadcast_progress():
  904. """Background task to broadcast progress updates."""
  905. from main import broadcast_status_update
  906. while True:
  907. # Send status updates regardless of pattern_lock state
  908. status = get_status()
  909. # Use the existing broadcast function from main.py
  910. await broadcast_status_update(status)
  911. # Check if we should stop broadcasting
  912. if not state.current_playlist:
  913. # If no playlist, only stop if no pattern is being executed
  914. if not pattern_lock.locked():
  915. logger.info("No playlist or pattern running, stopping broadcast")
  916. break
  917. # Wait before next update
  918. await asyncio.sleep(1)