pattern_manager.py 48 KB

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