pattern_manager.py 11 KB

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