pattern_manager.py 10 KB

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