pattern_manager.py 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  1. import os
  2. from zoneinfo import ZoneInfo
  3. import threading
  4. import time
  5. import random
  6. import logging
  7. from datetime import datetime, time as datetime_time
  8. from tqdm import tqdm
  9. from modules.connection import connection_manager
  10. from modules.core.state import state
  11. from math import pi
  12. import asyncio
  13. import json
  14. # Import for legacy support, but we'll use LED interface through state
  15. from modules.led.led_controller import effect_playing, effect_idle
  16. from modules.led.idle_timeout_manager import idle_timeout_manager
  17. import queue
  18. from dataclasses import dataclass
  19. from typing import Optional, Callable
  20. # Configure logging
  21. logger = logging.getLogger(__name__)
  22. # Global state
  23. THETA_RHO_DIR = './patterns'
  24. os.makedirs(THETA_RHO_DIR, exist_ok=True)
  25. # Create an asyncio Event for pause/resume
  26. pause_event = asyncio.Event()
  27. pause_event.set() # Initially not paused
  28. # Create an asyncio Lock for pattern execution
  29. pattern_lock = asyncio.Lock()
  30. # Progress update task
  31. progress_update_task = None
  32. # Cache timezone at module level - read once per session
  33. _cached_timezone = None
  34. _cached_zoneinfo = None
  35. def _get_system_timezone():
  36. """Get and cache the system timezone. Called once per session."""
  37. global _cached_timezone, _cached_zoneinfo
  38. if _cached_timezone is not None:
  39. return _cached_zoneinfo
  40. user_tz = 'UTC' # Default fallback
  41. # Try to read timezone from /etc/host-timezone (mounted from host)
  42. try:
  43. if os.path.exists('/etc/host-timezone'):
  44. with open('/etc/host-timezone', 'r') as f:
  45. user_tz = f.read().strip()
  46. logger.info(f"Still Sands using timezone: {user_tz} (from host system)")
  47. # Fallback to /etc/timezone if host-timezone doesn't exist
  48. elif os.path.exists('/etc/timezone'):
  49. with open('/etc/timezone', 'r') as f:
  50. user_tz = f.read().strip()
  51. logger.info(f"Still Sands using timezone: {user_tz} (from container)")
  52. # Fallback to TZ environment variable
  53. elif os.environ.get('TZ'):
  54. user_tz = os.environ.get('TZ')
  55. logger.info(f"Still Sands using timezone: {user_tz} (from environment)")
  56. else:
  57. logger.info("Still Sands using timezone: UTC (default)")
  58. except Exception as e:
  59. logger.debug(f"Could not read timezone: {e}")
  60. # Cache the timezone
  61. _cached_timezone = user_tz
  62. try:
  63. _cached_zoneinfo = ZoneInfo(user_tz)
  64. except Exception as e:
  65. logger.warning(f"Invalid timezone '{user_tz}', falling back to system time: {e}")
  66. _cached_zoneinfo = None
  67. return _cached_zoneinfo
  68. def is_in_scheduled_pause_period():
  69. """Check if current time falls within any scheduled pause period."""
  70. if not state.scheduled_pause_enabled or not state.scheduled_pause_time_slots:
  71. return False
  72. # Get cached timezone
  73. tz_info = _get_system_timezone()
  74. try:
  75. # Get current time in user's timezone
  76. if tz_info:
  77. now = datetime.now(tz_info)
  78. else:
  79. now = datetime.now()
  80. except Exception as e:
  81. logger.warning(f"Error getting current time: {e}")
  82. now = datetime.now()
  83. current_time = now.time()
  84. current_weekday = now.strftime("%A").lower() # monday, tuesday, etc.
  85. for slot in state.scheduled_pause_time_slots:
  86. # Parse start and end times
  87. try:
  88. start_time = datetime_time.fromisoformat(slot['start_time'])
  89. end_time = datetime_time.fromisoformat(slot['end_time'])
  90. except (ValueError, KeyError):
  91. logger.warning(f"Invalid time format in scheduled pause slot: {slot}")
  92. continue
  93. # Check if this slot applies to today
  94. slot_applies_today = False
  95. days_setting = slot.get('days', 'daily')
  96. if days_setting == 'daily':
  97. slot_applies_today = True
  98. elif days_setting == 'weekdays':
  99. slot_applies_today = current_weekday in ['monday', 'tuesday', 'wednesday', 'thursday', 'friday']
  100. elif days_setting == 'weekends':
  101. slot_applies_today = current_weekday in ['saturday', 'sunday']
  102. elif days_setting == 'custom':
  103. custom_days = slot.get('custom_days', [])
  104. slot_applies_today = current_weekday in custom_days
  105. if not slot_applies_today:
  106. continue
  107. # Check if current time is within the pause period
  108. if start_time <= end_time:
  109. # Normal case: start and end are on the same day
  110. if start_time <= current_time <= end_time:
  111. return True
  112. else:
  113. # Time spans midnight: start is before midnight, end is after midnight
  114. if current_time >= start_time or current_time <= end_time:
  115. return True
  116. return False
  117. async def check_table_is_idle() -> bool:
  118. """
  119. Check if the table is currently idle (not playing anything).
  120. Returns True if idle, False if playing.
  121. """
  122. return not state.current_playing_file or state.pause_requested
  123. def start_idle_led_timeout():
  124. """
  125. Start the idle LED timeout if enabled.
  126. Should be called whenever the idle effect is activated.
  127. """
  128. if not state.dw_led_idle_timeout_enabled:
  129. logger.debug("Idle LED timeout not enabled")
  130. return
  131. timeout_minutes = state.dw_led_idle_timeout_minutes
  132. if timeout_minutes <= 0:
  133. logger.debug("Idle LED timeout not configured (timeout <= 0)")
  134. return
  135. logger.debug(f"Starting idle LED timeout: {timeout_minutes} minutes")
  136. idle_timeout_manager.start_idle_timeout(
  137. timeout_minutes=timeout_minutes,
  138. state=state,
  139. check_idle_callback=check_table_is_idle
  140. )
  141. # Motion Control Thread Infrastructure
  142. @dataclass
  143. class MotionCommand:
  144. """Represents a motion command for the motion control thread."""
  145. command_type: str # 'move', 'stop', 'pause', 'resume', 'shutdown'
  146. theta: Optional[float] = None
  147. rho: Optional[float] = None
  148. speed: Optional[float] = None
  149. callback: Optional[Callable] = None
  150. future: Optional[asyncio.Future] = None
  151. class MotionControlThread:
  152. """Dedicated thread for hardware motion control operations."""
  153. def __init__(self):
  154. self.command_queue = queue.Queue()
  155. self.thread = None
  156. self.running = False
  157. self.paused = False
  158. def start(self):
  159. """Start the motion control thread."""
  160. if self.thread and self.thread.is_alive():
  161. return
  162. self.running = True
  163. self.thread = threading.Thread(target=self._motion_loop, daemon=True)
  164. self.thread.start()
  165. logger.info("Motion control thread started")
  166. def stop(self):
  167. """Stop the motion control thread."""
  168. if not self.running:
  169. return
  170. self.running = False
  171. # Send shutdown command
  172. self.command_queue.put(MotionCommand('shutdown'))
  173. if self.thread and self.thread.is_alive():
  174. self.thread.join(timeout=5.0)
  175. logger.info("Motion control thread stopped")
  176. def _motion_loop(self):
  177. """Main loop for the motion control thread."""
  178. logger.info("Motion control thread loop started")
  179. while self.running:
  180. try:
  181. # Get command with timeout to allow periodic checks
  182. command = self.command_queue.get(timeout=1.0)
  183. if command.command_type == 'shutdown':
  184. break
  185. elif command.command_type == 'move':
  186. self._execute_move(command)
  187. elif command.command_type == 'pause':
  188. self.paused = True
  189. elif command.command_type == 'resume':
  190. self.paused = False
  191. elif command.command_type == 'stop':
  192. # Clear any pending commands
  193. while not self.command_queue.empty():
  194. try:
  195. self.command_queue.get_nowait()
  196. except queue.Empty:
  197. break
  198. self.command_queue.task_done()
  199. except queue.Empty:
  200. # Timeout - continue loop for shutdown check
  201. continue
  202. except Exception as e:
  203. logger.error(f"Error in motion control thread: {e}")
  204. logger.info("Motion control thread loop ended")
  205. def _execute_move(self, command: MotionCommand):
  206. """Execute a move command in the motion thread."""
  207. try:
  208. # Wait if paused
  209. while self.paused and self.running:
  210. time.sleep(0.1)
  211. if not self.running:
  212. return
  213. # Execute the actual motion using sync version
  214. self._move_polar_sync(command.theta, command.rho, command.speed)
  215. # Signal completion if future provided
  216. if command.future and not command.future.done():
  217. command.future.get_loop().call_soon_threadsafe(
  218. command.future.set_result, None
  219. )
  220. except Exception as e:
  221. logger.error(f"Error executing move command: {e}")
  222. if command.future and not command.future.done():
  223. command.future.get_loop().call_soon_threadsafe(
  224. command.future.set_exception, e
  225. )
  226. def _move_polar_sync(self, theta: float, rho: float, speed: Optional[float] = None):
  227. """Synchronous version of move_polar for use in motion thread."""
  228. # This is the original sync logic but running in dedicated thread
  229. if state.table_type == 'dune_weaver_mini':
  230. x_scaling_factor = 2
  231. y_scaling_factor = 3.7
  232. else:
  233. x_scaling_factor = 2
  234. y_scaling_factor = 5
  235. delta_theta = theta - state.current_theta
  236. delta_rho = rho - state.current_rho
  237. x_increment = delta_theta * 100 / (2 * pi * x_scaling_factor)
  238. y_increment = delta_rho * 100 / y_scaling_factor
  239. x_total_steps = state.x_steps_per_mm * (100/x_scaling_factor)
  240. y_total_steps = state.y_steps_per_mm * (100/y_scaling_factor)
  241. offset = x_increment * (x_total_steps * x_scaling_factor / (state.gear_ratio * y_total_steps * y_scaling_factor))
  242. if state.table_type == 'dune_weaver_mini' or state.y_steps_per_mm == 546:
  243. y_increment -= offset
  244. else:
  245. y_increment += offset
  246. new_x_abs = state.machine_x + x_increment
  247. new_y_abs = state.machine_y + y_increment
  248. # Use provided speed or fall back to state.speed
  249. actual_speed = speed if speed is not None else state.speed
  250. # Call sync version of send_grbl_coordinates in this thread
  251. self._send_grbl_coordinates_sync(round(new_x_abs, 3), round(new_y_abs, 3), actual_speed)
  252. # Update state
  253. state.current_theta = theta
  254. state.current_rho = rho
  255. state.machine_x = new_x_abs
  256. state.machine_y = new_y_abs
  257. def _send_grbl_coordinates_sync(self, x: float, y: float, speed: int = 600, timeout: int = 2, home: bool = False):
  258. """Synchronous version of send_grbl_coordinates for motion thread."""
  259. logger.debug(f"Motion thread sending G-code: X{x} Y{y} at F{speed}")
  260. # Track overall attempt time
  261. overall_start_time = time.time()
  262. while True:
  263. try:
  264. gcode = f"$J=G91 G21 Y{y} F{speed}" if home else f"G1 X{x} Y{y} F{speed}"
  265. state.conn.send(gcode + "\n")
  266. logger.debug(f"Motion thread sent command: {gcode}")
  267. start_time = time.time()
  268. while True:
  269. response = state.conn.readline()
  270. logger.debug(f"Motion thread response: {response}")
  271. if response.lower() == "ok":
  272. logger.debug("Motion thread: Command execution confirmed.")
  273. return
  274. except Exception as e:
  275. error_str = str(e)
  276. logger.warning(f"Motion thread error sending command: {error_str}")
  277. # Immediately return for device not configured errors
  278. if "Device not configured" in error_str or "Errno 6" in error_str:
  279. logger.error(f"Motion thread: Device configuration error detected: {error_str}")
  280. state.stop_requested = True
  281. state.conn = None
  282. state.is_connected = False
  283. logger.info("Connection marked as disconnected due to device error")
  284. return False
  285. logger.warning(f"Motion thread: No 'ok' received for X{x} Y{y}, speed {speed}. Retrying...")
  286. time.sleep(0.1)
  287. # Global motion control thread instance
  288. motion_controller = MotionControlThread()
  289. async def cleanup_pattern_manager():
  290. """Clean up pattern manager resources"""
  291. global progress_update_task, pattern_lock, pause_event
  292. try:
  293. # Stop motion control thread
  294. motion_controller.stop()
  295. # Cancel progress update task if running
  296. if progress_update_task and not progress_update_task.done():
  297. try:
  298. progress_update_task.cancel()
  299. # Wait for task to actually cancel
  300. try:
  301. await progress_update_task
  302. except asyncio.CancelledError:
  303. pass
  304. except Exception as e:
  305. logger.error(f"Error cancelling progress update task: {e}")
  306. # Clean up pattern lock
  307. if pattern_lock:
  308. try:
  309. if pattern_lock.locked():
  310. pattern_lock.release()
  311. pattern_lock = None
  312. except Exception as e:
  313. logger.error(f"Error cleaning up pattern lock: {e}")
  314. # Clean up pause event
  315. if pause_event:
  316. try:
  317. pause_event.set() # Wake up any waiting tasks
  318. pause_event = None
  319. except Exception as e:
  320. logger.error(f"Error cleaning up pause event: {e}")
  321. # Clean up pause condition from state
  322. if state.pause_condition:
  323. try:
  324. with state.pause_condition:
  325. state.pause_condition.notify_all()
  326. state.pause_condition = threading.Condition()
  327. except Exception as e:
  328. logger.error(f"Error cleaning up pause condition: {e}")
  329. # Clear all state variables
  330. state.current_playing_file = None
  331. state.execution_progress = 0
  332. state.is_running = False
  333. state.pause_requested = False
  334. state.stop_requested = True
  335. state.is_clearing = False
  336. # Reset machine position
  337. await connection_manager.update_machine_position()
  338. logger.info("Pattern manager resources cleaned up")
  339. except Exception as e:
  340. logger.error(f"Error during pattern manager cleanup: {e}")
  341. finally:
  342. # Ensure we always reset these
  343. progress_update_task = None
  344. pattern_lock = None
  345. pause_event = None
  346. def list_theta_rho_files():
  347. files = []
  348. for root, dirs, filenames in os.walk(THETA_RHO_DIR):
  349. # Skip cached_images directories to avoid scanning thousands of WebP files
  350. if 'cached_images' in dirs:
  351. dirs.remove('cached_images')
  352. # Filter .thr files during traversal for better performance
  353. thr_files = [f for f in filenames if f.endswith('.thr')]
  354. for file in thr_files:
  355. relative_path = os.path.relpath(os.path.join(root, file), THETA_RHO_DIR)
  356. # Normalize path separators to always use forward slashes for consistency across platforms
  357. relative_path = relative_path.replace(os.sep, '/')
  358. files.append(relative_path)
  359. logger.debug(f"Found {len(files)} theta-rho files")
  360. return files
  361. def parse_theta_rho_file(file_path):
  362. """Parse a theta-rho file and return a list of (theta, rho) pairs."""
  363. coordinates = []
  364. try:
  365. logger.debug(f"Parsing theta-rho file: {file_path}")
  366. with open(file_path, 'r', encoding='utf-8') as file:
  367. for line in file:
  368. line = line.strip()
  369. if not line or line.startswith("#"):
  370. continue
  371. try:
  372. theta, rho = map(float, line.split())
  373. coordinates.append((theta, rho))
  374. except ValueError:
  375. logger.warning(f"Skipping invalid line: {line}")
  376. continue
  377. except Exception as e:
  378. logger.error(f"Error reading file: {e}")
  379. return coordinates
  380. logger.debug(f"Parsed {len(coordinates)} coordinates from {file_path}")
  381. return coordinates
  382. def get_first_rho_from_cache(file_path, cache_data=None):
  383. """Get the first rho value from cached metadata, falling back to file parsing if needed.
  384. Args:
  385. file_path: Path to the pattern file
  386. cache_data: Optional pre-loaded cache data dict to avoid repeated disk I/O
  387. """
  388. try:
  389. # Import cache_manager locally to avoid circular import
  390. from modules.core import cache_manager
  391. # Try to get from metadata cache first
  392. # Use relative path from THETA_RHO_DIR to match cache keys (which include subdirectories)
  393. file_name = os.path.relpath(file_path, THETA_RHO_DIR)
  394. # Use provided cache_data if available, otherwise load from disk
  395. if cache_data is not None:
  396. # Extract metadata directly from provided cache
  397. data_section = cache_data.get('data', {})
  398. if file_name in data_section:
  399. cached_entry = data_section[file_name]
  400. metadata = cached_entry.get('metadata')
  401. # When cache_data is provided, trust it without checking mtime
  402. # This significantly speeds up bulk operations (playlists with 1000+ patterns)
  403. # by avoiding 1000+ os.path.getmtime() calls on slow storage (e.g., Pi SD cards)
  404. if metadata and 'first_coordinate' in metadata:
  405. return metadata['first_coordinate']['y']
  406. else:
  407. # Fall back to loading cache from disk (original behavior)
  408. metadata = cache_manager.get_pattern_metadata(file_name)
  409. if metadata and 'first_coordinate' in metadata:
  410. # In the cache, 'x' is theta and 'y' is rho
  411. return metadata['first_coordinate']['y']
  412. # Fallback to parsing the file if not in cache
  413. logger.debug(f"Metadata not cached for {file_name}, parsing file")
  414. coordinates = parse_theta_rho_file(file_path)
  415. if coordinates:
  416. return coordinates[0][1] # Return rho value
  417. return None
  418. except Exception as e:
  419. logger.warning(f"Error getting first rho from cache for {file_path}: {str(e)}")
  420. return None
  421. def get_clear_pattern_file(clear_pattern_mode, path=None, cache_data=None):
  422. """Return a .thr file path based on pattern_name and table type.
  423. Args:
  424. clear_pattern_mode: The clear pattern mode to use
  425. path: Optional path to the pattern file for adaptive mode
  426. cache_data: Optional pre-loaded cache data dict to avoid repeated disk I/O
  427. """
  428. if not clear_pattern_mode or clear_pattern_mode == 'none':
  429. return
  430. # Define patterns for each table type
  431. clear_patterns = {
  432. 'dune_weaver': {
  433. 'clear_from_out': './patterns/clear_from_out.thr',
  434. 'clear_from_in': './patterns/clear_from_in.thr',
  435. 'clear_sideway': './patterns/clear_sideway.thr'
  436. },
  437. 'dune_weaver_mini': {
  438. 'clear_from_out': './patterns/clear_from_out_mini.thr',
  439. 'clear_from_in': './patterns/clear_from_in_mini.thr',
  440. 'clear_sideway': './patterns/clear_sideway_mini.thr'
  441. },
  442. 'dune_weaver_pro': {
  443. 'clear_from_out': './patterns/clear_from_out_pro.thr',
  444. 'clear_from_out_Ultra': './patterns/clear_from_out_Ultra.thr',
  445. 'clear_from_in': './patterns/clear_from_in_pro.thr',
  446. 'clear_from_in_Ultra': './patterns/clear_from_in_Ultra.thr',
  447. 'clear_sideway': './patterns/clear_sideway_pro.thr'
  448. }
  449. }
  450. # Get patterns for current table type, fallback to standard patterns if type not found
  451. table_patterns = clear_patterns.get(state.table_type, clear_patterns['dune_weaver'])
  452. # Check for custom patterns first
  453. if state.custom_clear_from_out and clear_pattern_mode in ['clear_from_out', 'adaptive']:
  454. if clear_pattern_mode == 'adaptive':
  455. # For adaptive mode, use cached metadata to check first rho
  456. if path:
  457. first_rho = get_first_rho_from_cache(path, cache_data)
  458. if first_rho is not None and first_rho < 0.5:
  459. # Use custom clear_from_out if set
  460. custom_path = os.path.join('./patterns', state.custom_clear_from_out)
  461. if os.path.exists(custom_path):
  462. logger.debug(f"Using custom clear_from_out: {custom_path}")
  463. return custom_path
  464. elif clear_pattern_mode == 'clear_from_out':
  465. custom_path = os.path.join('./patterns', state.custom_clear_from_out)
  466. if os.path.exists(custom_path):
  467. logger.debug(f"Using custom clear_from_out: {custom_path}")
  468. return custom_path
  469. if state.custom_clear_from_in and clear_pattern_mode in ['clear_from_in', 'adaptive']:
  470. if clear_pattern_mode == 'adaptive':
  471. # For adaptive mode, use cached metadata to check first rho
  472. if path:
  473. first_rho = get_first_rho_from_cache(path, cache_data)
  474. if first_rho is not None and first_rho >= 0.5:
  475. # Use custom clear_from_in if set
  476. custom_path = os.path.join('./patterns', state.custom_clear_from_in)
  477. if os.path.exists(custom_path):
  478. logger.debug(f"Using custom clear_from_in: {custom_path}")
  479. return custom_path
  480. elif clear_pattern_mode == 'clear_from_in':
  481. custom_path = os.path.join('./patterns', state.custom_clear_from_in)
  482. if os.path.exists(custom_path):
  483. logger.debug(f"Using custom clear_from_in: {custom_path}")
  484. return custom_path
  485. logger.debug(f"Clear pattern mode: {clear_pattern_mode} for table type: {state.table_type}")
  486. if clear_pattern_mode == "random":
  487. return random.choice(list(table_patterns.values()))
  488. if clear_pattern_mode == 'adaptive':
  489. if not path:
  490. logger.warning("No path provided for adaptive clear pattern")
  491. return random.choice(list(table_patterns.values()))
  492. # Use cached metadata to get first rho value
  493. first_rho = get_first_rho_from_cache(path, cache_data)
  494. if first_rho is None:
  495. logger.warning("Could not determine first rho value for adaptive clear pattern")
  496. return random.choice(list(table_patterns.values()))
  497. if first_rho < 0.5:
  498. return table_patterns['clear_from_out']
  499. else:
  500. return table_patterns['clear_from_in']
  501. else:
  502. if clear_pattern_mode not in table_patterns:
  503. return False
  504. return table_patterns[clear_pattern_mode]
  505. def is_clear_pattern(file_path):
  506. """Check if a file path is a clear pattern file."""
  507. # Get all possible clear pattern files for all table types
  508. clear_patterns = []
  509. for table_type in ['dune_weaver', 'dune_weaver_mini', 'dune_weaver_pro']:
  510. clear_patterns.extend([
  511. f'./patterns/clear_from_out{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr',
  512. f'./patterns/clear_from_in{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr',
  513. f'./patterns/clear_sideway{("_" + table_type.split("_")[-1]) if table_type != "dune_weaver" else ""}.thr'
  514. ])
  515. # Normalize paths for comparison
  516. normalized_path = os.path.normpath(file_path)
  517. normalized_clear_patterns = [os.path.normpath(p) for p in clear_patterns]
  518. # Check if the file path matches any clear pattern path
  519. return normalized_path in normalized_clear_patterns
  520. async def run_theta_rho_file(file_path, is_playlist=False):
  521. """Run a theta-rho file by sending data in optimized batches with tqdm ETA tracking."""
  522. if pattern_lock.locked():
  523. logger.warning("Another pattern is already running. Cannot start a new one.")
  524. return
  525. async with pattern_lock: # This ensures only one pattern can run at a time
  526. # Start progress update task only if not part of a playlist
  527. global progress_update_task
  528. if not is_playlist and not progress_update_task:
  529. progress_update_task = asyncio.create_task(broadcast_progress())
  530. coordinates = parse_theta_rho_file(file_path)
  531. total_coordinates = len(coordinates)
  532. if total_coordinates < 2:
  533. logger.warning("Not enough coordinates for interpolation")
  534. if not is_playlist:
  535. state.current_playing_file = None
  536. state.execution_progress = None
  537. return
  538. # Determine if this is a clearing pattern
  539. is_clear_file = is_clear_pattern(file_path)
  540. if is_clear_file:
  541. initial_speed = state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  542. logger.info(f"Running clearing pattern at initial speed {initial_speed}")
  543. else:
  544. logger.info(f"Running normal pattern at initial speed {state.speed}")
  545. state.execution_progress = (0, total_coordinates, None, 0)
  546. # stop actions without resetting the playlist, and don't wait for lock (we already have it)
  547. await stop_actions(clear_playlist=False, wait_for_lock=False)
  548. state.current_playing_file = file_path
  549. state.stop_requested = False
  550. # Reset LED idle timeout activity time when pattern starts
  551. import time as time_module
  552. state.dw_led_last_activity_time = time_module.time()
  553. logger.info(f"Starting pattern execution: {file_path}")
  554. logger.info(f"t: {state.current_theta}, r: {state.current_rho}")
  555. await reset_theta()
  556. start_time = time.time()
  557. if state.led_controller:
  558. logger.info(f"Setting LED to playing effect: {state.dw_led_playing_effect}")
  559. state.led_controller.effect_playing(state.dw_led_playing_effect)
  560. # Cancel idle timeout when playing starts
  561. idle_timeout_manager.cancel_timeout()
  562. with tqdm(
  563. total=total_coordinates,
  564. unit="coords",
  565. desc=f"Executing Pattern {file_path}",
  566. dynamic_ncols=True,
  567. disable=False,
  568. mininterval=1.0
  569. ) as pbar:
  570. for i, coordinate in enumerate(coordinates):
  571. theta, rho = coordinate
  572. if state.stop_requested:
  573. logger.info("Execution stopped by user")
  574. if state.led_controller:
  575. state.led_controller.effect_idle(state.dw_led_idle_effect)
  576. start_idle_led_timeout()
  577. break
  578. if state.skip_requested:
  579. logger.info("Skipping pattern...")
  580. await connection_manager.check_idle_async()
  581. if state.led_controller:
  582. state.led_controller.effect_idle(state.dw_led_idle_effect)
  583. start_idle_led_timeout()
  584. break
  585. # Wait for resume if paused (manual or scheduled)
  586. manual_pause = state.pause_requested
  587. scheduled_pause = is_in_scheduled_pause_period()
  588. if manual_pause or scheduled_pause:
  589. if manual_pause and scheduled_pause:
  590. logger.info("Execution paused (manual + scheduled pause active)...")
  591. elif manual_pause:
  592. logger.info("Execution paused (manual)...")
  593. else:
  594. logger.info("Execution paused (scheduled pause period)...")
  595. # Turn off LED controller if scheduled pause and control_wled is enabled
  596. if state.scheduled_pause_control_wled and state.led_controller:
  597. logger.info("Turning off LED lights during Still Sands period")
  598. state.led_controller.set_power(0)
  599. # Only show idle effect if NOT in scheduled pause with LED control
  600. # (manual pause always shows idle effect)
  601. if state.led_controller and not (scheduled_pause and state.scheduled_pause_control_wled):
  602. state.led_controller.effect_idle(state.dw_led_idle_effect)
  603. start_idle_led_timeout()
  604. # Remember if we turned off LED controller for scheduled pause
  605. wled_was_off_for_scheduled = scheduled_pause and state.scheduled_pause_control_wled and not manual_pause
  606. # Wait until both manual pause is released AND we're outside scheduled pause period
  607. while state.pause_requested or is_in_scheduled_pause_period():
  608. await asyncio.sleep(1) # Check every second
  609. # Also wait for the pause event in case of manual pause
  610. if state.pause_requested:
  611. await pause_event.wait()
  612. logger.info("Execution resumed...")
  613. if state.led_controller:
  614. # Turn LED controller back on if it was turned off for scheduled pause
  615. if wled_was_off_for_scheduled:
  616. logger.info("Turning LED lights back on as Still Sands period ended")
  617. state.led_controller.set_power(1)
  618. # CRITICAL: Give LED controller time to fully power on before sending more commands
  619. # Without this delay, rapid-fire requests can crash controllers on resource-constrained Pis
  620. await asyncio.sleep(0.5)
  621. state.led_controller.effect_playing(state.dw_led_playing_effect)
  622. # Cancel idle timeout when resuming from pause
  623. idle_timeout_manager.cancel_timeout()
  624. # Dynamically determine the speed for each movement
  625. # Use clear_pattern_speed if it's set and this is a clear file, otherwise use state.speed
  626. if is_clear_file and state.clear_pattern_speed is not None:
  627. current_speed = state.clear_pattern_speed
  628. else:
  629. current_speed = state.speed
  630. await move_polar(theta, rho, current_speed)
  631. # Update progress for all coordinates including the first one
  632. pbar.update(1)
  633. elapsed_time = time.time() - start_time
  634. estimated_remaining_time = (total_coordinates - (i + 1)) / pbar.format_dict['rate'] if pbar.format_dict['rate'] and total_coordinates else 0
  635. state.execution_progress = (i + 1, total_coordinates, estimated_remaining_time, elapsed_time)
  636. # Add a small delay to allow other async operations
  637. await asyncio.sleep(0.001)
  638. # Update progress one last time to show 100%
  639. elapsed_time = time.time() - start_time
  640. state.execution_progress = (total_coordinates, total_coordinates, 0, elapsed_time)
  641. # Give WebSocket a chance to send the final update
  642. await asyncio.sleep(0.1)
  643. if not state.conn:
  644. logger.error("Device is not connected. Stopping pattern execution.")
  645. return
  646. await connection_manager.check_idle_async()
  647. # Set LED back to idle when pattern completes normally (not stopped early)
  648. if state.led_controller and not state.stop_requested:
  649. logger.info(f"Setting LED to idle effect: {state.dw_led_idle_effect}")
  650. state.led_controller.effect_idle(state.dw_led_idle_effect)
  651. start_idle_led_timeout()
  652. logger.debug("LED effect set to idle after pattern completion")
  653. # Only clear state if not part of a playlist
  654. if not is_playlist:
  655. state.current_playing_file = None
  656. state.execution_progress = None
  657. logger.info("Pattern execution completed and state cleared")
  658. else:
  659. logger.info("Pattern execution completed, maintaining state for playlist")
  660. # Only cancel progress update task if not part of a playlist
  661. if not is_playlist and progress_update_task:
  662. progress_update_task.cancel()
  663. try:
  664. await progress_update_task
  665. except asyncio.CancelledError:
  666. pass
  667. progress_update_task = None
  668. async def run_theta_rho_files(file_paths, pause_time=0, clear_pattern=None, run_mode="single", shuffle=False):
  669. """Run multiple .thr files in sequence with options."""
  670. state.stop_requested = False
  671. # Reset LED idle timeout activity time when playlist starts
  672. import time as time_module
  673. state.dw_led_last_activity_time = time_module.time()
  674. # Set initial playlist state
  675. state.playlist_mode = run_mode
  676. state.current_playlist_index = 0
  677. # Start progress update task for the playlist
  678. global progress_update_task
  679. if not progress_update_task:
  680. progress_update_task = asyncio.create_task(broadcast_progress())
  681. if shuffle:
  682. random.shuffle(file_paths)
  683. logger.info("Playlist shuffled")
  684. try:
  685. while True:
  686. # Load metadata cache once for all patterns (significant performance improvement)
  687. # This avoids reading the cache file from disk for every pattern
  688. cache_data = None
  689. if clear_pattern and clear_pattern in ['adaptive', 'clear_from_in', 'clear_from_out']:
  690. from modules.core import cache_manager
  691. cache_data = cache_manager.load_metadata_cache()
  692. logger.info(f"Loaded metadata cache for {len(cache_data.get('data', {}))} patterns")
  693. # Construct the complete pattern sequence
  694. pattern_sequence = []
  695. for path in file_paths:
  696. # Add clear pattern if specified
  697. if clear_pattern and clear_pattern != 'none':
  698. clear_file_path = get_clear_pattern_file(clear_pattern, path, cache_data)
  699. if clear_file_path:
  700. pattern_sequence.append(clear_file_path)
  701. # Add main pattern
  702. pattern_sequence.append(path)
  703. # Shuffle if requested
  704. if shuffle:
  705. # Get pairs of patterns (clear + main) to keep them together
  706. pairs = [pattern_sequence[i:i+2] for i in range(0, len(pattern_sequence), 2)]
  707. random.shuffle(pairs)
  708. # Flatten the pairs back into a single list
  709. pattern_sequence = [pattern for pair in pairs for pattern in pair]
  710. logger.info("Playlist shuffled")
  711. # Set the playlist to the first pattern
  712. state.current_playlist = pattern_sequence
  713. # Execute the pattern sequence
  714. for idx, file_path in enumerate(pattern_sequence):
  715. state.current_playlist_index = idx
  716. if state.stop_requested:
  717. logger.info("Execution stopped")
  718. return
  719. # Update state for main patterns only
  720. logger.info(f"Running pattern {file_path}")
  721. # Execute the pattern
  722. await run_theta_rho_file(file_path, is_playlist=True)
  723. # Handle pause between patterns
  724. if idx < len(pattern_sequence) - 1 and not state.stop_requested and pause_time > 0 and not state.skip_requested:
  725. # Check if current pattern is a clear pattern
  726. if is_clear_pattern(file_path):
  727. logger.info("Skipping pause after clear pattern")
  728. else:
  729. logger.info(f"Pausing for {pause_time} seconds")
  730. state.original_pause_time = pause_time
  731. pause_start = time.time()
  732. while time.time() - pause_start < pause_time:
  733. state.pause_time_remaining = pause_start + pause_time - time.time()
  734. if state.skip_requested:
  735. logger.info("Pause interrupted by stop/skip request")
  736. break
  737. await asyncio.sleep(1)
  738. state.pause_time_remaining = 0
  739. state.skip_requested = False
  740. if run_mode == "indefinite":
  741. logger.info("Playlist completed. Restarting as per 'indefinite' run mode")
  742. if pause_time > 0:
  743. logger.debug(f"Pausing for {pause_time} seconds before restarting")
  744. pause_start = time.time()
  745. while time.time() - pause_start < pause_time:
  746. state.pause_time_remaining = pause_start + pause_time - time.time()
  747. if state.skip_requested:
  748. logger.info("Pause interrupted by stop/skip request")
  749. break
  750. await asyncio.sleep(1)
  751. state.pause_time_remaining = 0
  752. continue
  753. else:
  754. logger.info("Playlist completed")
  755. break
  756. finally:
  757. # Clean up progress update task
  758. if progress_update_task:
  759. progress_update_task.cancel()
  760. try:
  761. await progress_update_task
  762. except asyncio.CancelledError:
  763. pass
  764. progress_update_task = None
  765. # Clear all state variables
  766. state.current_playing_file = None
  767. state.execution_progress = None
  768. state.current_playlist = None
  769. state.current_playlist_index = None
  770. state.playlist_mode = None
  771. if state.led_controller:
  772. state.led_controller.effect_idle(state.dw_led_idle_effect)
  773. start_idle_led_timeout()
  774. logger.info("All requested patterns completed (or stopped) and state cleared")
  775. async def stop_actions(clear_playlist = True, wait_for_lock = True):
  776. """Stop all current actions and wait for pattern to fully release.
  777. Args:
  778. clear_playlist: Whether to clear playlist state
  779. wait_for_lock: Whether to wait for pattern_lock to be released. Set to False when
  780. called from within pattern execution to avoid deadlock.
  781. """
  782. try:
  783. with state.pause_condition:
  784. state.pause_requested = False
  785. state.stop_requested = True
  786. state.current_playing_file = None
  787. state.execution_progress = None
  788. state.is_clearing = False
  789. if clear_playlist:
  790. # Clear playlist state
  791. state.current_playlist = None
  792. state.current_playlist_index = None
  793. state.playlist_mode = None
  794. # Cancel progress update task if we're clearing the playlist
  795. global progress_update_task
  796. if progress_update_task and not progress_update_task.done():
  797. progress_update_task.cancel()
  798. state.pause_condition.notify_all()
  799. # Wait for the pattern lock to be released before continuing
  800. # This ensures that when stop_actions completes, the pattern has fully stopped
  801. # Skip this if called from within pattern execution to avoid deadlock
  802. if wait_for_lock and pattern_lock.locked():
  803. logger.info("Waiting for pattern to fully stop...")
  804. # Acquire and immediately release the lock to ensure the pattern has exited
  805. async with pattern_lock:
  806. logger.info("Pattern lock acquired - pattern has fully stopped")
  807. # Call async function directly since we're in async context
  808. await connection_manager.update_machine_position()
  809. except Exception as e:
  810. logger.error(f"Error during stop_actions: {e}")
  811. # Ensure we still update machine position even if there's an error
  812. try:
  813. await connection_manager.update_machine_position()
  814. except Exception as update_err:
  815. logger.error(f"Error updating machine position on error: {update_err}")
  816. async def move_polar(theta, rho, speed=None):
  817. """
  818. Queue a motion command to be executed in the dedicated motion control thread.
  819. This makes motion control non-blocking for API endpoints.
  820. Args:
  821. theta (float): Target theta coordinate
  822. rho (float): Target rho coordinate
  823. speed (int, optional): Speed override. If None, uses state.speed
  824. """
  825. # Ensure motion control thread is running
  826. if not motion_controller.running:
  827. motion_controller.start()
  828. # Create future for async/await pattern
  829. loop = asyncio.get_event_loop()
  830. future = loop.create_future()
  831. # Create and queue motion command
  832. command = MotionCommand(
  833. command_type='move',
  834. theta=theta,
  835. rho=rho,
  836. speed=speed,
  837. future=future
  838. )
  839. motion_controller.command_queue.put(command)
  840. logger.debug(f"Queued motion command: theta={theta}, rho={rho}, speed={speed}")
  841. # Wait for command completion
  842. await future
  843. def pause_execution():
  844. """Pause pattern execution using asyncio Event."""
  845. logger.info("Pausing pattern execution")
  846. state.pause_requested = True
  847. pause_event.clear() # Clear the event to pause execution
  848. return True
  849. def resume_execution():
  850. """Resume pattern execution using asyncio Event."""
  851. logger.info("Resuming pattern execution")
  852. state.pause_requested = False
  853. pause_event.set() # Set the event to resume execution
  854. return True
  855. async def reset_theta():
  856. logger.info('Resetting Theta')
  857. state.current_theta = state.current_theta % (2 * pi)
  858. # Call async function directly since we're in async context
  859. await connection_manager.update_machine_position()
  860. def set_speed(new_speed):
  861. state.speed = new_speed
  862. logger.info(f'Set new state.speed {new_speed}')
  863. def get_status():
  864. """Get the current status of pattern execution."""
  865. status = {
  866. "current_file": state.current_playing_file,
  867. "is_paused": state.pause_requested or is_in_scheduled_pause_period(),
  868. "manual_pause": state.pause_requested,
  869. "scheduled_pause": is_in_scheduled_pause_period(),
  870. "is_running": bool(state.current_playing_file and not state.stop_requested),
  871. "progress": None,
  872. "playlist": None,
  873. "speed": state.speed,
  874. "pause_time_remaining": state.pause_time_remaining,
  875. "original_pause_time": getattr(state, 'original_pause_time', None),
  876. "connection_status": state.conn.is_connected() if state.conn else False,
  877. "current_theta": state.current_theta,
  878. "current_rho": state.current_rho
  879. }
  880. # Add playlist information if available
  881. if state.current_playlist and state.current_playlist_index is not None:
  882. next_index = state.current_playlist_index + 1
  883. status["playlist"] = {
  884. "current_index": state.current_playlist_index,
  885. "total_files": len(state.current_playlist),
  886. "mode": state.playlist_mode,
  887. "next_file": state.current_playlist[next_index] if next_index < len(state.current_playlist) else None
  888. }
  889. if state.execution_progress:
  890. current, total, remaining_time, elapsed_time = state.execution_progress
  891. status["progress"] = {
  892. "current": current,
  893. "total": total,
  894. "remaining_time": remaining_time,
  895. "elapsed_time": elapsed_time,
  896. "percentage": (current / total * 100) if total > 0 else 0
  897. }
  898. return status
  899. async def broadcast_progress():
  900. """Background task to broadcast progress updates."""
  901. from main import broadcast_status_update
  902. while True:
  903. # Send status updates regardless of pattern_lock state
  904. status = get_status()
  905. # Use the existing broadcast function from main.py
  906. await broadcast_status_update(status)
  907. # Check if we should stop broadcasting
  908. if not state.current_playlist:
  909. # If no playlist, only stop if no pattern is being executed
  910. if not pattern_lock.locked():
  911. logger.info("No playlist or pattern running, stopping broadcast")
  912. break
  913. # Wait before next update
  914. await asyncio.sleep(1)