pattern_manager.py 39 KB

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