pattern_manager.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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 dune_weaver_flask.modules.serial import serial_manager
  9. from dune_weaver_flask.modules.core.state import state
  10. from math import pi
  11. # Configure logging
  12. logger = logging.getLogger(__name__)
  13. # Global state
  14. THETA_RHO_DIR = './patterns'
  15. CLEAR_PATTERNS = {
  16. "clear_from_in": "./patterns/clear_from_in.thr",
  17. "clear_from_out": "./patterns/clear_from_out.thr",
  18. "clear_sideway": "./patterns/clear_sideway.thr"
  19. }
  20. os.makedirs(THETA_RHO_DIR, exist_ok=True)
  21. def list_theta_rho_files():
  22. files = []
  23. for root, _, filenames in os.walk(THETA_RHO_DIR):
  24. for file in filenames:
  25. relative_path = os.path.relpath(os.path.join(root, file), THETA_RHO_DIR)
  26. files.append(relative_path)
  27. logger.debug(f"Found {len(files)} theta-rho files")
  28. return files
  29. def parse_theta_rho_file(file_path):
  30. """Parse a theta-rho file and return a list of (theta, rho) pairs."""
  31. coordinates = []
  32. try:
  33. logger.debug(f"Parsing theta-rho file: {file_path}")
  34. with open(file_path, 'r') as file:
  35. for line in file:
  36. line = line.strip()
  37. if not line or line.startswith("#"):
  38. continue
  39. try:
  40. theta, rho = map(float, line.split())
  41. coordinates.append((theta, rho))
  42. except ValueError:
  43. logger.warning(f"Skipping invalid line: {line}")
  44. continue
  45. except Exception as e:
  46. logger.error(f"Error reading file: {e}")
  47. return coordinates
  48. # Normalization Step
  49. if coordinates:
  50. first_theta = coordinates[0][0]
  51. normalized = [(theta - first_theta, rho) for theta, rho in coordinates]
  52. coordinates = normalized
  53. logger.debug(f"Parsed {len(coordinates)} coordinates from {file_path}")
  54. return coordinates
  55. def get_clear_pattern_file(clear_pattern_mode, path=None):
  56. """Return a .thr file path based on pattern_name."""
  57. if not clear_pattern_mode or clear_pattern_mode == 'none':
  58. return
  59. logger.info("Clear pattern mode: " + clear_pattern_mode)
  60. if clear_pattern_mode == "random":
  61. return random.choice(list(CLEAR_PATTERNS.values()))
  62. if clear_pattern_mode == 'adaptive':
  63. _, first_rho = parse_theta_rho_file(path)[0]
  64. if first_rho < 0.5:
  65. return CLEAR_PATTERNS['clear_from_out']
  66. else:
  67. return random.choice([CLEAR_PATTERNS['clear_from_in'], CLEAR_PATTERNS['clear_sideway']])
  68. else:
  69. return CLEAR_PATTERNS[clear_pattern_mode]
  70. def schedule_checker(schedule_hours):
  71. """Pauses/resumes execution based on a given time range."""
  72. if not schedule_hours:
  73. return
  74. start_time, end_time = schedule_hours
  75. now = datetime.now().time()
  76. if start_time <= now < end_time:
  77. if state.pause_requested:
  78. logger.info("Starting execution: Within schedule")
  79. serial_manager.update_machine_position()
  80. state.pause_requested = False
  81. with state.pause_condition:
  82. state.pause_condition.notify_all()
  83. else:
  84. if not state.pause_requested:
  85. logger.info("Pausing execution: Outside schedule")
  86. state.pause_requested = True
  87. serial_manager.update_machine_position()
  88. threading.Thread(target=wait_for_start_time, args=(schedule_hours,), daemon=True).start()
  89. def wait_for_start_time(schedule_hours):
  90. """Keep checking every 30 seconds if the time is within the schedule to resume execution."""
  91. start_time, end_time = schedule_hours
  92. while state.pause_requested:
  93. now = datetime.now().time()
  94. if start_time <= now < end_time:
  95. logger.info("Resuming execution: Within schedule")
  96. state.pause_requested = False
  97. with state.pause_condition:
  98. state.pause_condition.notify_all()
  99. break
  100. else:
  101. time.sleep(30)
  102. def interpolate_path(theta, rho):
  103. delta_theta = theta - state.current_theta
  104. delta_rho = rho - state.current_rho
  105. x_increment = delta_theta / (2 * pi) * 100
  106. y_increment = delta_rho * 100/5
  107. offset = x_increment * (1600/5750/5) # Total angular steps = 16000 / gear ratio = 10 / angular steps = 5750
  108. y_increment += offset
  109. new_x_abs = state.machine_x + x_increment
  110. new_y_abs = state.machine_y + y_increment
  111. # dynamic_speed = compute_dynamic_speed(rho, max_speed=state.speed)
  112. serial_manager.send_grbl_coordinates(round(new_x_abs, 3), round(new_y_abs,3), state.speed)
  113. state.current_theta = theta
  114. state.current_rho = rho
  115. state.machine_x = new_x_abs
  116. state.machine_y = new_y_abs
  117. def reset_theta():
  118. logger.info('Resetting Theta')
  119. state.current_theta = 0
  120. serial_manager.update_machine_position()
  121. def set_speed(new_speed):
  122. state.speed = new_speed
  123. logger.info(f'Set new state.speed {new_speed}')
  124. def run_theta_rho_file(file_path, schedule_hours=None):
  125. """Run a theta-rho file by sending data in optimized batches with tqdm ETA tracking."""
  126. if not file_path:
  127. return
  128. coordinates = parse_theta_rho_file(file_path)
  129. total_coordinates = len(coordinates)
  130. if total_coordinates < 2:
  131. logger.warning("Not enough coordinates for interpolation")
  132. state.current_playing_file = None
  133. state.execution_progress = None
  134. return
  135. state.execution_progress = (0, total_coordinates, None)
  136. stop_actions()
  137. BATCH_SIZE = 15 # Max planner buffer size
  138. with serial_manager.serial_lock:
  139. state.current_playing_file = file_path
  140. state.execution_progress = (0, 0, None)
  141. state.stop_requested = False
  142. logger.info(f"Starting pattern execution: {file_path}")
  143. logger.info(f"t: {state.current_theta}, r: {state.current_rho}")
  144. reset_theta()
  145. for coordinate in tqdm(coordinates):
  146. theta, rho = coordinate
  147. if state.stop_requested:
  148. logger.info("Execution stopped by user after completing the current batch")
  149. break
  150. with state.pause_condition:
  151. while state.pause_requested:
  152. logger.info("Execution paused...")
  153. state.pause_condition.wait()
  154. schedule_checker(schedule_hours)
  155. interpolate_path(theta, rho)
  156. serial_manager.check_idle()
  157. state.current_playing_file = None
  158. state.execution_progress = None
  159. logger.info("Pattern execution completed")
  160. def run_theta_rho_files(file_paths, pause_time=0, clear_pattern=None, run_mode="single", shuffle=False, schedule_hours=None):
  161. """Run multiple .thr files in sequence with options."""
  162. state.stop_requested = False
  163. if shuffle:
  164. random.shuffle(file_paths)
  165. logger.info("Playlist shuffled")
  166. state.current_playlist = file_paths
  167. while True:
  168. for idx, path in enumerate(file_paths):
  169. logger.info(f"Upcoming pattern: {path}")
  170. state.current_playing_index = idx
  171. schedule_checker(schedule_hours)
  172. if state.stop_requested:
  173. logger.info("Execution stopped before starting next pattern")
  174. return
  175. if clear_pattern:
  176. if state.stop_requested:
  177. logger.info("Execution stopped before running the next clear pattern")
  178. return
  179. clear_file_path = get_clear_pattern_file(clear_pattern, path)
  180. logger.info(f"Running clear pattern: {clear_file_path}")
  181. run_theta_rho_file(clear_file_path, schedule_hours)
  182. if not state.stop_requested:
  183. logger.info(f"Running pattern {idx + 1} of {len(file_paths)}: {path}")
  184. run_theta_rho_file(path, schedule_hours)
  185. if idx < len(file_paths) - 1:
  186. if state.stop_requested:
  187. logger.info("Execution stopped before running the next clear pattern")
  188. return
  189. if pause_time > 0:
  190. logger.debug(f"Pausing for {pause_time} seconds")
  191. time.sleep(pause_time)
  192. if run_mode == "indefinite":
  193. logger.info("Playlist completed. Restarting as per 'indefinite' run mode")
  194. if pause_time > 0:
  195. logger.debug(f"Pausing for {pause_time} seconds before restarting")
  196. time.sleep(pause_time)
  197. if shuffle:
  198. random.shuffle(file_paths)
  199. logger.info("Playlist reshuffled for the next loop")
  200. continue
  201. else:
  202. logger.info("Playlist completed")
  203. break
  204. logger.info("All requested patterns completed (or stopped)")
  205. def stop_actions():
  206. """Stop all current pattern execution."""
  207. with state.pause_condition:
  208. state.pause_requested = False
  209. state.stop_requested = True
  210. state.current_playing_index = None
  211. state.current_playlist = None
  212. state.is_clearing = False
  213. state.current_playing_file = None
  214. state.execution_progress = None
  215. serial_manager.update_machine_position()
  216. def get_status():
  217. """Get the current execution status."""
  218. # Update state.is_clearing based on current file
  219. if state.current_playing_file in CLEAR_PATTERNS.values():
  220. state.is_clearing = True
  221. else:
  222. state.is_clearing = False
  223. return {
  224. "ser_port": serial_manager.get_port(),
  225. "state.stop_requested": state.stop_requested,
  226. "state.pause_requested": state.pause_requested,
  227. "state.current_playing_file": state.current_playing_file,
  228. "state.execution_progress": state.execution_progress,
  229. "state.current_playing_index": state.current_playing_index,
  230. "state.current_playlist": state.current_playlist,
  231. "state.is_clearing": state.is_clearing
  232. }