pattern_manager.py 36 KB

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