main.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. from fastapi import FastAPI, UploadFile, File, HTTPException, BackgroundTasks, WebSocket, WebSocketDisconnect, Request
  2. from fastapi.responses import JSONResponse, FileResponse
  3. from fastapi.staticfiles import StaticFiles
  4. from fastapi.middleware.cors import CORSMiddleware
  5. from fastapi.templating import Jinja2Templates
  6. from pydantic import BaseModel
  7. from typing import List, Optional
  8. import os
  9. import logging
  10. from datetime import datetime
  11. from modules.connection import connection_manager
  12. from modules.core import pattern_manager
  13. from modules.core.pattern_manager import parse_theta_rho_file, THETA_RHO_DIR
  14. from modules.core import playlist_manager
  15. from modules.update import update_manager
  16. from modules.core.state import state
  17. from modules import mqtt
  18. import signal
  19. import asyncio
  20. from contextlib import asynccontextmanager
  21. from modules.led.led_interface import LEDInterface
  22. from modules.screen.screen_controller import ScreenController
  23. from modules.led.idle_timeout_manager import idle_timeout_manager
  24. from modules.core.cache_manager import get_cache_path, generate_image_preview, get_pattern_metadata
  25. from modules.core.version_manager import version_manager
  26. from modules.core.log_handler import init_memory_handler, get_memory_handler
  27. from modules.wifi.router import router as wifi_router, captive_portal_router
  28. import json
  29. import base64
  30. import hashlib
  31. import time
  32. import subprocess
  33. # Get log level from environment variable, default to INFO
  34. log_level_str = os.getenv('LOG_LEVEL', 'INFO').upper()
  35. log_level = getattr(logging, log_level_str, logging.INFO)
  36. logging.basicConfig(
  37. level=log_level,
  38. format='%(asctime)s - %(name)s:%(lineno)d - %(levelname)s - %(message)s',
  39. handlers=[
  40. logging.StreamHandler(),
  41. ]
  42. )
  43. # Initialize memory log handler for web UI log viewer
  44. # Increased to 5000 entries to support lazy loading in the UI
  45. init_memory_handler(max_entries=5000)
  46. logger = logging.getLogger(__name__)
  47. async def _check_table_is_idle() -> bool:
  48. """Helper function to check if table is idle."""
  49. return not state.current_playing_file or state.pause_requested
  50. def _start_idle_led_timeout():
  51. """Start idle LED timeout if enabled."""
  52. if not state.dw_led_idle_timeout_enabled or state.dw_led_idle_timeout_minutes <= 0:
  53. return
  54. logger.debug(f"Starting idle LED timeout: {state.dw_led_idle_timeout_minutes} minutes")
  55. idle_timeout_manager.start_idle_timeout(
  56. timeout_minutes=state.dw_led_idle_timeout_minutes,
  57. state=state,
  58. check_idle_callback=_check_table_is_idle
  59. )
  60. def check_homing_in_progress():
  61. """Check if homing is in progress and raise exception if so."""
  62. if state.is_homing:
  63. raise HTTPException(status_code=409, detail="Cannot perform this action while homing is in progress")
  64. def normalize_file_path(file_path: str) -> str:
  65. """Normalize file path separators for consistent cross-platform handling."""
  66. if not file_path:
  67. return ''
  68. # First normalize path separators
  69. normalized = file_path.replace('\\', '/')
  70. # Remove only the patterns directory prefix from the beginning, not patterns within the path
  71. if normalized.startswith('./patterns/'):
  72. normalized = normalized[11:]
  73. elif normalized.startswith('patterns/'):
  74. normalized = normalized[9:]
  75. return normalized
  76. @asynccontextmanager
  77. async def lifespan(app: FastAPI):
  78. # Startup
  79. logger.info("Starting Dune Weaver application...")
  80. # Register signal handlers
  81. signal.signal(signal.SIGINT, signal_handler)
  82. signal.signal(signal.SIGTERM, signal_handler)
  83. # Connect device in background so the web server starts immediately
  84. async def connect_and_home():
  85. """Connect to device and perform homing in background."""
  86. try:
  87. # Connect without homing first (fast)
  88. await asyncio.to_thread(connection_manager.connect_device, False)
  89. # If connected, perform homing in background (unless disabled)
  90. if state.conn and state.conn.is_connected():
  91. if not state.home_on_connect:
  92. logger.info("Device connected. Home-on-connect is disabled — skipping automatic homing.")
  93. else:
  94. logger.info("Device connected, starting homing in background...")
  95. state.is_homing = True
  96. try:
  97. success = await asyncio.to_thread(connection_manager.home)
  98. if not success:
  99. logger.warning("Background homing failed or was skipped")
  100. # If sensor homing failed, close connection and wait for user action
  101. if state.sensor_homing_failed:
  102. logger.error("Sensor homing failed - closing connection. User must check sensor or switch to crash homing.")
  103. if state.conn:
  104. await asyncio.to_thread(state.conn.close)
  105. state.conn = None
  106. return # Don't proceed with auto-play
  107. finally:
  108. state.is_homing = False
  109. logger.info("Background homing completed")
  110. # After homing (or skip), check for auto_play mode
  111. if state.auto_play_enabled and state.auto_play_playlist:
  112. logger.info(f"Homing complete, checking auto_play playlist: {state.auto_play_playlist}")
  113. try:
  114. playlist_exists = playlist_manager.get_playlist(state.auto_play_playlist) is not None
  115. if not playlist_exists:
  116. logger.warning(f"Auto-play playlist '{state.auto_play_playlist}' not found. Clearing invalid reference.")
  117. state.auto_play_playlist = None
  118. state.save()
  119. elif state.conn and state.conn.is_connected():
  120. logger.info(f"Starting auto-play playlist: {state.auto_play_playlist}")
  121. asyncio.create_task(playlist_manager.run_playlist(
  122. state.auto_play_playlist,
  123. pause_time=state.auto_play_pause_time,
  124. clear_pattern=state.auto_play_clear_pattern,
  125. run_mode=state.auto_play_run_mode,
  126. shuffle=state.auto_play_shuffle
  127. ))
  128. except Exception as e:
  129. logger.error(f"Failed to auto-play playlist: {str(e)}")
  130. except Exception as e:
  131. logger.warning(f"Failed to auto-connect to serial port: {str(e)}")
  132. # Start connection/homing in background - doesn't block server startup
  133. asyncio.create_task(connect_and_home())
  134. # Initialize LED controller based on saved configuration
  135. try:
  136. # Auto-detect provider for backward compatibility with existing installations
  137. if not state.led_provider or state.led_provider == "none":
  138. if state.wled_ip:
  139. state.led_provider = "wled"
  140. logger.info("Auto-detected WLED provider from existing configuration")
  141. # Initialize the appropriate controller
  142. if state.led_provider == "wled" and state.wled_ip:
  143. state.led_controller = LEDInterface("wled", state.wled_ip)
  144. logger.info(f"LED controller initialized: WLED at {state.wled_ip}")
  145. elif state.led_provider == "dw_leds":
  146. state.led_controller = LEDInterface(
  147. "dw_leds",
  148. num_leds=state.dw_led_num_leds,
  149. gpio_pin=state.dw_led_gpio_pin,
  150. pixel_order=state.dw_led_pixel_order,
  151. brightness=state.dw_led_brightness / 100.0,
  152. speed=state.dw_led_speed,
  153. intensity=state.dw_led_intensity
  154. )
  155. logger.info(f"LED controller initialized: DW LEDs ({state.dw_led_num_leds} LEDs on GPIO{state.dw_led_gpio_pin}, pixel order: {state.dw_led_pixel_order})")
  156. # Initialize hardware and start idle effect (matches behavior of /set_led_config)
  157. status = state.led_controller.check_status()
  158. if status.get("connected", False):
  159. if state.led_automation_enabled:
  160. state.led_controller.effect_idle(state.dw_led_idle_effect)
  161. _start_idle_led_timeout()
  162. logger.info("DW LEDs hardware initialized and idle effect started")
  163. else:
  164. logger.info("DW LEDs hardware initialized (manual mode, no auto-effect)")
  165. else:
  166. error_msg = status.get("error", "Unknown error")
  167. logger.warning(f"DW LED hardware initialization failed: {error_msg}")
  168. else:
  169. state.led_controller = None
  170. logger.info("LED controller not configured")
  171. # Save if provider was auto-detected
  172. if state.led_provider and state.wled_ip:
  173. state.save()
  174. except Exception as e:
  175. logger.warning(f"Failed to initialize LED controller: {str(e)}")
  176. state.led_controller = None
  177. # Initialize screen controller for LCD backlight control
  178. try:
  179. state.screen_controller = ScreenController()
  180. if state.screen_controller.available:
  181. logger.info("Screen controller initialized (backlight control available)")
  182. else:
  183. logger.info("Screen controller initialized (no backlight device found)")
  184. except Exception as e:
  185. logger.warning(f"Failed to initialize screen controller: {e}")
  186. state.screen_controller = None
  187. # Note: auto_play is now handled in connect_and_home() after homing completes
  188. try:
  189. mqtt.init_mqtt()
  190. except Exception as e:
  191. logger.warning(f"Failed to initialize MQTT: {str(e)}")
  192. # Schedule cache generation check for later (non-blocking startup)
  193. async def delayed_cache_check():
  194. """Check and generate cache in background."""
  195. try:
  196. logger.info("Starting cache check...")
  197. from modules.core.cache_manager import is_cache_generation_needed_async, generate_cache_background
  198. if await is_cache_generation_needed_async():
  199. logger.info("Cache generation needed, starting background task...")
  200. asyncio.create_task(generate_cache_background()) # Don't await - run in background
  201. else:
  202. logger.info("Cache is up to date, skipping generation")
  203. except Exception as e:
  204. logger.warning(f"Failed during cache generation: {str(e)}")
  205. # Start cache check in background immediately
  206. asyncio.create_task(delayed_cache_check())
  207. yield
  208. # Shutdown
  209. logger.info("Shutting down Dune Weaver application...")
  210. # NOTE: This is a partial content marker — the tool call had to elide the full body.