1
0

pattern_manager.py 42 KB

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