pattern_manager.py 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  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. # Update ball tracking (manager checks if it's active internally)
  262. if state.ball_tracking_manager:
  263. state.ball_tracking_manager.update_position(theta, rho)
  264. def _send_grbl_coordinates_sync(self, x: float, y: float, speed: int = 600, timeout: int = 2, home: bool = False):
  265. """Synchronous version of send_grbl_coordinates for motion thread."""
  266. logger.debug(f"Motion thread sending G-code: X{x} Y{y} at F{speed}")
  267. # Track overall attempt time
  268. overall_start_time = time.time()
  269. while True:
  270. try:
  271. gcode = f"$J=G91 G21 Y{y} F{speed}" if home else f"G1 X{x} Y{y} F{speed}"
  272. state.conn.send(gcode + "\n")
  273. logger.debug(f"Motion thread sent command: {gcode}")
  274. start_time = time.time()
  275. while True:
  276. response = state.conn.readline()
  277. logger.debug(f"Motion thread response: {response}")
  278. if response.lower() == "ok":
  279. logger.debug("Motion thread: Command execution confirmed.")
  280. return
  281. except Exception as e:
  282. error_str = str(e)
  283. logger.warning(f"Motion thread error sending command: {error_str}")
  284. # Immediately return for device not configured errors
  285. if "Device not configured" in error_str or "Errno 6" in error_str:
  286. logger.error(f"Motion thread: Device configuration error detected: {error_str}")
  287. state.stop_requested = True
  288. state.conn = None
  289. state.is_connected = False
  290. logger.info("Connection marked as disconnected due to device error")
  291. return False
  292. logger.warning(f"Motion thread: No 'ok' received for X{x} Y{y}, speed {speed}. Retrying...")
  293. time.sleep(0.1)
  294. # Global motion control thread instance
  295. motion_controller = MotionControlThread()
  296. async def cleanup_pattern_manager():
  297. """Clean up pattern manager resources"""
  298. global progress_update_task, pattern_lock, pause_event
  299. try:
  300. # Stop motion control thread
  301. motion_controller.stop()
  302. # Cancel progress update task if running
  303. if progress_update_task and not progress_update_task.done():
  304. try:
  305. progress_update_task.cancel()
  306. # Wait for task to actually cancel
  307. try:
  308. await progress_update_task
  309. except asyncio.CancelledError:
  310. pass
  311. except Exception as e:
  312. logger.error(f"Error cancelling progress update task: {e}")
  313. # Clean up pattern lock
  314. if pattern_lock:
  315. try:
  316. if pattern_lock.locked():
  317. pattern_lock.release()
  318. pattern_lock = None
  319. except Exception as e:
  320. logger.error(f"Error cleaning up pattern lock: {e}")
  321. # Clean up pause event
  322. if pause_event:
  323. try:
  324. pause_event.set() # Wake up any waiting tasks
  325. pause_event = None
  326. except Exception as e:
  327. logger.error(f"Error cleaning up pause event: {e}")
  328. # Clean up pause condition from state
  329. if state.pause_condition:
  330. try:
  331. with state.pause_condition:
  332. state.pause_condition.notify_all()
  333. state.pause_condition = threading.Condition()
  334. except Exception as e:
  335. logger.error(f"Error cleaning up pause condition: {e}")
  336. # Clear all state variables
  337. state.current_playing_file = None
  338. state.execution_progress = 0
  339. state.is_running = False
  340. state.pause_requested = False
  341. state.stop_requested = True
  342. state.is_clearing = False
  343. # Reset machine position
  344. await connection_manager.update_machine_position()
  345. logger.info("Pattern manager resources cleaned up")
  346. except Exception as e:
  347. logger.error(f"Error during pattern manager cleanup: {e}")
  348. finally:
  349. # Ensure we always reset these
  350. progress_update_task = None
  351. pattern_lock = None
  352. pause_event = None
  353. def list_theta_rho_files():
  354. files = []
  355. for root, dirs, filenames in os.walk(THETA_RHO_DIR):
  356. # Skip cached_images directories to avoid scanning thousands of WebP files
  357. if 'cached_images' in dirs:
  358. dirs.remove('cached_images')
  359. # Filter .thr files during traversal for better performance
  360. thr_files = [f for f in filenames if f.endswith('.thr')]
  361. for file in thr_files:
  362. relative_path = os.path.relpath(os.path.join(root, file), THETA_RHO_DIR)
  363. # Normalize path separators to always use forward slashes for consistency across platforms
  364. relative_path = relative_path.replace(os.sep, '/')
  365. files.append(relative_path)
  366. logger.debug(f"Found {len(files)} theta-rho files")
  367. return files
  368. def parse_theta_rho_file(file_path):
  369. """Parse a theta-rho file and return a list of (theta, rho) pairs."""
  370. coordinates = []
  371. try:
  372. logger.debug(f"Parsing theta-rho file: {file_path}")
  373. with open(file_path, 'r', encoding='utf-8') as file:
  374. for line in file:
  375. line = line.strip()
  376. if not line or line.startswith("#"):
  377. continue
  378. try:
  379. theta, rho = map(float, line.split())
  380. coordinates.append((theta, rho))
  381. except ValueError:
  382. logger.warning(f"Skipping invalid line: {line}")
  383. continue
  384. except Exception as e:
  385. logger.error(f"Error reading file: {e}")
  386. return coordinates
  387. logger.debug(f"Parsed {len(coordinates)} coordinates from {file_path}")
  388. return coordinates
  389. def get_first_rho_from_cache(file_path, cache_data=None):
  390. """Get the first rho value from cached metadata, falling back to file parsing if needed.
  391. Args:
  392. file_path: Path to the pattern file
  393. cache_data: Optional pre-loaded cache data dict to avoid repeated disk I/O
  394. """
  395. try:
  396. # Import cache_manager locally to avoid circular import
  397. from modules.core import cache_manager
  398. # Try to get from metadata cache first
  399. # Use relative path from THETA_RHO_DIR to match cache keys (which include subdirectories)
  400. file_name = os.path.relpath(file_path, THETA_RHO_DIR)
  401. # Use provided cache_data if available, otherwise load from disk
  402. if cache_data is not None:
  403. # Extract metadata directly from provided cache
  404. data_section = cache_data.get('data', {})
  405. if file_name in data_section:
  406. cached_entry = data_section[file_name]
  407. metadata = cached_entry.get('metadata')
  408. # When cache_data is provided, trust it without checking mtime
  409. # This significantly speeds up bulk operations (playlists with 1000+ patterns)
  410. # by avoiding 1000+ os.path.getmtime() calls on slow storage (e.g., Pi SD cards)
  411. if metadata and 'first_coordinate' in metadata:
  412. return metadata['first_coordinate']['y']
  413. else:
  414. # Fall back to loading cache from disk (original behavior)
  415. metadata = cache_manager.get_pattern_metadata(file_name)
  416. if metadata and 'first_coordinate' in metadata:
  417. # In the cache, 'x' is theta and 'y' is rho
  418. return metadata['first_coordinate']['y']
  419. # Fallback to parsing the file if not in cache
  420. logger.debug(f"Metadata not cached for {file_name}, parsing file")
  421. coordinates = parse_theta_rho_file(file_path)
  422. if coordinates:
  423. return coordinates[0][1] # Return rho value
  424. return None
  425. except Exception as e:
  426. logger.warning(f"Error getting first rho from cache for {file_path}: {str(e)}")
  427. return None
  428. def get_clear_pattern_file(clear_pattern_mode, path=None, cache_data=None):
  429. """Return a .thr file path based on pattern_name and table type.
  430. Args:
  431. clear_pattern_mode: The clear pattern mode to use
  432. path: Optional path to the pattern file for adaptive mode
  433. cache_data: Optional pre-loaded cache data dict to avoid repeated disk I/O
  434. """
  435. if not clear_pattern_mode or clear_pattern_mode == 'none':
  436. return
  437. # Define patterns for each table type
  438. clear_patterns = {
  439. 'dune_weaver': {
  440. 'clear_from_out': './patterns/clear_from_out.thr',
  441. 'clear_from_in': './patterns/clear_from_in.thr',
  442. 'clear_sideway': './patterns/clear_sideway.thr'
  443. },
  444. 'dune_weaver_mini': {
  445. 'clear_from_out': './patterns/clear_from_out_mini.thr',
  446. 'clear_from_in': './patterns/clear_from_in_mini.thr',
  447. 'clear_sideway': './patterns/clear_sideway_mini.thr'
  448. },
  449. 'dune_weaver_pro': {
  450. 'clear_from_out': './patterns/clear_from_out_pro.thr',
  451. 'clear_from_out_Ultra': './patterns/clear_from_out_Ultra.thr',
  452. 'clear_from_in': './patterns/clear_from_in_pro.thr',
  453. 'clear_from_in_Ultra': './patterns/clear_from_in_Ultra.thr',
  454. 'clear_sideway': './patterns/clear_sideway_pro.thr'
  455. }
  456. }
  457. # Get patterns for current table type, fallback to standard patterns if type not found
  458. table_patterns = clear_patterns.get(state.table_type, clear_patterns['dune_weaver'])
  459. # Check for custom patterns first
  460. if state.custom_clear_from_out and clear_pattern_mode in ['clear_from_out', 'adaptive']:
  461. if clear_pattern_mode == 'adaptive':
  462. # For adaptive mode, use cached metadata to check first rho
  463. if path:
  464. first_rho = get_first_rho_from_cache(path, cache_data)
  465. if first_rho is not None and first_rho < 0.5:
  466. # Use custom clear_from_out if set
  467. custom_path = os.path.join('./patterns', state.custom_clear_from_out)
  468. if os.path.exists(custom_path):
  469. logger.debug(f"Using custom clear_from_out: {custom_path}")
  470. return custom_path
  471. elif clear_pattern_mode == 'clear_from_out':
  472. custom_path = os.path.join('./patterns', state.custom_clear_from_out)
  473. if os.path.exists(custom_path):
  474. logger.debug(f"Using custom clear_from_out: {custom_path}")
  475. return custom_path
  476. if state.custom_clear_from_in and clear_pattern_mode in ['clear_from_in', 'adaptive']:
  477. if clear_pattern_mode == 'adaptive':
  478. # For adaptive mode, use cached metadata to check first rho
  479. if path:
  480. first_rho = get_first_rho_from_cache(path, cache_data)
  481. if first_rho is not None and first_rho >= 0.5:
  482. # Use custom clear_from_in if set
  483. custom_path = os.path.join('./patterns', state.custom_clear_from_in)
  484. if os.path.exists(custom_path):
  485. logger.debug(f"Using custom clear_from_in: {custom_path}")
  486. return custom_path
  487. elif clear_pattern_mode == 'clear_from_in':
  488. custom_path = os.path.join('./patterns', state.custom_clear_from_in)
  489. if os.path.exists(custom_path):
  490. logger.debug(f"Using custom clear_from_in: {custom_path}")
  491. return custom_path
  492. logger.debug(f"Clear pattern mode: {clear_pattern_mode} for table type: {state.table_type}")
  493. if clear_pattern_mode == "random":
  494. return random.choice(list(table_patterns.values()))
  495. if clear_pattern_mode == 'adaptive':
  496. if not path:
  497. logger.warning("No path provided for adaptive clear pattern")
  498. return random.choice(list(table_patterns.values()))
  499. # Use cached metadata to get first rho value
  500. first_rho = get_first_rho_from_cache(path, cache_data)
  501. if first_rho is None:
  502. logger.warning("Could not determine first rho value for adaptive clear pattern")
  503. return random.choice(list(table_patterns.values()))
  504. if first_rho < 0.5:
  505. return table_patterns['clear_from_out']
  506. else:
  507. return table_patterns['clear_from_in']
  508. else:
  509. if clear_pattern_mode not in table_patterns:
  510. return False
  511. return table_patterns[clear_pattern_mode]
  512. def is_clear_pattern(file_path):
  513. """Check if a file path is a clear pattern file."""
  514. # Get all possible clear pattern files for all table types
  515. clear_patterns = []
  516. for table_type in ['dune_weaver', 'dune_weaver_mini', 'dune_weaver_pro']:
  517. clear_patterns.extend([
  518. f'./patterns/clear_from_out{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr',
  519. f'./patterns/clear_from_in{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr',
  520. f'./patterns/clear_sideway{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr'
  521. ])
  522. # Normalize paths for comparison
  523. normalized_path = os.path.normpath(file_path)
  524. normalized_clear_patterns = [os.path.normpath(p) for p in clear_patterns]
  525. # Check if the file path matches any clear pattern path
  526. return normalized_path in normalized_clear_patterns
  527. async def run_theta_rho_file(file_path, is_playlist=False):
  528. """Run a theta-rho file by sending data in optimized batches with tqdm ETA tracking."""
  529. if pattern_lock.locked():
  530. logger.warning("Another pattern is already running. Cannot start a new one.")
  531. return
  532. async with pattern_lock: # This ensures only one pattern can run at a time
  533. # Start progress update task only if not part of a playlist
  534. global progress_update_task
  535. if not is_playlist and not progress_update_task:
  536. progress_update_task = asyncio.create_task(broadcast_progress())
  537. coordinates = parse_theta_rho_file(file_path)
  538. total_coordinates = len(coordinates)
  539. if total_coordinates < 2:
  540. logger.warning("Not enough coordinates for interpolation")
  541. if not is_playlist:
  542. state.current_playing_file = None
  543. state.execution_progress = None
  544. return
  545. # Determine if this is a clearing pattern
  546. is_clear_file = is_clear_pattern(file_path)
  547. if is_clear_file:
  548. initial_speed = state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  549. logger.info(f"Running clearing pattern at initial speed {initial_speed}")
  550. else:
  551. logger.info(f"Running normal pattern at initial speed {state.speed}")
  552. state.execution_progress = (0, total_coordinates, None, 0)
  553. # stop actions without resetting the playlist, and don't wait for lock (we already have it)
  554. await stop_actions(clear_playlist=False, wait_for_lock=False)
  555. state.current_playing_file = file_path
  556. state.stop_requested = False
  557. # Reset LED idle timeout activity time when pattern starts
  558. import time as time_module
  559. state.dw_led_last_activity_time = time_module.time()
  560. logger.info(f"Starting pattern execution: {file_path}")
  561. logger.info(f"t: {state.current_theta}, r: {state.current_rho}")
  562. await reset_theta()
  563. start_time = time.time()
  564. if state.led_controller:
  565. logger.info(f"Setting LED to playing effect: {state.dw_led_playing_effect}")
  566. state.led_controller.effect_playing(state.dw_led_playing_effect)
  567. # Cancel idle timeout when playing starts
  568. idle_timeout_manager.cancel_timeout()
  569. # Start ball tracking if mode is "playing_only"
  570. if state.ball_tracking_mode == "playing_only" and state.ball_tracking_manager:
  571. logger.info("Starting ball tracking (playing_only mode)")
  572. state.ball_tracking_manager.start()
  573. with tqdm(
  574. total=total_coordinates,
  575. unit="coords",
  576. desc=f"Executing Pattern {file_path}",
  577. dynamic_ncols=True,
  578. disable=False,
  579. mininterval=1.0
  580. ) as pbar:
  581. for i, coordinate in enumerate(coordinates):
  582. theta, rho = coordinate
  583. if state.stop_requested:
  584. logger.info("Execution stopped by user")
  585. if state.led_controller:
  586. state.led_controller.effect_idle(state.dw_led_idle_effect)
  587. start_idle_led_timeout()
  588. # Stop ball tracking on stop
  589. if state.ball_tracking_mode == "playing_only" and state.ball_tracking_manager:
  590. state.ball_tracking_manager.stop()
  591. break
  592. if state.skip_requested:
  593. logger.info("Skipping pattern...")
  594. await connection_manager.check_idle_async()
  595. if state.led_controller:
  596. state.led_controller.effect_idle(state.dw_led_idle_effect)
  597. start_idle_led_timeout()
  598. # Stop ball tracking on skip
  599. if state.ball_tracking_mode == "playing_only" and state.ball_tracking_manager:
  600. state.ball_tracking_manager.stop()
  601. break
  602. # Wait for resume if paused (manual or scheduled)
  603. manual_pause = state.pause_requested
  604. scheduled_pause = is_in_scheduled_pause_period()
  605. if manual_pause or scheduled_pause:
  606. if manual_pause and scheduled_pause:
  607. logger.info("Execution paused (manual + scheduled pause active)...")
  608. elif manual_pause:
  609. logger.info("Execution paused (manual)...")
  610. else:
  611. logger.info("Execution paused (scheduled pause period)...")
  612. # Turn off LED controller if scheduled pause and control_wled is enabled
  613. if state.scheduled_pause_control_wled and state.led_controller:
  614. logger.info("Turning off LED lights during Still Sands period")
  615. state.led_controller.set_power(0)
  616. # Only show idle effect if NOT in scheduled pause with LED control
  617. # (manual pause always shows idle effect)
  618. if state.led_controller and not (scheduled_pause and state.scheduled_pause_control_wled):
  619. state.led_controller.effect_idle(state.dw_led_idle_effect)
  620. start_idle_led_timeout()
  621. # Remember if we turned off LED controller for scheduled pause
  622. wled_was_off_for_scheduled = scheduled_pause and state.scheduled_pause_control_wled and not manual_pause
  623. # Wait until both manual pause is released AND we're outside scheduled pause period
  624. while state.pause_requested or is_in_scheduled_pause_period():
  625. await asyncio.sleep(1) # Check every second
  626. # Also wait for the pause event in case of manual pause
  627. if state.pause_requested:
  628. await pause_event.wait()
  629. logger.info("Execution resumed...")
  630. if state.led_controller:
  631. # Turn LED controller back on if it was turned off for scheduled pause
  632. if wled_was_off_for_scheduled:
  633. logger.info("Turning LED lights back on as Still Sands period ended")
  634. state.led_controller.set_power(1)
  635. # CRITICAL: Give LED controller time to fully power on before sending more commands
  636. # Without this delay, rapid-fire requests can crash controllers on resource-constrained Pis
  637. await asyncio.sleep(0.5)
  638. state.led_controller.effect_playing(state.dw_led_playing_effect)
  639. # Cancel idle timeout when resuming from pause
  640. idle_timeout_manager.cancel_timeout()
  641. # Dynamically determine the speed for each movement
  642. # Use clear_pattern_speed if it's set and this is a clear file, otherwise use state.speed
  643. if is_clear_file and state.clear_pattern_speed is not None:
  644. current_speed = state.clear_pattern_speed
  645. else:
  646. current_speed = state.speed
  647. await move_polar(theta, rho, current_speed)
  648. # Update progress for all coordinates including the first one
  649. pbar.update(1)
  650. elapsed_time = time.time() - start_time
  651. estimated_remaining_time = (total_coordinates - (i + 1)) / pbar.format_dict['rate'] if pbar.format_dict['rate'] and total_coordinates else 0
  652. state.execution_progress = (i + 1, total_coordinates, estimated_remaining_time, elapsed_time)
  653. # Add a small delay to allow other async operations
  654. await asyncio.sleep(0.001)
  655. # Update progress one last time to show 100%
  656. elapsed_time = time.time() - start_time
  657. state.execution_progress = (total_coordinates, total_coordinates, 0, elapsed_time)
  658. # Give WebSocket a chance to send the final update
  659. await asyncio.sleep(0.1)
  660. if not state.conn:
  661. logger.error("Device is not connected. Stopping pattern execution.")
  662. return
  663. await connection_manager.check_idle_async()
  664. # Set LED back to idle when pattern completes normally (not stopped early)
  665. if state.led_controller and not state.stop_requested:
  666. logger.info(f"Setting LED to idle effect: {state.dw_led_idle_effect}")
  667. state.led_controller.effect_idle(state.dw_led_idle_effect)
  668. start_idle_led_timeout()
  669. logger.debug("LED effect set to idle after pattern completion")
  670. # Stop ball tracking if mode is "playing_only"
  671. if state.ball_tracking_mode == "playing_only" and state.ball_tracking_manager:
  672. logger.info("Stopping ball tracking (pattern completed)")
  673. state.ball_tracking_manager.stop()
  674. # Only clear state if not part of a playlist
  675. if not is_playlist:
  676. state.current_playing_file = None
  677. state.execution_progress = None
  678. logger.info("Pattern execution completed and state cleared")
  679. else:
  680. logger.info("Pattern execution completed, maintaining state for playlist")
  681. # Only cancel progress update task if not part of a playlist
  682. if not is_playlist and progress_update_task:
  683. progress_update_task.cancel()
  684. try:
  685. await progress_update_task
  686. except asyncio.CancelledError:
  687. pass
  688. progress_update_task = None
  689. async def run_theta_rho_files(file_paths, pause_time=0, clear_pattern=None, run_mode="single", shuffle=False):
  690. """Run multiple .thr files in sequence with options."""
  691. state.stop_requested = False
  692. # Reset LED idle timeout activity time when playlist starts
  693. import time as time_module
  694. state.dw_led_last_activity_time = time_module.time()
  695. # Set initial playlist state
  696. state.playlist_mode = run_mode
  697. state.current_playlist_index = 0
  698. # Start progress update task for the playlist
  699. global progress_update_task
  700. if not progress_update_task:
  701. progress_update_task = asyncio.create_task(broadcast_progress())
  702. if shuffle:
  703. random.shuffle(file_paths)
  704. logger.info("Playlist shuffled")
  705. try:
  706. while True:
  707. # Load metadata cache once for all patterns (significant performance improvement)
  708. # This avoids reading the cache file from disk for every pattern
  709. cache_data = None
  710. if clear_pattern and clear_pattern in ['adaptive', 'clear_from_in', 'clear_from_out']:
  711. from modules.core import cache_manager
  712. cache_data = cache_manager.load_metadata_cache()
  713. logger.info(f"Loaded metadata cache for {len(cache_data.get('data', {}))} patterns")
  714. # Construct the complete pattern sequence
  715. pattern_sequence = []
  716. for path in file_paths:
  717. # Add clear pattern if specified
  718. if clear_pattern and clear_pattern != 'none':
  719. clear_file_path = get_clear_pattern_file(clear_pattern, path, cache_data)
  720. if clear_file_path:
  721. pattern_sequence.append(clear_file_path)
  722. # Add main pattern
  723. pattern_sequence.append(path)
  724. # Shuffle if requested
  725. if shuffle:
  726. # Get pairs of patterns (clear + main) to keep them together
  727. pairs = [pattern_sequence[i:i+2] for i in range(0, len(pattern_sequence), 2)]
  728. random.shuffle(pairs)
  729. # Flatten the pairs back into a single list
  730. pattern_sequence = [pattern for pair in pairs for pattern in pair]
  731. logger.info("Playlist shuffled")
  732. # Set the playlist to the first pattern
  733. state.current_playlist = pattern_sequence
  734. # Execute the pattern sequence
  735. for idx, file_path in enumerate(pattern_sequence):
  736. state.current_playlist_index = idx
  737. if state.stop_requested:
  738. logger.info("Execution stopped")
  739. return
  740. # Update state for main patterns only
  741. logger.info(f"Running pattern {file_path}")
  742. # Execute the pattern
  743. await run_theta_rho_file(file_path, is_playlist=True)
  744. # Handle pause between patterns
  745. if idx < len(pattern_sequence) - 1 and not state.stop_requested and pause_time > 0 and not state.skip_requested:
  746. # Check if current pattern is a clear pattern
  747. if is_clear_pattern(file_path):
  748. logger.info("Skipping pause after clear pattern")
  749. else:
  750. logger.info(f"Pausing for {pause_time} seconds")
  751. state.original_pause_time = pause_time
  752. pause_start = time.time()
  753. while time.time() - pause_start < pause_time:
  754. state.pause_time_remaining = pause_start + pause_time - time.time()
  755. if state.skip_requested:
  756. logger.info("Pause interrupted by stop/skip request")
  757. break
  758. await asyncio.sleep(1)
  759. state.pause_time_remaining = 0
  760. state.skip_requested = False
  761. if run_mode == "indefinite":
  762. logger.info("Playlist completed. Restarting as per 'indefinite' run mode")
  763. if pause_time > 0:
  764. logger.debug(f"Pausing for {pause_time} seconds before restarting")
  765. pause_start = time.time()
  766. while time.time() - pause_start < pause_time:
  767. state.pause_time_remaining = pause_start + pause_time - time.time()
  768. if state.skip_requested:
  769. logger.info("Pause interrupted by stop/skip request")
  770. break
  771. await asyncio.sleep(1)
  772. state.pause_time_remaining = 0
  773. continue
  774. else:
  775. logger.info("Playlist completed")
  776. break
  777. finally:
  778. # Clean up progress update task
  779. if progress_update_task:
  780. progress_update_task.cancel()
  781. try:
  782. await progress_update_task
  783. except asyncio.CancelledError:
  784. pass
  785. progress_update_task = None
  786. # Clear all state variables
  787. state.current_playing_file = None
  788. state.execution_progress = None
  789. state.current_playlist = None
  790. state.current_playlist_index = None
  791. state.playlist_mode = None
  792. if state.led_controller:
  793. state.led_controller.effect_idle(state.dw_led_idle_effect)
  794. start_idle_led_timeout()
  795. logger.info("All requested patterns completed (or stopped) and state cleared")
  796. async def stop_actions(clear_playlist = True, wait_for_lock = True):
  797. """Stop all current actions and wait for pattern to fully release.
  798. Args:
  799. clear_playlist: Whether to clear playlist state
  800. wait_for_lock: Whether to wait for pattern_lock to be released. Set to False when
  801. called from within pattern execution to avoid deadlock.
  802. """
  803. try:
  804. with state.pause_condition:
  805. state.pause_requested = False
  806. state.stop_requested = True
  807. state.current_playing_file = None
  808. state.execution_progress = None
  809. state.is_clearing = False
  810. if clear_playlist:
  811. # Clear playlist state
  812. state.current_playlist = None
  813. state.current_playlist_index = None
  814. state.playlist_mode = None
  815. # Cancel progress update task if we're clearing the playlist
  816. global progress_update_task
  817. if progress_update_task and not progress_update_task.done():
  818. progress_update_task.cancel()
  819. state.pause_condition.notify_all()
  820. # Wait for the pattern lock to be released before continuing
  821. # This ensures that when stop_actions completes, the pattern has fully stopped
  822. # Skip this if called from within pattern execution to avoid deadlock
  823. if wait_for_lock and pattern_lock.locked():
  824. logger.info("Waiting for pattern to fully stop...")
  825. # Acquire and immediately release the lock to ensure the pattern has exited
  826. async with pattern_lock:
  827. logger.info("Pattern lock acquired - pattern has fully stopped")
  828. # Call async function directly since we're in async context
  829. await connection_manager.update_machine_position()
  830. except Exception as e:
  831. logger.error(f"Error during stop_actions: {e}")
  832. # Ensure we still update machine position even if there's an error
  833. try:
  834. await connection_manager.update_machine_position()
  835. except Exception as update_err:
  836. logger.error(f"Error updating machine position on error: {update_err}")
  837. async def move_polar(theta, rho, speed=None):
  838. """
  839. Queue a motion command to be executed in the dedicated motion control thread.
  840. This makes motion control non-blocking for API endpoints.
  841. Args:
  842. theta (float): Target theta coordinate
  843. rho (float): Target rho coordinate
  844. speed (int, optional): Speed override. If None, uses state.speed
  845. """
  846. # Ensure motion control thread is running
  847. if not motion_controller.running:
  848. motion_controller.start()
  849. # Create future for async/await pattern
  850. loop = asyncio.get_event_loop()
  851. future = loop.create_future()
  852. # Create and queue motion command
  853. command = MotionCommand(
  854. command_type='move',
  855. theta=theta,
  856. rho=rho,
  857. speed=speed,
  858. future=future
  859. )
  860. motion_controller.command_queue.put(command)
  861. logger.debug(f"Queued motion command: theta={theta}, rho={rho}, speed={speed}")
  862. # Wait for command completion
  863. await future
  864. def pause_execution():
  865. """Pause pattern execution using asyncio Event."""
  866. logger.info("Pausing pattern execution")
  867. state.pause_requested = True
  868. pause_event.clear() # Clear the event to pause execution
  869. return True
  870. def resume_execution():
  871. """Resume pattern execution using asyncio Event."""
  872. logger.info("Resuming pattern execution")
  873. state.pause_requested = False
  874. pause_event.set() # Set the event to resume execution
  875. return True
  876. async def reset_theta():
  877. logger.info('Resetting Theta')
  878. state.current_theta = state.current_theta % (2 * pi)
  879. # Call async function directly since we're in async context
  880. await connection_manager.update_machine_position()
  881. def set_speed(new_speed):
  882. state.speed = new_speed
  883. logger.info(f'Set new state.speed {new_speed}')
  884. def get_status():
  885. """Get the current status of pattern execution."""
  886. status = {
  887. "current_file": state.current_playing_file,
  888. "is_paused": state.pause_requested or is_in_scheduled_pause_period(),
  889. "manual_pause": state.pause_requested,
  890. "scheduled_pause": is_in_scheduled_pause_period(),
  891. "is_running": bool(state.current_playing_file and not state.stop_requested),
  892. "progress": None,
  893. "playlist": None,
  894. "speed": state.speed,
  895. "pause_time_remaining": state.pause_time_remaining,
  896. "original_pause_time": getattr(state, 'original_pause_time', None),
  897. "connection_status": state.conn.is_connected() if state.conn else False,
  898. "current_theta": state.current_theta,
  899. "current_rho": state.current_rho
  900. }
  901. # Add playlist information if available
  902. if state.current_playlist and state.current_playlist_index is not None:
  903. next_index = state.current_playlist_index + 1
  904. status["playlist"] = {
  905. "current_index": state.current_playlist_index,
  906. "total_files": len(state.current_playlist),
  907. "mode": state.playlist_mode,
  908. "next_file": state.current_playlist[next_index] if next_index < len(state.current_playlist) else None
  909. }
  910. if state.execution_progress:
  911. current, total, remaining_time, elapsed_time = state.execution_progress
  912. status["progress"] = {
  913. "current": current,
  914. "total": total,
  915. "remaining_time": remaining_time,
  916. "elapsed_time": elapsed_time,
  917. "percentage": (current / total * 100) if total > 0 else 0
  918. }
  919. return status
  920. async def broadcast_progress():
  921. """Background task to broadcast progress updates."""
  922. from main import broadcast_status_update
  923. while True:
  924. # Send status updates regardless of pattern_lock state
  925. status = get_status()
  926. # Use the existing broadcast function from main.py
  927. await broadcast_status_update(status)
  928. # Check if we should stop broadcasting
  929. if not state.current_playlist:
  930. # If no playlist, only stop if no pattern is being executed
  931. if not pattern_lock.locked():
  932. logger.info("No playlist or pattern running, stopping broadcast")
  933. break
  934. # Wait before next update
  935. await asyncio.sleep(1)