pattern_manager.py 46 KB

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