pattern_manager.py 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  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. scheduled_pause = is_in_scheduled_pause_period()
  597. if manual_pause or scheduled_pause:
  598. if manual_pause and scheduled_pause:
  599. logger.info("Execution paused (manual + scheduled pause active)...")
  600. elif manual_pause:
  601. logger.info("Execution paused (manual)...")
  602. else:
  603. logger.info("Execution paused (scheduled pause period)...")
  604. # Turn off LED controller if scheduled pause and control_wled is enabled
  605. if state.scheduled_pause_control_wled and state.led_controller:
  606. logger.info("Turning off LED lights during Still Sands period")
  607. state.led_controller.set_power(0)
  608. # Only show idle effect if NOT in scheduled pause with LED control
  609. # (manual pause always shows idle effect)
  610. if state.led_controller and not (scheduled_pause and state.scheduled_pause_control_wled):
  611. state.led_controller.effect_idle(state.dw_led_idle_effect)
  612. start_idle_led_timeout()
  613. # Remember if we turned off LED controller for scheduled pause
  614. wled_was_off_for_scheduled = scheduled_pause and state.scheduled_pause_control_wled and not manual_pause
  615. # Wait until both manual pause is released AND we're outside scheduled pause period
  616. while state.pause_requested or is_in_scheduled_pause_period():
  617. await asyncio.sleep(1) # Check every second
  618. # Also wait for the pause event in case of manual pause
  619. if state.pause_requested:
  620. await pause_event.wait()
  621. logger.info("Execution resumed...")
  622. if state.led_controller:
  623. # Turn LED controller back on if it was turned off for scheduled pause
  624. if wled_was_off_for_scheduled:
  625. logger.info("Turning LED lights back on as Still Sands period ended")
  626. state.led_controller.set_power(1)
  627. # CRITICAL: Give LED controller time to fully power on before sending more commands
  628. # Without this delay, rapid-fire requests can crash controllers on resource-constrained Pis
  629. await asyncio.sleep(0.5)
  630. state.led_controller.effect_playing(state.dw_led_playing_effect)
  631. # Cancel idle timeout when resuming from pause
  632. idle_timeout_manager.cancel_timeout()
  633. # Dynamically determine the speed for each movement
  634. # Use clear_pattern_speed if it's set and this is a clear file, otherwise use state.speed
  635. if is_clear_file and state.clear_pattern_speed is not None:
  636. current_speed = state.clear_pattern_speed
  637. else:
  638. current_speed = state.speed
  639. await move_polar(theta, rho, current_speed)
  640. # Update progress for all coordinates including the first one
  641. pbar.update(1)
  642. elapsed_time = time.time() - start_time
  643. estimated_remaining_time = (total_coordinates - (i + 1)) / pbar.format_dict['rate'] if pbar.format_dict['rate'] and total_coordinates else 0
  644. state.execution_progress = (i + 1, total_coordinates, estimated_remaining_time, elapsed_time)
  645. # Add a small delay to allow other async operations
  646. await asyncio.sleep(0.001)
  647. # Update progress one last time to show 100%
  648. elapsed_time = time.time() - start_time
  649. state.execution_progress = (total_coordinates, total_coordinates, 0, elapsed_time)
  650. # Give WebSocket a chance to send the final update
  651. await asyncio.sleep(0.1)
  652. if not state.conn:
  653. logger.error("Device is not connected. Stopping pattern execution.")
  654. return
  655. await connection_manager.check_idle_async()
  656. # Set LED back to idle when pattern completes normally (not stopped early)
  657. if state.led_controller and not state.stop_requested:
  658. logger.info(f"Setting LED to idle effect: {state.dw_led_idle_effect}")
  659. state.led_controller.effect_idle(state.dw_led_idle_effect)
  660. start_idle_led_timeout()
  661. logger.debug("LED effect set to idle after pattern completion")
  662. # Increment pattern count for auto-homing (only for non-clear patterns)
  663. # This happens after pattern completes successfully (not stopped or skipped)
  664. if not state.stop_requested and not state.skip_requested and not is_clear_file:
  665. state.auto_home_pattern_count += 1
  666. logger.info(f"Pattern completed. Auto-home count: {state.auto_home_pattern_count}/{state.auto_home_interval}")
  667. # Check if we should auto-home
  668. if (state.auto_home_enabled and
  669. state.homing == 1 and # Only for sensor homing mode
  670. state.auto_home_interval > 0 and
  671. state.auto_home_pattern_count >= state.auto_home_interval):
  672. logger.info(f"Auto-homing triggered after {state.auto_home_pattern_count} patterns")
  673. state.auto_home_pattern_count = 0 # Reset counter
  674. # Perform homing
  675. try:
  676. homing_success = await asyncio.to_thread(connection_manager.home)
  677. if homing_success:
  678. logger.info("Auto-homing completed successfully")
  679. else:
  680. logger.warning("Auto-homing failed")
  681. except Exception as e:
  682. logger.error(f"Error during auto-homing: {e}")
  683. # Only clear state if not part of a playlist
  684. if not is_playlist:
  685. state.current_playing_file = None
  686. state.execution_progress = None
  687. logger.info("Pattern execution completed and state cleared")
  688. else:
  689. logger.info("Pattern execution completed, maintaining state for playlist")
  690. # Only cancel progress update task if not part of a playlist
  691. if not is_playlist and progress_update_task:
  692. progress_update_task.cancel()
  693. try:
  694. await progress_update_task
  695. except asyncio.CancelledError:
  696. pass
  697. progress_update_task = None
  698. async def run_theta_rho_files(file_paths, pause_time=0, clear_pattern=None, run_mode="single", shuffle=False):
  699. """Run multiple .thr files in sequence with options."""
  700. state.stop_requested = False
  701. # Reset LED idle timeout activity time when playlist starts
  702. import time as time_module
  703. state.dw_led_last_activity_time = time_module.time()
  704. # Set initial playlist state
  705. state.playlist_mode = run_mode
  706. state.current_playlist_index = 0
  707. # Start progress update task for the playlist
  708. global progress_update_task
  709. if not progress_update_task:
  710. progress_update_task = asyncio.create_task(broadcast_progress())
  711. if shuffle:
  712. random.shuffle(file_paths)
  713. logger.info("Playlist shuffled")
  714. try:
  715. while True:
  716. # Load metadata cache once for all patterns (significant performance improvement)
  717. # This avoids reading the cache file from disk for every pattern
  718. cache_data = None
  719. if clear_pattern and clear_pattern in ['adaptive', 'clear_from_in', 'clear_from_out']:
  720. from modules.core import cache_manager
  721. cache_data = cache_manager.load_metadata_cache()
  722. logger.info(f"Loaded metadata cache for {len(cache_data.get('data', {}))} patterns")
  723. # Construct the complete pattern sequence
  724. pattern_sequence = []
  725. for path in file_paths:
  726. # Add clear pattern if specified
  727. if clear_pattern and clear_pattern != 'none':
  728. clear_file_path = get_clear_pattern_file(clear_pattern, path, cache_data)
  729. if clear_file_path:
  730. pattern_sequence.append(clear_file_path)
  731. # Add main pattern
  732. pattern_sequence.append(path)
  733. # Shuffle if requested
  734. if shuffle:
  735. # Get pairs of patterns (clear + main) to keep them together
  736. pairs = [pattern_sequence[i:i+2] for i in range(0, len(pattern_sequence), 2)]
  737. random.shuffle(pairs)
  738. # Flatten the pairs back into a single list
  739. pattern_sequence = [pattern for pair in pairs for pattern in pair]
  740. logger.info("Playlist shuffled")
  741. # Set the playlist to the first pattern
  742. state.current_playlist = pattern_sequence
  743. # Execute the pattern sequence
  744. for idx, file_path in enumerate(pattern_sequence):
  745. state.current_playlist_index = idx
  746. if state.stop_requested:
  747. logger.info("Execution stopped")
  748. return
  749. # Update state for main patterns only
  750. logger.info(f"Running pattern {file_path}")
  751. # Execute the pattern
  752. await run_theta_rho_file(file_path, is_playlist=True)
  753. # Handle pause between patterns
  754. if idx < len(pattern_sequence) - 1 and not state.stop_requested and pause_time > 0 and not state.skip_requested:
  755. # Check if current pattern is a clear pattern
  756. if is_clear_pattern(file_path):
  757. logger.info("Skipping pause after clear pattern")
  758. else:
  759. logger.info(f"Pausing for {pause_time} seconds")
  760. state.original_pause_time = pause_time
  761. pause_start = time.time()
  762. while time.time() - pause_start < pause_time:
  763. state.pause_time_remaining = pause_start + pause_time - time.time()
  764. if state.skip_requested:
  765. logger.info("Pause interrupted by stop/skip request")
  766. break
  767. await asyncio.sleep(1)
  768. state.pause_time_remaining = 0
  769. state.skip_requested = False
  770. if run_mode == "indefinite":
  771. logger.info("Playlist completed. Restarting as per 'indefinite' run mode")
  772. if pause_time > 0:
  773. logger.debug(f"Pausing for {pause_time} seconds before restarting")
  774. pause_start = time.time()
  775. while time.time() - pause_start < pause_time:
  776. state.pause_time_remaining = pause_start + pause_time - time.time()
  777. if state.skip_requested:
  778. logger.info("Pause interrupted by stop/skip request")
  779. break
  780. await asyncio.sleep(1)
  781. state.pause_time_remaining = 0
  782. continue
  783. else:
  784. logger.info("Playlist completed")
  785. break
  786. finally:
  787. # Clean up progress update task
  788. if progress_update_task:
  789. progress_update_task.cancel()
  790. try:
  791. await progress_update_task
  792. except asyncio.CancelledError:
  793. pass
  794. progress_update_task = None
  795. # Clear all state variables
  796. state.current_playing_file = None
  797. state.execution_progress = None
  798. state.current_playlist = None
  799. state.current_playlist_index = None
  800. state.playlist_mode = None
  801. if state.led_controller:
  802. state.led_controller.effect_idle(state.dw_led_idle_effect)
  803. start_idle_led_timeout()
  804. logger.info("All requested patterns completed (or stopped) and state cleared")
  805. async def stop_actions(clear_playlist = True, wait_for_lock = True):
  806. """Stop all current actions and wait for pattern to fully release.
  807. Args:
  808. clear_playlist: Whether to clear playlist state
  809. wait_for_lock: Whether to wait for pattern_lock to be released. Set to False when
  810. called from within pattern execution to avoid deadlock.
  811. """
  812. try:
  813. with state.pause_condition:
  814. state.pause_requested = False
  815. state.stop_requested = True
  816. state.current_playing_file = None
  817. state.execution_progress = None
  818. state.is_clearing = False
  819. if clear_playlist:
  820. # Clear playlist state
  821. state.current_playlist = None
  822. state.current_playlist_index = None
  823. state.playlist_mode = None
  824. # Cancel progress update task if we're clearing the playlist
  825. global progress_update_task
  826. if progress_update_task and not progress_update_task.done():
  827. progress_update_task.cancel()
  828. state.pause_condition.notify_all()
  829. # Wait for the pattern lock to be released before continuing
  830. # This ensures that when stop_actions completes, the pattern has fully stopped
  831. # Skip this if called from within pattern execution to avoid deadlock
  832. if wait_for_lock and pattern_lock.locked():
  833. logger.info("Waiting for pattern to fully stop...")
  834. # Acquire and immediately release the lock to ensure the pattern has exited
  835. async with pattern_lock:
  836. logger.info("Pattern lock acquired - pattern has fully stopped")
  837. # Call async function directly since we're in async context
  838. await connection_manager.update_machine_position()
  839. except Exception as e:
  840. logger.error(f"Error during stop_actions: {e}")
  841. # Ensure we still update machine position even if there's an error
  842. try:
  843. await connection_manager.update_machine_position()
  844. except Exception as update_err:
  845. logger.error(f"Error updating machine position on error: {update_err}")
  846. async def move_polar(theta, rho, speed=None):
  847. """
  848. Queue a motion command to be executed in the dedicated motion control thread.
  849. This makes motion control non-blocking for API endpoints.
  850. Args:
  851. theta (float): Target theta coordinate
  852. rho (float): Target rho coordinate
  853. speed (int, optional): Speed override. If None, uses state.speed
  854. """
  855. # Ensure motion control thread is running
  856. if not motion_controller.running:
  857. motion_controller.start()
  858. # Create future for async/await pattern
  859. loop = asyncio.get_event_loop()
  860. future = loop.create_future()
  861. # Create and queue motion command
  862. command = MotionCommand(
  863. command_type='move',
  864. theta=theta,
  865. rho=rho,
  866. speed=speed,
  867. future=future
  868. )
  869. motion_controller.command_queue.put(command)
  870. logger.debug(f"Queued motion command: theta={theta}, rho={rho}, speed={speed}")
  871. # Wait for command completion
  872. await future
  873. def pause_execution():
  874. """Pause pattern execution using asyncio Event."""
  875. logger.info("Pausing pattern execution")
  876. state.pause_requested = True
  877. pause_event.clear() # Clear the event to pause execution
  878. return True
  879. def resume_execution():
  880. """Resume pattern execution using asyncio Event."""
  881. logger.info("Resuming pattern execution")
  882. state.pause_requested = False
  883. pause_event.set() # Set the event to resume execution
  884. return True
  885. async def reset_theta():
  886. logger.info('Resetting Theta')
  887. state.current_theta = state.current_theta % (2 * pi)
  888. # Call async function directly since we're in async context
  889. await connection_manager.update_machine_position()
  890. def set_speed(new_speed):
  891. state.speed = new_speed
  892. logger.info(f'Set new state.speed {new_speed}')
  893. def get_status():
  894. """Get the current status of pattern execution."""
  895. status = {
  896. "current_file": state.current_playing_file,
  897. "is_paused": state.pause_requested or is_in_scheduled_pause_period(),
  898. "manual_pause": state.pause_requested,
  899. "scheduled_pause": is_in_scheduled_pause_period(),
  900. "is_running": bool(state.current_playing_file and not state.stop_requested),
  901. "progress": None,
  902. "playlist": None,
  903. "speed": state.speed,
  904. "pause_time_remaining": state.pause_time_remaining,
  905. "original_pause_time": getattr(state, 'original_pause_time', None),
  906. "connection_status": state.conn.is_connected() if state.conn else False,
  907. "current_theta": state.current_theta,
  908. "current_rho": state.current_rho
  909. }
  910. # Add playlist information if available
  911. if state.current_playlist and state.current_playlist_index is not None:
  912. next_index = state.current_playlist_index + 1
  913. status["playlist"] = {
  914. "current_index": state.current_playlist_index,
  915. "total_files": len(state.current_playlist),
  916. "mode": state.playlist_mode,
  917. "next_file": state.current_playlist[next_index] if next_index < len(state.current_playlist) else None
  918. }
  919. if state.execution_progress:
  920. current, total, remaining_time, elapsed_time = state.execution_progress
  921. status["progress"] = {
  922. "current": current,
  923. "total": total,
  924. "remaining_time": remaining_time,
  925. "elapsed_time": elapsed_time,
  926. "percentage": (current / total * 100) if total > 0 else 0
  927. }
  928. return status
  929. async def broadcast_progress():
  930. """Background task to broadcast progress updates."""
  931. from main import broadcast_status_update
  932. while True:
  933. # Send status updates regardless of pattern_lock state
  934. status = get_status()
  935. # Use the existing broadcast function from main.py
  936. await broadcast_status_update(status)
  937. # Check if we should stop broadcasting
  938. if not state.current_playlist:
  939. # If no playlist, only stop if no pattern is being executed
  940. if not pattern_lock.locked():
  941. logger.info("No playlist or pattern running, stopping broadcast")
  942. break
  943. # Wait before next update
  944. await asyncio.sleep(1)