pattern_manager.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. import os
  2. import threading
  3. import time
  4. import random
  5. from datetime import datetime
  6. from tqdm import tqdm
  7. from dune_weaver_flask.modules.serial.serial_manager import serial_manager
  8. class PatternManager:
  9. def __init__(self):
  10. self.THETA_RHO_DIR = './patterns'
  11. self.CLEAR_PATTERNS = {
  12. "clear_from_in": "./patterns/clear_from_in.thr",
  13. "clear_from_out": "./patterns/clear_from_out.thr",
  14. "clear_sideway": "./patterns/clear_sideway.thr"
  15. }
  16. os.makedirs(self.THETA_RHO_DIR, exist_ok=True)
  17. # Execution state
  18. self.stop_requested = False
  19. self.pause_requested = False
  20. self.pause_condition = threading.Condition()
  21. self.current_playing_file = None
  22. self.execution_progress = None
  23. self.current_playing_index = None
  24. self.current_playlist = None
  25. self.is_clearing = False
  26. def parse_theta_rho_file(self, file_path):
  27. """Parse a theta-rho file and return a list of (theta, rho) pairs."""
  28. coordinates = []
  29. try:
  30. with open(file_path, 'r') as file:
  31. for line in file:
  32. line = line.strip()
  33. if not line or line.startswith("#"):
  34. continue
  35. try:
  36. theta, rho = map(float, line.split())
  37. coordinates.append((theta, rho))
  38. except ValueError:
  39. print(f"Skipping invalid line: {line}")
  40. continue
  41. except Exception as e:
  42. print(f"Error reading file: {e}")
  43. return coordinates
  44. # Normalization Step
  45. if coordinates:
  46. first_theta = coordinates[0][0]
  47. normalized = [(theta - first_theta, rho) for theta, rho in coordinates]
  48. coordinates = normalized
  49. return coordinates
  50. def get_clear_pattern_file(self, clear_pattern_mode, path=None):
  51. """Return a .thr file path based on pattern_name."""
  52. if not clear_pattern_mode or clear_pattern_mode == 'none':
  53. return
  54. print("Clear pattern mode: " + clear_pattern_mode)
  55. if clear_pattern_mode == "random":
  56. return random.choice(list(self.CLEAR_PATTERNS.values()))
  57. if clear_pattern_mode == 'adaptive':
  58. _, first_rho = self.parse_theta_rho_file(path)[0]
  59. if first_rho < 0.5:
  60. return self.CLEAR_PATTERNS['clear_from_out']
  61. else:
  62. return random.choice([self.CLEAR_PATTERNS['clear_from_in'], self.CLEAR_PATTERNS['clear_sideway']])
  63. else:
  64. return self.CLEAR_PATTERNS[clear_pattern_mode]
  65. def schedule_checker(self, schedule_hours):
  66. """Pauses/resumes execution based on a given time range."""
  67. if not schedule_hours:
  68. return
  69. start_time, end_time = schedule_hours
  70. now = datetime.now().time()
  71. if start_time <= now < end_time:
  72. if self.pause_requested:
  73. print("Starting execution: Within schedule.")
  74. self.pause_requested = False
  75. with self.pause_condition:
  76. self.pause_condition.notify_all()
  77. else:
  78. if not self.pause_requested:
  79. print("Pausing execution: Outside schedule.")
  80. self.pause_requested = True
  81. threading.Thread(target=self.wait_for_start_time, args=(schedule_hours,), daemon=True).start()
  82. def wait_for_start_time(self, schedule_hours):
  83. """Keep checking every 30 seconds if the time is within the schedule to resume execution."""
  84. start_time, end_time = schedule_hours
  85. while self.pause_requested:
  86. now = datetime.now().time()
  87. if start_time <= now < end_time:
  88. print("Resuming execution: Within schedule.")
  89. self.pause_requested = False
  90. with self.pause_condition:
  91. self.pause_condition.notify_all()
  92. break
  93. else:
  94. time.sleep(30)
  95. def run_theta_rho_file(self, file_path, schedule_hours=None):
  96. """Run a theta-rho file by sending data in optimized batches with tqdm ETA tracking."""
  97. coordinates = self.parse_theta_rho_file(file_path)
  98. total_coordinates = len(coordinates)
  99. if total_coordinates < 2:
  100. print("Not enough coordinates for interpolation.")
  101. self.current_playing_file = None
  102. self.execution_progress = None
  103. return
  104. self.execution_progress = (0, total_coordinates, None)
  105. batch_size = 10
  106. self.stop_actions()
  107. with serial_manager.serial_lock:
  108. self.current_playing_file = file_path
  109. self.execution_progress = (0, 0, None)
  110. self.stop_requested = False
  111. with tqdm(total=total_coordinates, unit="coords", desc=f"Executing Pattern {file_path}", dynamic_ncols=True, disable=None) as pbar:
  112. for i in range(0, total_coordinates, batch_size):
  113. if self.stop_requested:
  114. print("Execution stopped by user after completing the current batch.")
  115. break
  116. with self.pause_condition:
  117. while self.pause_requested:
  118. print("Execution paused...")
  119. self.pause_condition.wait()
  120. batch = coordinates[i:i + batch_size]
  121. if i == 0:
  122. serial_manager.send_coordinate_batch(batch)
  123. self.execution_progress = (i + batch_size, total_coordinates, None)
  124. pbar.update(batch_size)
  125. continue
  126. while True:
  127. self.schedule_checker(schedule_hours)
  128. if serial_manager.ser.in_waiting > 0:
  129. response = serial_manager.ser.readline().decode().strip()
  130. if response == "R":
  131. serial_manager.send_coordinate_batch(batch)
  132. pbar.update(batch_size)
  133. estimated_remaining_time = pbar.format_dict['elapsed'] / (i + batch_size) * (total_coordinates - (i + batch_size))
  134. self.execution_progress = (i + batch_size, total_coordinates, estimated_remaining_time)
  135. break
  136. elif response != "IGNORED: FINISHED" and response.startswith("IGNORE"):
  137. print("Received IGNORE. Resending the previous batch...")
  138. print(response)
  139. prev_start = max(0, i - batch_size)
  140. prev_end = i
  141. previous_batch = coordinates[prev_start:prev_end]
  142. serial_manager.send_coordinate_batch(previous_batch)
  143. break
  144. else:
  145. print(f"Arduino response: {response}")
  146. self.reset_theta()
  147. serial_manager.ser.write("FINISHED\n".encode())
  148. self.current_playing_file = None
  149. self.execution_progress = None
  150. print("Pattern execution completed.")
  151. def run_theta_rho_files(self, file_paths, pause_time=0, clear_pattern=None, run_mode="single", shuffle=False, schedule_hours=None):
  152. """Run multiple .thr files in sequence with options."""
  153. self.stop_requested = False
  154. if shuffle:
  155. random.shuffle(file_paths)
  156. print("Playlist shuffled.")
  157. self.current_playlist = file_paths
  158. while True:
  159. for idx, path in enumerate(file_paths):
  160. print("Upcoming pattern: " + path)
  161. self.current_playing_index = idx
  162. self.schedule_checker(schedule_hours)
  163. if self.stop_requested:
  164. print("Execution stopped before starting next pattern.")
  165. return
  166. if clear_pattern:
  167. if self.stop_requested:
  168. print("Execution stopped before running the next clear pattern.")
  169. return
  170. clear_file_path = self.get_clear_pattern_file(clear_pattern, path)
  171. print(f"Running clear pattern: {clear_file_path}")
  172. self.run_theta_rho_file(clear_file_path, schedule_hours)
  173. if not self.stop_requested:
  174. print(f"Running pattern {idx + 1} of {len(file_paths)}: {path}")
  175. self.run_theta_rho_file(path, schedule_hours)
  176. if idx < len(file_paths) - 1:
  177. if self.stop_requested:
  178. print("Execution stopped before running the next clear pattern.")
  179. return
  180. if pause_time > 0:
  181. print(f"Pausing for {pause_time} seconds...")
  182. time.sleep(pause_time)
  183. if run_mode == "indefinite":
  184. print("Playlist completed. Restarting as per 'indefinite' run mode.")
  185. if pause_time > 0:
  186. print(f"Pausing for {pause_time} seconds before restarting...")
  187. time.sleep(pause_time)
  188. if shuffle:
  189. random.shuffle(file_paths)
  190. print("Playlist reshuffled for the next loop.")
  191. continue
  192. else:
  193. print("Playlist completed.")
  194. break
  195. self.reset_theta()
  196. with serial_manager.serial_lock:
  197. serial_manager.ser.write("FINISHED\n".encode())
  198. print("All requested patterns completed (or stopped).")
  199. def reset_theta(self):
  200. """Reset theta on the Arduino."""
  201. with serial_manager.serial_lock:
  202. serial_manager.ser.write("RESET_THETA\n".encode())
  203. while True:
  204. with serial_manager.serial_lock:
  205. if serial_manager.ser.in_waiting > 0:
  206. response = serial_manager.ser.readline().decode().strip()
  207. print(f"Arduino response: {response}")
  208. if response == "THETA_RESET":
  209. print("Theta successfully reset.")
  210. break
  211. time.sleep(0.5)
  212. def stop_actions(self):
  213. """Stop all current pattern execution."""
  214. with self.pause_condition:
  215. self.pause_requested = False
  216. self.pause_condition.notify_all()
  217. self.stop_requested = True
  218. self.current_playing_index = None
  219. self.current_playlist = None
  220. self.is_clearing = False
  221. self.current_playing_file = None
  222. self.execution_progress = None
  223. def get_status(self):
  224. """Get the current status of pattern execution."""
  225. if self.current_playing_file in self.CLEAR_PATTERNS.values():
  226. self.is_clearing = True
  227. else:
  228. self.is_clearing = False
  229. return {
  230. "ser_port": serial_manager.get_port(),
  231. "stop_requested": self.stop_requested,
  232. "pause_requested": self.pause_requested,
  233. "current_playing_file": self.current_playing_file,
  234. "execution_progress": self.execution_progress,
  235. "current_playing_index": self.current_playing_index,
  236. "current_playlist": self.current_playlist,
  237. "is_clearing": self.is_clearing
  238. }
  239. # Create a global instance
  240. pattern_manager = PatternManager()