1
0

pattern_manager.py 49 KB

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