pattern_manager.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  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. file_name = os.path.basename(file_path)
  367. # Use provided cache_data if available, otherwise load from disk
  368. if cache_data is not None:
  369. # Extract metadata directly from provided cache
  370. data_section = cache_data.get('data', {})
  371. if file_name in data_section:
  372. cached_entry = data_section[file_name]
  373. metadata = cached_entry.get('metadata')
  374. # When cache_data is provided, trust it without checking mtime
  375. # This significantly speeds up bulk operations (playlists with 1000+ patterns)
  376. # by avoiding 1000+ os.path.getmtime() calls on slow storage (e.g., Pi SD cards)
  377. if metadata and 'first_coordinate' in metadata:
  378. return metadata['first_coordinate']['y']
  379. else:
  380. # Fall back to loading cache from disk (original behavior)
  381. metadata = cache_manager.get_pattern_metadata(file_name)
  382. if metadata and 'first_coordinate' in metadata:
  383. # In the cache, 'x' is theta and 'y' is rho
  384. return metadata['first_coordinate']['y']
  385. # Fallback to parsing the file if not in cache
  386. logger.debug(f"Metadata not cached for {file_name}, parsing file")
  387. coordinates = parse_theta_rho_file(file_path)
  388. if coordinates:
  389. return coordinates[0][1] # Return rho value
  390. return None
  391. except Exception as e:
  392. logger.warning(f"Error getting first rho from cache for {file_path}: {str(e)}")
  393. return None
  394. def get_clear_pattern_file(clear_pattern_mode, path=None, cache_data=None):
  395. """Return a .thr file path based on pattern_name and table type.
  396. Args:
  397. clear_pattern_mode: The clear pattern mode to use
  398. path: Optional path to the pattern file for adaptive mode
  399. cache_data: Optional pre-loaded cache data dict to avoid repeated disk I/O
  400. """
  401. if not clear_pattern_mode or clear_pattern_mode == 'none':
  402. return
  403. # Define patterns for each table type
  404. clear_patterns = {
  405. 'dune_weaver': {
  406. 'clear_from_out': './patterns/clear_from_out.thr',
  407. 'clear_from_in': './patterns/clear_from_in.thr',
  408. 'clear_sideway': './patterns/clear_sideway.thr'
  409. },
  410. 'dune_weaver_mini': {
  411. 'clear_from_out': './patterns/clear_from_out_mini.thr',
  412. 'clear_from_in': './patterns/clear_from_in_mini.thr',
  413. 'clear_sideway': './patterns/clear_sideway_mini.thr'
  414. },
  415. 'dune_weaver_pro': {
  416. 'clear_from_out': './patterns/clear_from_out_pro.thr',
  417. 'clear_from_out_Ultra': './patterns/clear_from_out_Ultra.thr',
  418. 'clear_from_in': './patterns/clear_from_in_pro.thr',
  419. 'clear_from_in_Ultra': './patterns/clear_from_in_Ultra.thr',
  420. 'clear_sideway': './patterns/clear_sideway_pro.thr'
  421. }
  422. }
  423. # Get patterns for current table type, fallback to standard patterns if type not found
  424. table_patterns = clear_patterns.get(state.table_type, clear_patterns['dune_weaver'])
  425. # Check for custom patterns first
  426. if state.custom_clear_from_out and clear_pattern_mode in ['clear_from_out', 'adaptive']:
  427. if clear_pattern_mode == 'adaptive':
  428. # For adaptive mode, use cached metadata to check first rho
  429. if path:
  430. first_rho = get_first_rho_from_cache(path, cache_data)
  431. if first_rho is not None and first_rho < 0.5:
  432. # Use custom clear_from_out if set
  433. custom_path = os.path.join('./patterns', state.custom_clear_from_out)
  434. if os.path.exists(custom_path):
  435. logger.debug(f"Using custom clear_from_out: {custom_path}")
  436. return custom_path
  437. elif clear_pattern_mode == 'clear_from_out':
  438. custom_path = os.path.join('./patterns', state.custom_clear_from_out)
  439. if os.path.exists(custom_path):
  440. logger.debug(f"Using custom clear_from_out: {custom_path}")
  441. return custom_path
  442. if state.custom_clear_from_in and clear_pattern_mode in ['clear_from_in', 'adaptive']:
  443. if clear_pattern_mode == 'adaptive':
  444. # For adaptive mode, use cached metadata to check first rho
  445. if path:
  446. first_rho = get_first_rho_from_cache(path, cache_data)
  447. if first_rho is not None and first_rho >= 0.5:
  448. # Use custom clear_from_in if set
  449. custom_path = os.path.join('./patterns', state.custom_clear_from_in)
  450. if os.path.exists(custom_path):
  451. logger.debug(f"Using custom clear_from_in: {custom_path}")
  452. return custom_path
  453. elif clear_pattern_mode == 'clear_from_in':
  454. custom_path = os.path.join('./patterns', state.custom_clear_from_in)
  455. if os.path.exists(custom_path):
  456. logger.debug(f"Using custom clear_from_in: {custom_path}")
  457. return custom_path
  458. logger.debug(f"Clear pattern mode: {clear_pattern_mode} for table type: {state.table_type}")
  459. if clear_pattern_mode == "random":
  460. return random.choice(list(table_patterns.values()))
  461. if clear_pattern_mode == 'adaptive':
  462. if not path:
  463. logger.warning("No path provided for adaptive clear pattern")
  464. return random.choice(list(table_patterns.values()))
  465. # Use cached metadata to get first rho value
  466. first_rho = get_first_rho_from_cache(path, cache_data)
  467. if first_rho is None:
  468. logger.warning("Could not determine first rho value for adaptive clear pattern")
  469. return random.choice(list(table_patterns.values()))
  470. if first_rho < 0.5:
  471. return table_patterns['clear_from_out']
  472. else:
  473. return table_patterns['clear_from_in']
  474. else:
  475. if clear_pattern_mode not in table_patterns:
  476. return False
  477. return table_patterns[clear_pattern_mode]
  478. def is_clear_pattern(file_path):
  479. """Check if a file path is a clear pattern file."""
  480. # Get all possible clear pattern files for all table types
  481. clear_patterns = []
  482. for table_type in ['dune_weaver', 'dune_weaver_mini', 'dune_weaver_pro']:
  483. clear_patterns.extend([
  484. f'./patterns/clear_from_out{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr',
  485. f'./patterns/clear_from_in{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr',
  486. f'./patterns/clear_sideway{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr'
  487. ])
  488. # Normalize paths for comparison
  489. normalized_path = os.path.normpath(file_path)
  490. normalized_clear_patterns = [os.path.normpath(p) for p in clear_patterns]
  491. # Check if the file path matches any clear pattern path
  492. return normalized_path in normalized_clear_patterns
  493. async def run_theta_rho_file(file_path, is_playlist=False):
  494. """Run a theta-rho file by sending data in optimized batches with tqdm ETA tracking."""
  495. if pattern_lock.locked():
  496. logger.warning("Another pattern is already running. Cannot start a new one.")
  497. return
  498. async with pattern_lock: # This ensures only one pattern can run at a time
  499. # Start progress update task only if not part of a playlist
  500. global progress_update_task
  501. if not is_playlist and not progress_update_task:
  502. progress_update_task = asyncio.create_task(broadcast_progress())
  503. coordinates = parse_theta_rho_file(file_path)
  504. total_coordinates = len(coordinates)
  505. if total_coordinates < 2:
  506. logger.warning("Not enough coordinates for interpolation")
  507. if not is_playlist:
  508. state.current_playing_file = None
  509. state.execution_progress = None
  510. return
  511. # Determine if this is a clearing pattern
  512. is_clear_file = is_clear_pattern(file_path)
  513. if is_clear_file:
  514. initial_speed = state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  515. logger.info(f"Running clearing pattern at initial speed {initial_speed}")
  516. else:
  517. logger.info(f"Running normal pattern at initial speed {state.speed}")
  518. state.execution_progress = (0, total_coordinates, None, 0)
  519. # stop actions without resetting the playlist
  520. await stop_actions(clear_playlist=False)
  521. state.current_playing_file = file_path
  522. state.stop_requested = False
  523. logger.info(f"Starting pattern execution: {file_path}")
  524. logger.info(f"t: {state.current_theta}, r: {state.current_rho}")
  525. await reset_theta()
  526. start_time = time.time()
  527. if state.led_controller:
  528. effect_playing(state.led_controller)
  529. with tqdm(
  530. total=total_coordinates,
  531. unit="coords",
  532. desc=f"Executing Pattern {file_path}",
  533. dynamic_ncols=True,
  534. disable=False,
  535. mininterval=1.0
  536. ) as pbar:
  537. for i, coordinate in enumerate(coordinates):
  538. theta, rho = coordinate
  539. if state.stop_requested:
  540. logger.info("Execution stopped by user")
  541. if state.led_controller:
  542. effect_idle(state.led_controller)
  543. break
  544. if state.skip_requested:
  545. logger.info("Skipping pattern...")
  546. await connection_manager.check_idle_async()
  547. if state.led_controller:
  548. effect_idle(state.led_controller)
  549. break
  550. # Wait for resume if paused (manual or scheduled)
  551. manual_pause = state.pause_requested
  552. scheduled_pause = is_in_scheduled_pause_period()
  553. if manual_pause or scheduled_pause:
  554. if manual_pause and scheduled_pause:
  555. logger.info("Execution paused (manual + scheduled pause active)...")
  556. elif manual_pause:
  557. logger.info("Execution paused (manual)...")
  558. else:
  559. logger.info("Execution paused (scheduled pause period)...")
  560. # Turn off WLED if scheduled pause and control_wled is enabled
  561. if state.scheduled_pause_control_wled and state.led_controller:
  562. logger.info("Turning off WLED lights during Still Sands period")
  563. state.led_controller.set_power(0)
  564. # Only show idle effect if NOT in scheduled pause with WLED control
  565. # (manual pause always shows idle effect)
  566. if state.led_controller and not (scheduled_pause and state.scheduled_pause_control_wled):
  567. effect_idle(state.led_controller)
  568. # Remember if we turned off WLED for scheduled pause
  569. wled_was_off_for_scheduled = scheduled_pause and state.scheduled_pause_control_wled and not manual_pause
  570. # Wait until both manual pause is released AND we're outside scheduled pause period
  571. while state.pause_requested or is_in_scheduled_pause_period():
  572. await asyncio.sleep(1) # Check every second
  573. # Also wait for the pause event in case of manual pause
  574. if state.pause_requested:
  575. await pause_event.wait()
  576. logger.info("Execution resumed...")
  577. if state.led_controller:
  578. # Turn WLED back on if it was turned off for scheduled pause
  579. if wled_was_off_for_scheduled:
  580. logger.info("Turning WLED lights back on as Still Sands period ended")
  581. state.led_controller.set_power(1)
  582. effect_playing(state.led_controller)
  583. # Dynamically determine the speed for each movement
  584. # Use clear_pattern_speed if it's set and this is a clear file, otherwise use state.speed
  585. if is_clear_file and state.clear_pattern_speed is not None:
  586. current_speed = state.clear_pattern_speed
  587. else:
  588. current_speed = state.speed
  589. await move_polar(theta, rho, current_speed)
  590. # Update progress for all coordinates including the first one
  591. pbar.update(1)
  592. elapsed_time = time.time() - start_time
  593. estimated_remaining_time = (total_coordinates - (i + 1)) / pbar.format_dict['rate'] if pbar.format_dict['rate'] and total_coordinates else 0
  594. state.execution_progress = (i + 1, total_coordinates, estimated_remaining_time, elapsed_time)
  595. # Add a small delay to allow other async operations
  596. await asyncio.sleep(0.001)
  597. # Update progress one last time to show 100%
  598. elapsed_time = time.time() - start_time
  599. state.execution_progress = (total_coordinates, total_coordinates, 0, elapsed_time)
  600. # Give WebSocket a chance to send the final update
  601. await asyncio.sleep(0.1)
  602. if not state.conn:
  603. logger.error("Device is not connected. Stopping pattern execution.")
  604. return
  605. await connection_manager.check_idle_async()
  606. # Set LED back to idle when pattern completes normally (not stopped early)
  607. if state.led_controller and not state.stop_requested:
  608. effect_idle(state.led_controller)
  609. logger.debug("LED effect set to idle after pattern completion")
  610. # Only clear state if not part of a playlist
  611. if not is_playlist:
  612. state.current_playing_file = None
  613. state.execution_progress = None
  614. logger.info("Pattern execution completed and state cleared")
  615. else:
  616. logger.info("Pattern execution completed, maintaining state for playlist")
  617. # Only cancel progress update task if not part of a playlist
  618. if not is_playlist and progress_update_task:
  619. progress_update_task.cancel()
  620. try:
  621. await progress_update_task
  622. except asyncio.CancelledError:
  623. pass
  624. progress_update_task = None
  625. async def run_theta_rho_files(file_paths, pause_time=0, clear_pattern=None, run_mode="single", shuffle=False):
  626. """Run multiple .thr files in sequence with options."""
  627. state.stop_requested = False
  628. # Set initial playlist state
  629. state.playlist_mode = run_mode
  630. state.current_playlist_index = 0
  631. # Start progress update task for the playlist
  632. global progress_update_task
  633. if not progress_update_task:
  634. progress_update_task = asyncio.create_task(broadcast_progress())
  635. if shuffle:
  636. random.shuffle(file_paths)
  637. logger.info("Playlist shuffled")
  638. try:
  639. while True:
  640. # Load metadata cache once for all patterns (significant performance improvement)
  641. # This avoids reading the cache file from disk for every pattern
  642. cache_data = None
  643. if clear_pattern and clear_pattern in ['adaptive', 'clear_from_in', 'clear_from_out']:
  644. from modules.core import cache_manager
  645. cache_data = cache_manager.load_metadata_cache()
  646. logger.info(f"Loaded metadata cache for {len(cache_data.get('data', {}))} patterns")
  647. # Construct the complete pattern sequence
  648. pattern_sequence = []
  649. for path in file_paths:
  650. # Add clear pattern if specified
  651. if clear_pattern and clear_pattern != 'none':
  652. clear_file_path = get_clear_pattern_file(clear_pattern, path, cache_data)
  653. if clear_file_path:
  654. pattern_sequence.append(clear_file_path)
  655. # Add main pattern
  656. pattern_sequence.append(path)
  657. # Shuffle if requested
  658. if shuffle:
  659. # Get pairs of patterns (clear + main) to keep them together
  660. pairs = [pattern_sequence[i:i+2] for i in range(0, len(pattern_sequence), 2)]
  661. random.shuffle(pairs)
  662. # Flatten the pairs back into a single list
  663. pattern_sequence = [pattern for pair in pairs for pattern in pair]
  664. logger.info("Playlist shuffled")
  665. # Set the playlist to the first pattern
  666. state.current_playlist = pattern_sequence
  667. # Execute the pattern sequence
  668. for idx, file_path in enumerate(pattern_sequence):
  669. state.current_playlist_index = idx
  670. if state.stop_requested:
  671. logger.info("Execution stopped")
  672. return
  673. # Update state for main patterns only
  674. logger.info(f"Running pattern {file_path}")
  675. # Execute the pattern
  676. await run_theta_rho_file(file_path, is_playlist=True)
  677. # Handle pause between patterns
  678. if idx < len(pattern_sequence) - 1 and not state.stop_requested and pause_time > 0 and not state.skip_requested:
  679. # Check if current pattern is a clear pattern
  680. if is_clear_pattern(file_path):
  681. logger.info("Skipping pause after clear pattern")
  682. else:
  683. logger.info(f"Pausing for {pause_time} seconds")
  684. state.original_pause_time = pause_time
  685. pause_start = time.time()
  686. while time.time() - pause_start < pause_time:
  687. state.pause_time_remaining = pause_start + pause_time - time.time()
  688. if state.skip_requested:
  689. logger.info("Pause interrupted by stop/skip request")
  690. break
  691. await asyncio.sleep(1)
  692. state.pause_time_remaining = 0
  693. state.skip_requested = False
  694. if run_mode == "indefinite":
  695. logger.info("Playlist completed. Restarting as per 'indefinite' run mode")
  696. if pause_time > 0:
  697. logger.debug(f"Pausing for {pause_time} seconds before restarting")
  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. continue
  707. else:
  708. logger.info("Playlist completed")
  709. break
  710. finally:
  711. # Clean up progress update task
  712. if progress_update_task:
  713. progress_update_task.cancel()
  714. try:
  715. await progress_update_task
  716. except asyncio.CancelledError:
  717. pass
  718. progress_update_task = None
  719. # Clear all state variables
  720. state.current_playing_file = None
  721. state.execution_progress = None
  722. state.current_playlist = None
  723. state.current_playlist_index = None
  724. state.playlist_mode = None
  725. if state.led_controller:
  726. effect_idle(state.led_controller)
  727. logger.info("All requested patterns completed (or stopped) and state cleared")
  728. async def stop_actions(clear_playlist = True):
  729. """Stop all current actions and wait for pattern to fully release."""
  730. try:
  731. with state.pause_condition:
  732. state.pause_requested = False
  733. state.stop_requested = True
  734. state.current_playing_file = None
  735. state.execution_progress = None
  736. state.is_clearing = False
  737. if clear_playlist:
  738. # Clear playlist state
  739. state.current_playlist = None
  740. state.current_playlist_index = None
  741. state.playlist_mode = None
  742. # Cancel progress update task if we're clearing the playlist
  743. global progress_update_task
  744. if progress_update_task and not progress_update_task.done():
  745. progress_update_task.cancel()
  746. state.pause_condition.notify_all()
  747. # Wait for the pattern lock to be released before continuing
  748. # This ensures that when stop_actions completes, the pattern has fully stopped
  749. if pattern_lock.locked():
  750. logger.info("Waiting for pattern to fully stop...")
  751. # Acquire and immediately release the lock to ensure the pattern has exited
  752. async with pattern_lock:
  753. logger.info("Pattern lock acquired - pattern has fully stopped")
  754. # Call async function directly since we're in async context
  755. await connection_manager.update_machine_position()
  756. except Exception as e:
  757. logger.error(f"Error during stop_actions: {e}")
  758. # Ensure we still update machine position even if there's an error
  759. try:
  760. await connection_manager.update_machine_position()
  761. except Exception as update_err:
  762. logger.error(f"Error updating machine position on error: {update_err}")
  763. async def move_polar(theta, rho, speed=None):
  764. """
  765. Queue a motion command to be executed in the dedicated motion control thread.
  766. This makes motion control non-blocking for API endpoints.
  767. Args:
  768. theta (float): Target theta coordinate
  769. rho (float): Target rho coordinate
  770. speed (int, optional): Speed override. If None, uses state.speed
  771. """
  772. # Ensure motion control thread is running
  773. if not motion_controller.running:
  774. motion_controller.start()
  775. # Create future for async/await pattern
  776. loop = asyncio.get_event_loop()
  777. future = loop.create_future()
  778. # Create and queue motion command
  779. command = MotionCommand(
  780. command_type='move',
  781. theta=theta,
  782. rho=rho,
  783. speed=speed,
  784. future=future
  785. )
  786. motion_controller.command_queue.put(command)
  787. logger.debug(f"Queued motion command: theta={theta}, rho={rho}, speed={speed}")
  788. # Wait for command completion
  789. await future
  790. def pause_execution():
  791. """Pause pattern execution using asyncio Event."""
  792. logger.info("Pausing pattern execution")
  793. state.pause_requested = True
  794. pause_event.clear() # Clear the event to pause execution
  795. return True
  796. def resume_execution():
  797. """Resume pattern execution using asyncio Event."""
  798. logger.info("Resuming pattern execution")
  799. state.pause_requested = False
  800. pause_event.set() # Set the event to resume execution
  801. return True
  802. async def reset_theta():
  803. logger.info('Resetting Theta')
  804. state.current_theta = state.current_theta % (2 * pi)
  805. # Call async function directly since we're in async context
  806. await connection_manager.update_machine_position()
  807. def set_speed(new_speed):
  808. state.speed = new_speed
  809. logger.info(f'Set new state.speed {new_speed}')
  810. def get_status():
  811. """Get the current status of pattern execution."""
  812. status = {
  813. "current_file": state.current_playing_file,
  814. "is_paused": state.pause_requested or is_in_scheduled_pause_period(),
  815. "manual_pause": state.pause_requested,
  816. "scheduled_pause": is_in_scheduled_pause_period(),
  817. "is_running": bool(state.current_playing_file and not state.stop_requested),
  818. "progress": None,
  819. "playlist": None,
  820. "speed": state.speed,
  821. "pause_time_remaining": state.pause_time_remaining,
  822. "original_pause_time": getattr(state, 'original_pause_time', None),
  823. "connection_status": state.conn.is_connected() if state.conn else False,
  824. "current_theta": state.current_theta,
  825. "current_rho": state.current_rho
  826. }
  827. # Add playlist information if available
  828. if state.current_playlist and state.current_playlist_index is not None:
  829. next_index = state.current_playlist_index + 1
  830. status["playlist"] = {
  831. "current_index": state.current_playlist_index,
  832. "total_files": len(state.current_playlist),
  833. "mode": state.playlist_mode,
  834. "next_file": state.current_playlist[next_index] if next_index < len(state.current_playlist) else None
  835. }
  836. if state.execution_progress:
  837. current, total, remaining_time, elapsed_time = state.execution_progress
  838. status["progress"] = {
  839. "current": current,
  840. "total": total,
  841. "remaining_time": remaining_time,
  842. "elapsed_time": elapsed_time,
  843. "percentage": (current / total * 100) if total > 0 else 0
  844. }
  845. return status
  846. async def broadcast_progress():
  847. """Background task to broadcast progress updates."""
  848. from main import broadcast_status_update
  849. while True:
  850. # Send status updates regardless of pattern_lock state
  851. status = get_status()
  852. # Use the existing broadcast function from main.py
  853. await broadcast_status_update(status)
  854. # Check if we should stop broadcasting
  855. if not state.current_playlist:
  856. # If no playlist, only stop if no pattern is being executed
  857. if not pattern_lock.locked():
  858. logger.info("No playlist or pattern running, stopping broadcast")
  859. break
  860. # Wait before next update
  861. await asyncio.sleep(1)