pattern_manager.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. global current_playing_file, execution_progress, stop_requested, current_theta, current_rho, speed
  133. coordinates = parse_theta_rho_file(file_path)
  134. total_coordinates = len(coordinates)
  135. if total_coordinates < 2:
  136. logger.warning("Not enough coordinates for interpolation")
  137. current_playing_file = None
  138. execution_progress = None
  139. return
  140. execution_progress = (0, total_coordinates, None)
  141. stop_actions()
  142. BATCH_SIZE = 15 # Max planner buffer size
  143. with serial_manager.serial_lock:
  144. current_playing_file = file_path
  145. execution_progress = (0, 0, None)
  146. stop_requested = False
  147. logger.info(f"Starting pattern execution: {file_path}")
  148. logger.debug(f"t: {current_theta}, r: {current_rho}")
  149. reset_theta()
  150. sent_index = 0 # Tracks how many coordinates have been sent
  151. while sent_index < len(coordinates):
  152. # Check buffer
  153. buffer_status = serial_manager.check_buffer()
  154. if buffer_status:
  155. buffer_left = buffer_status["planner_buffer"]
  156. else:
  157. buffer_left = 0 # Assume empty buffer if no response
  158. # Calculate how many new coordinates to send
  159. available_slots = BATCH_SIZE - buffer_left
  160. if available_slots > 0:
  161. num_to_send = min(available_slots, len(coordinates) - sent_index)
  162. batch = coordinates[sent_index:sent_index + num_to_send]
  163. for theta, rho in batch:
  164. if stop_requested:
  165. logger.debug("Execution stopped by user.")
  166. break
  167. with pause_condition:
  168. while pause_requested:
  169. logger.debug("Execution paused...")
  170. pause_condition.wait()
  171. schedule_checker(schedule_hours)
  172. interpolate_path(theta, rho, speed)
  173. sent_index += num_to_send # Update sent index
  174. # Wait before checking buffer again
  175. time.sleep(0.1) # Check buffer every second
  176. serial_manager.check_idle()
  177. current_playing_file = None
  178. execution_progress = None
  179. logger.info("Pattern execution completed")
  180. def run_theta_rho_files(file_paths, pause_time=0, clear_pattern=None, run_mode="single", shuffle=False, schedule_hours=None):
  181. """Run multiple .thr files in sequence with options."""
  182. global stop_requested, current_playlist, current_playing_index
  183. stop_requested = False
  184. if shuffle:
  185. random.shuffle(file_paths)
  186. logger.info("Playlist shuffled")
  187. current_playlist = file_paths
  188. while True:
  189. for idx, path in enumerate(file_paths):
  190. logger.info(f"Upcoming pattern: {path}")
  191. current_playing_index = idx
  192. schedule_checker(schedule_hours)
  193. if stop_requested:
  194. logger.info("Execution stopped before starting next pattern")
  195. return
  196. if clear_pattern:
  197. if stop_requested:
  198. logger.info("Execution stopped before running the next clear pattern")
  199. return
  200. clear_file_path = get_clear_pattern_file(clear_pattern, path)
  201. logger.info(f"Running clear pattern: {clear_file_path}")
  202. run_theta_rho_file(clear_file_path, schedule_hours)
  203. if not stop_requested:
  204. logger.info(f"Running pattern {idx + 1} of {len(file_paths)}: {path}")
  205. run_theta_rho_file(path, schedule_hours)
  206. if idx < len(file_paths) - 1:
  207. if stop_requested:
  208. logger.info("Execution stopped before running the next clear pattern")
  209. return
  210. if pause_time > 0:
  211. logger.debug(f"Pausing for {pause_time} seconds")
  212. time.sleep(pause_time)
  213. if run_mode == "indefinite":
  214. logger.info("Playlist completed. Restarting as per 'indefinite' run mode")
  215. if pause_time > 0:
  216. logger.debug(f"Pausing for {pause_time} seconds before restarting")
  217. time.sleep(pause_time)
  218. if shuffle:
  219. random.shuffle(file_paths)
  220. logger.info("Playlist reshuffled for the next loop")
  221. continue
  222. else:
  223. logger.info("Playlist completed")
  224. break
  225. logger.info("All requested patterns completed (or stopped)")
  226. def stop_actions():
  227. """Stop all current pattern execution."""
  228. global pause_requested, stop_requested, current_playing_index, current_playlist, is_clearing, current_playing_file, execution_progress
  229. with pause_condition:
  230. pause_requested = False
  231. stop_requested = True
  232. current_playing_index = None
  233. current_playlist = None
  234. is_clearing = False
  235. current_playing_file = None
  236. execution_progress = None
  237. def get_status():
  238. """Get the current execution status."""
  239. global is_clearing
  240. # Update is_clearing based on current file
  241. if current_playing_file in CLEAR_PATTERNS.values():
  242. is_clearing = True
  243. else:
  244. is_clearing = False
  245. return {
  246. "ser_port": serial_manager.get_port(),
  247. "stop_requested": stop_requested,
  248. "pause_requested": pause_requested,
  249. "current_playing_file": current_playing_file,
  250. "execution_progress": execution_progress,
  251. "current_playing_index": current_playing_index,
  252. "current_playlist": current_playlist,
  253. "is_clearing": is_clearing
  254. }