pattern_manager.py 10 KB

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