pattern_manager.py 11 KB

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