1
0

pattern_manager.py 43 KB

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