pattern_manager.py 11 KB

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