1
0

pattern_manager.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  1. import os
  2. import threading
  3. import time
  4. import random
  5. import logging
  6. from datetime import datetime
  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. # Configure logging
  15. logger = logging.getLogger(__name__)
  16. # Global state
  17. THETA_RHO_DIR = './patterns'
  18. CLEAR_PATTERNS = {
  19. "clear_from_in": "./patterns/clear_from_in.thr",
  20. "clear_from_out": "./patterns/clear_from_out.thr",
  21. "clear_sideway": "./patterns/clear_sideway.thr"
  22. }
  23. os.makedirs(THETA_RHO_DIR, exist_ok=True)
  24. # Create an asyncio Event for pause/resume
  25. pause_event = asyncio.Event()
  26. pause_event.set() # Initially not paused
  27. # Create an asyncio Lock for pattern execution
  28. pattern_lock = asyncio.Lock()
  29. # Progress update task
  30. progress_update_task = None
  31. async def cleanup_pattern_manager():
  32. """Clean up pattern manager resources"""
  33. global progress_update_task, pattern_lock, pause_event
  34. try:
  35. # Cancel progress update task if running
  36. if progress_update_task and not progress_update_task.done():
  37. try:
  38. progress_update_task.cancel()
  39. # Wait for task to actually cancel
  40. try:
  41. await progress_update_task
  42. except asyncio.CancelledError:
  43. pass
  44. except Exception as e:
  45. logger.error(f"Error cancelling progress update task: {e}")
  46. # Clean up pattern lock
  47. if pattern_lock:
  48. try:
  49. if pattern_lock.locked():
  50. pattern_lock.release()
  51. pattern_lock = None
  52. except Exception as e:
  53. logger.error(f"Error cleaning up pattern lock: {e}")
  54. # Clean up pause event
  55. if pause_event:
  56. try:
  57. pause_event.set() # Wake up any waiting tasks
  58. pause_event = None
  59. except Exception as e:
  60. logger.error(f"Error cleaning up pause event: {e}")
  61. # Clean up pause condition from state
  62. if state.pause_condition:
  63. try:
  64. with state.pause_condition:
  65. state.pause_condition.notify_all()
  66. state.pause_condition = threading.Condition()
  67. except Exception as e:
  68. logger.error(f"Error cleaning up pause condition: {e}")
  69. # Clear all state variables
  70. state.current_playing_file = None
  71. state.execution_progress = 0
  72. state.is_running = False
  73. state.pause_requested = False
  74. state.stop_requested = True
  75. state.is_clearing = False
  76. # Reset machine position
  77. await connection_manager.update_machine_position()
  78. logger.info("Pattern manager resources cleaned up")
  79. except Exception as e:
  80. logger.error(f"Error during pattern manager cleanup: {e}")
  81. finally:
  82. # Ensure we always reset these
  83. progress_update_task = None
  84. pattern_lock = None
  85. pause_event = None
  86. def list_theta_rho_files():
  87. files = []
  88. for root, _, filenames in os.walk(THETA_RHO_DIR):
  89. for file in filenames:
  90. relative_path = os.path.relpath(os.path.join(root, file), THETA_RHO_DIR)
  91. files.append(relative_path)
  92. logger.debug(f"Found {len(files)} theta-rho files")
  93. return files
  94. def parse_theta_rho_file(file_path):
  95. """Parse a theta-rho file and return a list of (theta, rho) pairs."""
  96. coordinates = []
  97. try:
  98. logger.debug(f"Parsing theta-rho file: {file_path}")
  99. with open(file_path, 'r') as file:
  100. for line in file:
  101. line = line.strip()
  102. if not line or line.startswith("#"):
  103. continue
  104. try:
  105. theta, rho = map(float, line.split())
  106. coordinates.append((theta, rho))
  107. except ValueError:
  108. logger.warning(f"Skipping invalid line: {line}")
  109. continue
  110. except Exception as e:
  111. logger.error(f"Error reading file: {e}")
  112. return coordinates
  113. # Normalization Step
  114. if coordinates:
  115. first_theta = coordinates[0][0]
  116. normalized = [(theta - first_theta, rho) for theta, rho in coordinates]
  117. coordinates = normalized
  118. logger.debug(f"Parsed {len(coordinates)} coordinates from {file_path}")
  119. return coordinates
  120. def get_clear_pattern_file(clear_pattern_mode, path=None):
  121. """Return a .thr file path based on pattern_name."""
  122. if not clear_pattern_mode or clear_pattern_mode == 'none':
  123. return
  124. logger.info("Clear pattern mode: " + clear_pattern_mode)
  125. if clear_pattern_mode == "random":
  126. return random.choice(list(CLEAR_PATTERNS.values()))
  127. if clear_pattern_mode == 'adaptive':
  128. if not path:
  129. logger.warning("No path provided for adaptive clear pattern")
  130. return random.choice(list(CLEAR_PATTERNS.values()))
  131. coordinates = parse_theta_rho_file(path)
  132. if not coordinates:
  133. logger.warning("No valid coordinates found in file for adaptive clear pattern")
  134. return random.choice(list(CLEAR_PATTERNS.values()))
  135. first_rho = coordinates[0][1]
  136. if first_rho < 0.5:
  137. return CLEAR_PATTERNS['clear_from_out']
  138. else:
  139. return random.choice([CLEAR_PATTERNS['clear_from_in'], CLEAR_PATTERNS['clear_sideway']])
  140. else:
  141. if clear_pattern_mode not in CLEAR_PATTERNS:
  142. logger.warning(f"Invalid clear pattern mode: {clear_pattern_mode}")
  143. return random.choice(list(CLEAR_PATTERNS.values()))
  144. return CLEAR_PATTERNS[clear_pattern_mode]
  145. async def run_theta_rho_file(file_path, is_playlist=False):
  146. """Run a theta-rho file by sending data in optimized batches with tqdm ETA tracking."""
  147. if pattern_lock.locked():
  148. logger.warning("Another pattern is already running. Cannot start a new one.")
  149. return
  150. async with pattern_lock: # This ensures only one pattern can run at a time
  151. # Start progress update task only if not part of a playlist
  152. global progress_update_task
  153. if not is_playlist and not progress_update_task:
  154. progress_update_task = asyncio.create_task(broadcast_progress())
  155. coordinates = parse_theta_rho_file(file_path)
  156. total_coordinates = len(coordinates)
  157. if total_coordinates < 2:
  158. logger.warning("Not enough coordinates for interpolation")
  159. if not is_playlist:
  160. state.current_playing_file = None
  161. state.execution_progress = None
  162. return
  163. state.execution_progress = (0, total_coordinates, None, 0)
  164. # stop actions without resetting the playlist
  165. stop_actions(clear_playlist=False)
  166. state.current_playing_file = file_path
  167. state.stop_requested = False
  168. logger.info(f"Starting pattern execution: {file_path}")
  169. logger.info(f"t: {state.current_theta}, r: {state.current_rho}")
  170. reset_theta()
  171. start_time = time.time()
  172. if state.led_controller:
  173. effect_playing(state.led_controller)
  174. with tqdm(
  175. total=total_coordinates,
  176. unit="coords",
  177. desc=f"Executing Pattern {file_path}",
  178. dynamic_ncols=True,
  179. disable=False,
  180. mininterval=1.0
  181. ) as pbar:
  182. for i, coordinate in enumerate(coordinates):
  183. theta, rho = coordinate
  184. if state.stop_requested:
  185. logger.info("Execution stopped by user")
  186. if state.led_controller:
  187. effect_idle(state.led_controller)
  188. break
  189. # Wait for resume if paused
  190. if state.pause_requested:
  191. logger.info("Execution paused...")
  192. if state.led_controller:
  193. effect_idle(state.led_controller)
  194. await pause_event.wait()
  195. logger.info("Execution resumed...")
  196. if state.led_controller:
  197. effect_playing(state.led_controller)
  198. move_polar(theta, rho)
  199. # Update progress for all coordinates including the first one
  200. pbar.update(1)
  201. elapsed_time = time.time() - start_time
  202. estimated_remaining_time = (total_coordinates - (i + 1)) / pbar.format_dict['rate'] if pbar.format_dict['rate'] and total_coordinates else 0
  203. state.execution_progress = (i + 1, total_coordinates, estimated_remaining_time, elapsed_time)
  204. # Add a small delay to allow other async operations
  205. await asyncio.sleep(0.001)
  206. # Update progress one last time to show 100%
  207. elapsed_time = time.time() - start_time
  208. state.execution_progress = (total_coordinates, total_coordinates, 0, elapsed_time)
  209. # Give WebSocket a chance to send the final update
  210. await asyncio.sleep(0.1)
  211. connection_manager.check_idle()
  212. # Only clear state if not part of a playlist
  213. if not is_playlist:
  214. state.current_playing_file = None
  215. state.execution_progress = None
  216. logger.info("Pattern execution completed and state cleared")
  217. else:
  218. logger.info("Pattern execution completed, maintaining state for playlist")
  219. # Only cancel progress update task if not part of a playlist
  220. if not is_playlist and progress_update_task:
  221. progress_update_task.cancel()
  222. try:
  223. await progress_update_task
  224. except asyncio.CancelledError:
  225. pass
  226. progress_update_task = None
  227. if state.led_controller:
  228. effect_idle(state.led_controller)
  229. async def run_theta_rho_files(file_paths, pause_time=0, clear_pattern=None, run_mode="single", shuffle=False):
  230. """Run multiple .thr files in sequence with options."""
  231. state.stop_requested = False
  232. # Set initial playlist state
  233. state.playlist_mode = run_mode
  234. state.current_playlist_index = 0
  235. state.current_playlist = file_paths
  236. # Start progress update task for the playlist
  237. global progress_update_task
  238. if not progress_update_task:
  239. progress_update_task = asyncio.create_task(broadcast_progress())
  240. if shuffle:
  241. random.shuffle(file_paths)
  242. logger.info("Playlist shuffled")
  243. try:
  244. while True:
  245. for idx, path in enumerate(file_paths):
  246. logger.info(f"Upcoming pattern: {path}")
  247. state.current_playlist_index = idx
  248. if state.stop_requested:
  249. logger.info("Execution stopped before starting next pattern")
  250. return
  251. if clear_pattern and clear_pattern != 'none':
  252. if state.stop_requested:
  253. logger.info("Execution stopped before running the next clear pattern")
  254. return
  255. clear_file_path = get_clear_pattern_file(clear_pattern, path)
  256. if clear_file_path: # Only run clear pattern if we got a valid file path
  257. logger.info(f"Running clear pattern: {clear_file_path}")
  258. await run_theta_rho_file(clear_file_path, is_playlist=True)
  259. else:
  260. logger.info("Skipping clear pattern - no valid clear pattern file")
  261. if not state.stop_requested:
  262. logger.info(f"Running pattern {idx + 1} of {len(file_paths)}: {path}")
  263. await run_theta_rho_file(path, is_playlist=True)
  264. if idx < len(file_paths) - 1:
  265. if state.stop_requested:
  266. logger.info("Execution stopped before running the next clear pattern")
  267. return
  268. if pause_time > 0:
  269. logger.info(f"Pausing for {pause_time} seconds")
  270. await asyncio.sleep(pause_time)
  271. if run_mode == "indefinite":
  272. logger.info("Playlist completed. Restarting as per 'indefinite' run mode")
  273. if pause_time > 0:
  274. logger.debug(f"Pausing for {pause_time} seconds before restarting")
  275. await asyncio.sleep(pause_time)
  276. if shuffle:
  277. random.shuffle(file_paths)
  278. logger.info("Playlist reshuffled for the next loop")
  279. continue
  280. else:
  281. logger.info("Playlist completed")
  282. break
  283. finally:
  284. # Clean up progress update task at the end of the playlist
  285. if progress_update_task:
  286. progress_update_task.cancel()
  287. try:
  288. await progress_update_task
  289. except asyncio.CancelledError:
  290. pass
  291. progress_update_task = None
  292. # Clear all state variables
  293. state.current_playing_file = None
  294. state.execution_progress = None
  295. state.current_playlist = None
  296. state.current_playlist_index = None
  297. state.playlist_mode = None
  298. logger.info("All requested patterns completed (or stopped) and state cleared")
  299. def stop_actions(clear_playlist = True):
  300. """Stop all current actions."""
  301. try:
  302. with state.pause_condition:
  303. state.pause_requested = False
  304. state.stop_requested = True
  305. state.current_playing_file = None
  306. state.execution_progress = None
  307. state.is_clearing = False
  308. if clear_playlist:
  309. # Clear playlist state
  310. state.current_playlist = None
  311. state.current_playlist_index = None
  312. state.playlist_mode = None
  313. # Cancel progress update task if we're clearing the playlist
  314. global progress_update_task
  315. if progress_update_task and not progress_update_task.done():
  316. progress_update_task.cancel()
  317. state.pause_condition.notify_all()
  318. connection_manager.update_machine_position()
  319. except Exception as e:
  320. logger.error(f"Error during stop_actions: {e}")
  321. # Ensure we still update machine position even if there's an error
  322. connection_manager.update_machine_position()
  323. def move_polar(theta, rho):
  324. """
  325. This functions take in a pair of theta rho coordinate, compute the distance to travel based on current theta, rho,
  326. and translate the motion to gcode jog command and sent to grbl.
  327. Since having similar steps_per_mm will make x and y axis moves at around the same speed, we have to scale the
  328. x_steps_per_mm and y_steps_per_mm so that they are roughly the same. Here's the range of motion:
  329. X axis (angular): 50mm = 1 revolution
  330. Y axis (radial): 0 => 20mm = theta 0 (center) => 1 (perimeter)
  331. Args:
  332. theta (_type_): _description_
  333. rho (_type_): _description_
  334. """
  335. # Adding soft limit to reduce hardware sound
  336. soft_limit_inner = 0.01
  337. if rho < soft_limit_inner:
  338. rho = soft_limit_inner
  339. soft_limit_outter = 0.015
  340. if rho > (1-soft_limit_outter):
  341. rho = (1-soft_limit_outter)
  342. if state.gear_ratio == 6.25:
  343. x_scaling_factor = 2
  344. y_scaling_factor = 3.7
  345. else:
  346. x_scaling_factor = 2
  347. y_scaling_factor = 5
  348. delta_theta = theta - state.current_theta
  349. delta_rho = rho - state.current_rho
  350. x_increment = delta_theta * 100 / (2 * pi * x_scaling_factor) # Added -1 to reverse direction
  351. y_increment = delta_rho * 100 / y_scaling_factor
  352. x_total_steps = state.x_steps_per_mm * (100/x_scaling_factor)
  353. y_total_steps = state.y_steps_per_mm * (100/y_scaling_factor)
  354. offset = x_increment * (x_total_steps * x_scaling_factor / (state.gear_ratio * y_total_steps * y_scaling_factor))
  355. if state.gear_ratio == 6.25:
  356. y_increment -= offset
  357. else:
  358. y_increment += offset
  359. new_x_abs = state.machine_x + x_increment
  360. new_y_abs = state.machine_y + y_increment
  361. # dynamic_speed = compute_dynamic_speed(rho, max_speed=state.speed)
  362. connection_manager.send_grbl_coordinates(round(new_x_abs, 3), round(new_y_abs,3), state.speed)
  363. state.current_theta = theta
  364. state.current_rho = rho
  365. state.machine_x = new_x_abs
  366. state.machine_y = new_y_abs
  367. def pause_execution():
  368. """Pause pattern execution using asyncio Event."""
  369. logger.info("Pausing pattern execution")
  370. state.pause_requested = True
  371. pause_event.clear() # Clear the event to pause execution
  372. return True
  373. def resume_execution():
  374. """Resume pattern execution using asyncio Event."""
  375. logger.info("Resuming pattern execution")
  376. state.pause_requested = False
  377. pause_event.set() # Set the event to resume execution
  378. return True
  379. def reset_theta():
  380. logger.info('Resetting Theta')
  381. state.current_theta = 0
  382. connection_manager.update_machine_position()
  383. def set_speed(new_speed):
  384. state.speed = new_speed
  385. logger.info(f'Set new state.speed {new_speed}')
  386. def get_status():
  387. """Get the current status of pattern execution."""
  388. status = {
  389. "current_file": state.current_playing_file,
  390. "is_paused": state.pause_requested,
  391. "is_running": bool(state.current_playing_file and not state.stop_requested),
  392. "progress": None,
  393. "playlist": None,
  394. "speed": state.speed
  395. }
  396. # Add playlist information if available
  397. if state.current_playlist and state.current_playlist_index is not None:
  398. next_index = state.current_playlist_index + 1
  399. status["playlist"] = {
  400. "current_index": state.current_playlist_index,
  401. "total_files": len(state.current_playlist),
  402. "mode": state.playlist_mode,
  403. "next_file": state.current_playlist[next_index] if next_index < len(state.current_playlist) else (state.current_playlist[0] if state.playlist_mode == "loop" else None)
  404. }
  405. if state.execution_progress:
  406. current, total, remaining_time, elapsed_time = state.execution_progress
  407. status["progress"] = {
  408. "current": current,
  409. "total": total,
  410. "remaining_time": remaining_time,
  411. "elapsed_time": elapsed_time,
  412. "percentage": (current / total * 100) if total > 0 else 0
  413. }
  414. return status
  415. async def broadcast_progress():
  416. """Background task to broadcast progress updates."""
  417. from app import active_status_connections
  418. while True:
  419. # Send status updates regardless of pattern_lock state
  420. status = get_status()
  421. disconnected = set()
  422. # Create a copy of the set for iteration
  423. active_connections = active_status_connections.copy()
  424. for websocket in active_connections:
  425. try:
  426. await websocket.send_json(status)
  427. except Exception as e:
  428. logger.warning(f"Failed to send status update: {e}")
  429. disconnected.add(websocket)
  430. # Clean up disconnected clients
  431. if disconnected:
  432. active_status_connections.difference_update(disconnected)
  433. # Check if we should stop broadcasting
  434. if not state.current_playlist:
  435. # If no playlist, only stop if no pattern is being executed
  436. if not pattern_lock.locked():
  437. logger.info("No playlist or pattern running, stopping broadcast")
  438. break
  439. # Wait before next update
  440. await asyncio.sleep(1)