pattern_manager.py 39 KB

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