main.py 94 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286
  1. from fastapi import FastAPI, UploadFile, File, HTTPException, BackgroundTasks, WebSocket, WebSocketDisconnect, Request
  2. from fastapi.responses import JSONResponse, FileResponse, Response
  3. from fastapi.staticfiles import StaticFiles
  4. from fastapi.templating import Jinja2Templates
  5. from pydantic import BaseModel
  6. from typing import List, Optional, Tuple, Dict, Any, Union
  7. import atexit
  8. import os
  9. import logging
  10. from datetime import datetime, time
  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 sys
  20. import asyncio
  21. from contextlib import asynccontextmanager
  22. from modules.led.led_controller import LEDController, effect_idle
  23. from modules.led.led_interface import LEDInterface
  24. from modules.led.idle_timeout_manager import idle_timeout_manager
  25. import math
  26. from modules.core.cache_manager import generate_all_image_previews, get_cache_path, generate_image_preview, get_pattern_metadata
  27. from modules.core.version_manager import version_manager
  28. import json
  29. import base64
  30. import time
  31. import argparse
  32. from concurrent.futures import ProcessPoolExecutor
  33. import multiprocessing
  34. import subprocess
  35. import platform
  36. # Get log level from environment variable, default to INFO
  37. log_level_str = os.getenv('LOG_LEVEL', 'INFO').upper()
  38. log_level = getattr(logging, log_level_str, logging.INFO)
  39. # Create a process pool for CPU-intensive tasks
  40. # Limit to reasonable number of workers for embedded systems
  41. cpu_count = multiprocessing.cpu_count()
  42. # Maximum 3 workers (leaving 1 for motion), minimum 1
  43. process_pool_size = min(3, max(1, cpu_count - 1))
  44. process_pool = None # Will be initialized in lifespan
  45. logging.basicConfig(
  46. level=log_level,
  47. format='%(asctime)s - %(name)s:%(lineno)d - %(levelname)s - %(message)s',
  48. handlers=[
  49. logging.StreamHandler(),
  50. ]
  51. )
  52. logger = logging.getLogger(__name__)
  53. async def _check_table_is_idle() -> bool:
  54. """Helper function to check if table is idle."""
  55. return not state.current_playing_file or state.pause_requested
  56. def _start_idle_led_timeout():
  57. """Start idle LED timeout if enabled."""
  58. if not state.dw_led_idle_timeout_enabled or state.dw_led_idle_timeout_minutes <= 0:
  59. return
  60. logger.debug(f"Starting idle LED timeout: {state.dw_led_idle_timeout_minutes} minutes")
  61. idle_timeout_manager.start_idle_timeout(
  62. timeout_minutes=state.dw_led_idle_timeout_minutes,
  63. state=state,
  64. check_idle_callback=_check_table_is_idle
  65. )
  66. def normalize_file_path(file_path: str) -> str:
  67. """Normalize file path separators for consistent cross-platform handling."""
  68. if not file_path:
  69. return ''
  70. # First normalize path separators
  71. normalized = file_path.replace('\\', '/')
  72. # Remove only the patterns directory prefix from the beginning, not patterns within the path
  73. if normalized.startswith('./patterns/'):
  74. normalized = normalized[11:]
  75. elif normalized.startswith('patterns/'):
  76. normalized = normalized[9:]
  77. return normalized
  78. @asynccontextmanager
  79. async def lifespan(app: FastAPI):
  80. # Startup
  81. logger.info("Starting Dune Weaver application...")
  82. # Register signal handlers
  83. signal.signal(signal.SIGINT, signal_handler)
  84. signal.signal(signal.SIGTERM, signal_handler)
  85. # Initialize process pool for CPU-intensive tasks
  86. global process_pool
  87. process_pool = ProcessPoolExecutor(max_workers=process_pool_size)
  88. logger.info(f"Initialized process pool with {process_pool_size} workers (detected {cpu_count} cores total)")
  89. try:
  90. connection_manager.connect_device()
  91. except Exception as e:
  92. logger.warning(f"Failed to auto-connect to serial port: {str(e)}")
  93. # Initialize LED controller based on saved configuration
  94. try:
  95. # Auto-detect provider for backward compatibility with existing installations
  96. if not state.led_provider or state.led_provider == "none":
  97. if state.wled_ip:
  98. state.led_provider = "wled"
  99. logger.info("Auto-detected WLED provider from existing configuration")
  100. # Initialize the appropriate controller
  101. if state.led_provider == "wled" and state.wled_ip:
  102. state.led_controller = LEDInterface("wled", state.wled_ip)
  103. logger.info(f"LED controller initialized: WLED at {state.wled_ip}")
  104. elif state.led_provider == "dw_leds":
  105. state.led_controller = LEDInterface(
  106. "dw_leds",
  107. num_leds=state.dw_led_num_leds,
  108. gpio_pin=state.dw_led_gpio_pin,
  109. pixel_order=state.dw_led_pixel_order,
  110. brightness=state.dw_led_brightness / 100.0,
  111. speed=state.dw_led_speed,
  112. intensity=state.dw_led_intensity
  113. )
  114. 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})")
  115. else:
  116. state.led_controller = None
  117. logger.info("LED controller not configured")
  118. # Save if provider was auto-detected
  119. if state.led_provider and state.wled_ip:
  120. state.save()
  121. except Exception as e:
  122. logger.warning(f"Failed to initialize LED controller: {str(e)}")
  123. state.led_controller = None
  124. # Check if auto_play mode is enabled and auto-play playlist (right after connection attempt)
  125. if state.auto_play_enabled and state.auto_play_playlist:
  126. logger.info(f"auto_play mode enabled, checking for connection before auto-playing playlist: {state.auto_play_playlist}")
  127. try:
  128. # Check if we have a valid connection before starting playlist
  129. if state.conn and hasattr(state.conn, 'is_connected') and state.conn.is_connected():
  130. logger.info(f"Connection available, starting auto-play playlist: {state.auto_play_playlist} with options: run_mode={state.auto_play_run_mode}, pause_time={state.auto_play_pause_time}, clear_pattern={state.auto_play_clear_pattern}, shuffle={state.auto_play_shuffle}")
  131. asyncio.create_task(playlist_manager.run_playlist(
  132. state.auto_play_playlist,
  133. pause_time=state.auto_play_pause_time,
  134. clear_pattern=state.auto_play_clear_pattern,
  135. run_mode=state.auto_play_run_mode,
  136. shuffle=state.auto_play_shuffle
  137. ))
  138. else:
  139. logger.warning("No hardware connection available, skipping auto_play mode auto-play")
  140. except Exception as e:
  141. logger.error(f"Failed to auto-play auto_play playlist: {str(e)}")
  142. try:
  143. mqtt_handler = mqtt.init_mqtt()
  144. except Exception as e:
  145. logger.warning(f"Failed to initialize MQTT: {str(e)}")
  146. # Schedule cache generation check for later (non-blocking startup)
  147. async def delayed_cache_check():
  148. """Check and generate cache in background."""
  149. try:
  150. logger.info("Starting cache check...")
  151. from modules.core.cache_manager import is_cache_generation_needed_async, generate_cache_background
  152. if await is_cache_generation_needed_async():
  153. logger.info("Cache generation needed, starting background task...")
  154. asyncio.create_task(generate_cache_background()) # Don't await - run in background
  155. else:
  156. logger.info("Cache is up to date, skipping generation")
  157. except Exception as e:
  158. logger.warning(f"Failed during cache generation: {str(e)}")
  159. # Start cache check in background immediately
  160. asyncio.create_task(delayed_cache_check())
  161. # Start idle timeout monitor
  162. async def idle_timeout_monitor():
  163. """Monitor LED idle timeout and turn off LEDs when timeout expires."""
  164. import time
  165. while True:
  166. try:
  167. await asyncio.sleep(30) # Check every 30 seconds
  168. if not state.dw_led_idle_timeout_enabled:
  169. continue
  170. if not state.led_controller or not state.led_controller.is_configured:
  171. continue
  172. # Check if we're currently playing a pattern
  173. is_playing = bool(state.current_playing_file or state.current_playlist)
  174. if is_playing:
  175. # Reset activity time when playing
  176. state.dw_led_last_activity_time = time.time()
  177. continue
  178. # If no activity time set, initialize it
  179. if state.dw_led_last_activity_time is None:
  180. state.dw_led_last_activity_time = time.time()
  181. continue
  182. # Calculate idle duration
  183. idle_seconds = time.time() - state.dw_led_last_activity_time
  184. timeout_seconds = state.dw_led_idle_timeout_minutes * 60
  185. # Turn off LEDs if timeout expired
  186. if idle_seconds >= timeout_seconds:
  187. status = state.led_controller.check_status()
  188. # Check both "power" (WLED) and "power_on" (DW LEDs) keys
  189. is_powered_on = status.get("power", False) or status.get("power_on", False)
  190. if is_powered_on: # Only turn off if currently on
  191. logger.info(f"Idle timeout ({state.dw_led_idle_timeout_minutes} minutes) expired, turning off LEDs")
  192. state.led_controller.set_power(0)
  193. # Reset activity time to prevent repeated turn-off attempts
  194. state.dw_led_last_activity_time = time.time()
  195. except Exception as e:
  196. logger.error(f"Error in idle timeout monitor: {e}")
  197. await asyncio.sleep(60) # Wait longer on error
  198. asyncio.create_task(idle_timeout_monitor())
  199. yield # This separates startup from shutdown code
  200. # Shutdown
  201. logger.info("Shutting down Dune Weaver application...")
  202. # Shutdown process pool
  203. if process_pool:
  204. process_pool.shutdown(wait=True)
  205. logger.info("Process pool shutdown complete")
  206. app = FastAPI(lifespan=lifespan)
  207. templates = Jinja2Templates(directory="templates")
  208. app.mount("/static", StaticFiles(directory="static"), name="static")
  209. # Pydantic models for request/response validation
  210. class ConnectRequest(BaseModel):
  211. port: Optional[str] = None
  212. class auto_playModeRequest(BaseModel):
  213. enabled: bool
  214. playlist: Optional[str] = None
  215. run_mode: Optional[str] = "loop"
  216. pause_time: Optional[float] = 5.0
  217. clear_pattern: Optional[str] = "adaptive"
  218. shuffle: Optional[bool] = False
  219. class TimeSlot(BaseModel):
  220. start_time: str # HH:MM format
  221. end_time: str # HH:MM format
  222. days: str # "daily", "weekdays", "weekends", or "custom"
  223. custom_days: Optional[List[str]] = [] # ["monday", "tuesday", etc.]
  224. class ScheduledPauseRequest(BaseModel):
  225. enabled: bool
  226. control_wled: Optional[bool] = False
  227. finish_pattern: Optional[bool] = False # Finish current pattern before pausing
  228. time_slots: List[TimeSlot] = []
  229. class CoordinateRequest(BaseModel):
  230. theta: float
  231. rho: float
  232. class PlaylistRequest(BaseModel):
  233. playlist_name: str
  234. files: List[str] = []
  235. pause_time: float = 0
  236. clear_pattern: Optional[str] = None
  237. run_mode: str = "single"
  238. shuffle: bool = False
  239. class PlaylistRunRequest(BaseModel):
  240. playlist_name: str
  241. pause_time: Optional[float] = 0
  242. clear_pattern: Optional[str] = None
  243. run_mode: Optional[str] = "single"
  244. shuffle: Optional[bool] = False
  245. start_time: Optional[str] = None
  246. end_time: Optional[str] = None
  247. class SpeedRequest(BaseModel):
  248. speed: float
  249. class WLEDRequest(BaseModel):
  250. wled_ip: Optional[str] = None
  251. class LEDConfigRequest(BaseModel):
  252. provider: str # "wled", "dw_leds", or "none"
  253. ip_address: Optional[str] = None # For WLED only
  254. # DW LED specific fields
  255. num_leds: Optional[int] = None
  256. gpio_pin: Optional[int] = None
  257. pixel_order: Optional[str] = None
  258. brightness: Optional[int] = None
  259. class DeletePlaylistRequest(BaseModel):
  260. playlist_name: str
  261. class RenamePlaylistRequest(BaseModel):
  262. old_name: str
  263. new_name: str
  264. class ThetaRhoRequest(BaseModel):
  265. file_name: str
  266. pre_execution: Optional[str] = "none"
  267. class GetCoordinatesRequest(BaseModel):
  268. file_name: str
  269. # Store active WebSocket connections
  270. active_status_connections = set()
  271. active_cache_progress_connections = set()
  272. @app.websocket("/ws/status")
  273. async def websocket_status_endpoint(websocket: WebSocket):
  274. await websocket.accept()
  275. active_status_connections.add(websocket)
  276. try:
  277. while True:
  278. status = pattern_manager.get_status()
  279. try:
  280. await websocket.send_json({
  281. "type": "status_update",
  282. "data": status
  283. })
  284. except RuntimeError as e:
  285. if "close message has been sent" in str(e):
  286. break
  287. raise
  288. await asyncio.sleep(1)
  289. except WebSocketDisconnect:
  290. pass
  291. finally:
  292. active_status_connections.discard(websocket)
  293. try:
  294. await websocket.close()
  295. except RuntimeError:
  296. pass
  297. async def broadcast_status_update(status: dict):
  298. """Broadcast status update to all connected clients."""
  299. disconnected = set()
  300. for websocket in active_status_connections:
  301. try:
  302. await websocket.send_json({
  303. "type": "status_update",
  304. "data": status
  305. })
  306. except WebSocketDisconnect:
  307. disconnected.add(websocket)
  308. except RuntimeError:
  309. disconnected.add(websocket)
  310. active_status_connections.difference_update(disconnected)
  311. @app.websocket("/ws/cache-progress")
  312. async def websocket_cache_progress_endpoint(websocket: WebSocket):
  313. from modules.core.cache_manager import get_cache_progress
  314. await websocket.accept()
  315. active_cache_progress_connections.add(websocket)
  316. try:
  317. while True:
  318. progress = get_cache_progress()
  319. try:
  320. await websocket.send_json({
  321. "type": "cache_progress",
  322. "data": progress
  323. })
  324. except RuntimeError as e:
  325. if "close message has been sent" in str(e):
  326. break
  327. raise
  328. await asyncio.sleep(1.0) # Update every 1 second (reduced frequency for better performance)
  329. except WebSocketDisconnect:
  330. pass
  331. finally:
  332. active_cache_progress_connections.discard(websocket)
  333. try:
  334. await websocket.close()
  335. except RuntimeError:
  336. pass
  337. # FastAPI routes
  338. @app.get("/")
  339. async def index(request: Request):
  340. return templates.TemplateResponse("index.html", {"request": request, "app_name": state.app_name})
  341. @app.get("/settings")
  342. async def settings(request: Request):
  343. return templates.TemplateResponse("settings.html", {"request": request, "app_name": state.app_name})
  344. @app.get("/api/auto_play-mode")
  345. async def get_auto_play_mode():
  346. """Get current auto_play mode settings."""
  347. return {
  348. "enabled": state.auto_play_enabled,
  349. "playlist": state.auto_play_playlist,
  350. "run_mode": state.auto_play_run_mode,
  351. "pause_time": state.auto_play_pause_time,
  352. "clear_pattern": state.auto_play_clear_pattern,
  353. "shuffle": state.auto_play_shuffle
  354. }
  355. @app.post("/api/auto_play-mode")
  356. async def set_auto_play_mode(request: auto_playModeRequest):
  357. """Update auto_play mode settings."""
  358. state.auto_play_enabled = request.enabled
  359. if request.playlist is not None:
  360. state.auto_play_playlist = request.playlist
  361. if request.run_mode is not None:
  362. state.auto_play_run_mode = request.run_mode
  363. if request.pause_time is not None:
  364. state.auto_play_pause_time = request.pause_time
  365. if request.clear_pattern is not None:
  366. state.auto_play_clear_pattern = request.clear_pattern
  367. if request.shuffle is not None:
  368. state.auto_play_shuffle = request.shuffle
  369. state.save()
  370. logger.info(f"auto_play mode {'enabled' if request.enabled else 'disabled'}, playlist: {request.playlist}")
  371. return {"success": True, "message": "auto_play mode settings updated"}
  372. @app.get("/api/scheduled-pause")
  373. async def get_scheduled_pause():
  374. """Get current Still Sands settings."""
  375. return {
  376. "enabled": state.scheduled_pause_enabled,
  377. "control_wled": state.scheduled_pause_control_wled,
  378. "finish_pattern": state.scheduled_pause_finish_pattern,
  379. "time_slots": state.scheduled_pause_time_slots
  380. }
  381. @app.post("/api/scheduled-pause")
  382. async def set_scheduled_pause(request: ScheduledPauseRequest):
  383. """Update Still Sands settings."""
  384. try:
  385. # Validate time slots
  386. for i, slot in enumerate(request.time_slots):
  387. # Validate time format (HH:MM)
  388. try:
  389. start_time = datetime.strptime(slot.start_time, "%H:%M").time()
  390. end_time = datetime.strptime(slot.end_time, "%H:%M").time()
  391. except ValueError:
  392. raise HTTPException(
  393. status_code=400,
  394. detail=f"Invalid time format in slot {i+1}. Use HH:MM format."
  395. )
  396. # Validate days setting
  397. if slot.days not in ["daily", "weekdays", "weekends", "custom"]:
  398. raise HTTPException(
  399. status_code=400,
  400. detail=f"Invalid days setting in slot {i+1}. Must be 'daily', 'weekdays', 'weekends', or 'custom'."
  401. )
  402. # Validate custom days if applicable
  403. if slot.days == "custom":
  404. if not slot.custom_days or len(slot.custom_days) == 0:
  405. raise HTTPException(
  406. status_code=400,
  407. detail=f"Custom days must be specified for slot {i+1} when days is set to 'custom'."
  408. )
  409. valid_days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
  410. for day in slot.custom_days:
  411. if day not in valid_days:
  412. raise HTTPException(
  413. status_code=400,
  414. detail=f"Invalid day '{day}' in slot {i+1}. Valid days are: {', '.join(valid_days)}"
  415. )
  416. # Update state
  417. state.scheduled_pause_enabled = request.enabled
  418. state.scheduled_pause_control_wled = request.control_wled
  419. state.scheduled_pause_finish_pattern = request.finish_pattern
  420. state.scheduled_pause_time_slots = [slot.model_dump() for slot in request.time_slots]
  421. state.save()
  422. wled_msg = " (with WLED control)" if request.control_wled else ""
  423. finish_msg = " (finish pattern first)" if request.finish_pattern else ""
  424. logger.info(f"Still Sands {'enabled' if request.enabled else 'disabled'} with {len(request.time_slots)} time slots{wled_msg}{finish_msg}")
  425. return {"success": True, "message": "Still Sands settings updated"}
  426. except HTTPException:
  427. raise
  428. except Exception as e:
  429. logger.error(f"Error updating Still Sands settings: {str(e)}")
  430. raise HTTPException(status_code=500, detail=f"Failed to update Still Sands settings: {str(e)}")
  431. @app.get("/api/homing-config")
  432. async def get_homing_config():
  433. """Get homing configuration (mode and compass offset)."""
  434. return {
  435. "homing_mode": state.homing,
  436. "angular_homing_offset_degrees": state.angular_homing_offset_degrees
  437. }
  438. class HomingConfigRequest(BaseModel):
  439. homing_mode: int = 0 # 0 = crash, 1 = sensor
  440. angular_homing_offset_degrees: float = 0.0
  441. @app.post("/api/homing-config")
  442. async def set_homing_config(request: HomingConfigRequest):
  443. """Set homing configuration (mode and compass offset)."""
  444. try:
  445. # Validate homing mode
  446. if request.homing_mode not in [0, 1]:
  447. raise HTTPException(status_code=400, detail="Homing mode must be 0 (crash) or 1 (sensor)")
  448. state.homing = request.homing_mode
  449. state.angular_homing_offset_degrees = request.angular_homing_offset_degrees
  450. state.save()
  451. mode_name = "crash" if request.homing_mode == 0 else "sensor"
  452. logger.info(f"Homing mode set to {mode_name}, compass offset set to {request.angular_homing_offset_degrees}°")
  453. return {"success": True, "message": "Homing configuration updated"}
  454. except HTTPException:
  455. raise
  456. except Exception as e:
  457. logger.error(f"Error updating homing configuration: {str(e)}")
  458. raise HTTPException(status_code=500, detail=f"Failed to update homing configuration: {str(e)}")
  459. @app.get("/list_serial_ports")
  460. async def list_ports():
  461. logger.debug("Listing available serial ports")
  462. return await asyncio.to_thread(connection_manager.list_serial_ports)
  463. @app.post("/connect")
  464. async def connect(request: ConnectRequest):
  465. if not request.port:
  466. state.conn = connection_manager.WebSocketConnection('ws://fluidnc.local:81')
  467. connection_manager.device_init()
  468. logger.info('Successfully connected to websocket ws://fluidnc.local:81')
  469. return {"success": True}
  470. try:
  471. state.conn = connection_manager.SerialConnection(request.port)
  472. connection_manager.device_init()
  473. logger.info(f'Successfully connected to serial port {request.port}')
  474. return {"success": True}
  475. except Exception as e:
  476. logger.error(f'Failed to connect to serial port {request.port}: {str(e)}')
  477. raise HTTPException(status_code=500, detail=str(e))
  478. @app.post("/disconnect")
  479. async def disconnect():
  480. try:
  481. state.conn.close()
  482. logger.info('Successfully disconnected from serial port')
  483. return {"success": True}
  484. except Exception as e:
  485. logger.error(f'Failed to disconnect serial: {str(e)}')
  486. raise HTTPException(status_code=500, detail=str(e))
  487. @app.post("/restart_connection")
  488. async def restart(request: ConnectRequest):
  489. if not request.port:
  490. logger.warning("Restart serial request received without port")
  491. raise HTTPException(status_code=400, detail="No port provided")
  492. try:
  493. logger.info(f"Restarting connection on port {request.port}")
  494. connection_manager.restart_connection()
  495. return {"success": True}
  496. except Exception as e:
  497. logger.error(f"Failed to restart serial on port {request.port}: {str(e)}")
  498. raise HTTPException(status_code=500, detail=str(e))
  499. @app.get("/list_theta_rho_files")
  500. async def list_theta_rho_files():
  501. logger.debug("Listing theta-rho files")
  502. # Run the blocking file system operation in a thread pool
  503. files = await asyncio.to_thread(pattern_manager.list_theta_rho_files)
  504. return sorted(files)
  505. @app.get("/list_theta_rho_files_with_metadata")
  506. async def list_theta_rho_files_with_metadata():
  507. """Get list of theta-rho files with metadata for sorting and filtering.
  508. Optimized to process files asynchronously and support request cancellation.
  509. """
  510. from modules.core.cache_manager import get_pattern_metadata
  511. import asyncio
  512. from concurrent.futures import ThreadPoolExecutor
  513. # Run the blocking file listing in a thread
  514. files = await asyncio.to_thread(pattern_manager.list_theta_rho_files)
  515. files_with_metadata = []
  516. # Use ThreadPoolExecutor for I/O-bound operations
  517. executor = ThreadPoolExecutor(max_workers=4)
  518. def process_file(file_path):
  519. """Process a single file and return its metadata."""
  520. try:
  521. full_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_path)
  522. # Get file stats
  523. file_stat = os.stat(full_path)
  524. # Get cached metadata (this should be fast if cached)
  525. metadata = get_pattern_metadata(file_path)
  526. # Extract full folder path from file path
  527. path_parts = file_path.split('/')
  528. if len(path_parts) > 1:
  529. # Get everything except the filename (join all folder parts)
  530. category = '/'.join(path_parts[:-1])
  531. else:
  532. category = 'root'
  533. # Get file name without extension
  534. file_name = os.path.splitext(os.path.basename(file_path))[0]
  535. # Use modification time (mtime) for "date modified"
  536. date_modified = file_stat.st_mtime
  537. return {
  538. 'path': file_path,
  539. 'name': file_name,
  540. 'category': category,
  541. 'date_modified': date_modified,
  542. 'coordinates_count': metadata.get('total_coordinates', 0) if metadata else 0
  543. }
  544. except Exception as e:
  545. logger.warning(f"Error getting metadata for {file_path}: {str(e)}")
  546. # Include file with minimal info if metadata fails
  547. path_parts = file_path.split('/')
  548. if len(path_parts) > 1:
  549. category = '/'.join(path_parts[:-1])
  550. else:
  551. category = 'root'
  552. return {
  553. 'path': file_path,
  554. 'name': os.path.splitext(os.path.basename(file_path))[0],
  555. 'category': category,
  556. 'date_modified': 0,
  557. 'coordinates_count': 0
  558. }
  559. # Load the entire metadata cache at once (async)
  560. # This is much faster than 1000+ individual metadata lookups
  561. try:
  562. import json
  563. metadata_cache_path = "metadata_cache.json"
  564. # Use async file reading to avoid blocking the event loop
  565. cache_data = await asyncio.to_thread(lambda: json.load(open(metadata_cache_path, 'r')))
  566. cache_dict = cache_data.get('data', {})
  567. logger.debug(f"Loaded metadata cache with {len(cache_dict)} entries")
  568. # Process all files using cached data only
  569. for file_path in files:
  570. try:
  571. # Extract category from path
  572. path_parts = file_path.split('/')
  573. category = '/'.join(path_parts[:-1]) if len(path_parts) > 1 else 'root'
  574. # Get file name without extension
  575. file_name = os.path.splitext(os.path.basename(file_path))[0]
  576. # Get metadata from cache
  577. cached_entry = cache_dict.get(file_path, {})
  578. if isinstance(cached_entry, dict) and 'metadata' in cached_entry:
  579. metadata = cached_entry['metadata']
  580. coords_count = metadata.get('total_coordinates', 0)
  581. date_modified = cached_entry.get('mtime', 0)
  582. else:
  583. coords_count = 0
  584. date_modified = 0
  585. files_with_metadata.append({
  586. 'path': file_path,
  587. 'name': file_name,
  588. 'category': category,
  589. 'date_modified': date_modified,
  590. 'coordinates_count': coords_count
  591. })
  592. except Exception as e:
  593. logger.warning(f"Error processing {file_path}: {e}")
  594. # Include file with minimal info if processing fails
  595. path_parts = file_path.split('/')
  596. category = '/'.join(path_parts[:-1]) if len(path_parts) > 1 else 'root'
  597. files_with_metadata.append({
  598. 'path': file_path,
  599. 'name': os.path.splitext(os.path.basename(file_path))[0],
  600. 'category': category,
  601. 'date_modified': 0,
  602. 'coordinates_count': 0
  603. })
  604. except Exception as e:
  605. logger.error(f"Failed to load metadata cache, falling back to slow method: {e}")
  606. # Fallback to original method if cache loading fails
  607. # Create tasks only when needed
  608. loop = asyncio.get_event_loop()
  609. tasks = [loop.run_in_executor(executor, process_file, file_path) for file_path in files]
  610. for task in asyncio.as_completed(tasks):
  611. try:
  612. result = await task
  613. files_with_metadata.append(result)
  614. except Exception as task_error:
  615. logger.error(f"Error processing file: {str(task_error)}")
  616. # Clean up executor
  617. executor.shutdown(wait=False)
  618. return files_with_metadata
  619. @app.post("/upload_theta_rho")
  620. async def upload_theta_rho(file: UploadFile = File(...)):
  621. """Upload a theta-rho file."""
  622. try:
  623. # Save the file
  624. # Ensure custom_patterns directory exists
  625. custom_patterns_dir = os.path.join(pattern_manager.THETA_RHO_DIR, "custom_patterns")
  626. os.makedirs(custom_patterns_dir, exist_ok=True)
  627. # Use forward slashes for internal path representation to maintain consistency
  628. file_path_in_patterns_dir = f"custom_patterns/{file.filename}"
  629. full_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_path_in_patterns_dir)
  630. # Save the uploaded file with proper encoding for Windows compatibility
  631. file_content = await file.read()
  632. try:
  633. # First try to decode as UTF-8 and re-encode to ensure proper encoding
  634. text_content = file_content.decode('utf-8')
  635. with open(full_file_path, "w", encoding='utf-8') as f:
  636. f.write(text_content)
  637. except UnicodeDecodeError:
  638. # If UTF-8 decoding fails, save as binary (fallback)
  639. with open(full_file_path, "wb") as f:
  640. f.write(file_content)
  641. logger.info(f"File {file.filename} saved successfully")
  642. # Generate image preview for the new file with retry logic
  643. max_retries = 3
  644. for attempt in range(max_retries):
  645. try:
  646. logger.info(f"Generating preview for {file_path_in_patterns_dir} (attempt {attempt + 1}/{max_retries})")
  647. success = await generate_image_preview(file_path_in_patterns_dir)
  648. if success:
  649. logger.info(f"Preview generated successfully for {file_path_in_patterns_dir}")
  650. break
  651. else:
  652. logger.warning(f"Preview generation failed for {file_path_in_patterns_dir} (attempt {attempt + 1})")
  653. if attempt < max_retries - 1:
  654. await asyncio.sleep(0.5) # Small delay before retry
  655. except Exception as e:
  656. logger.error(f"Error generating preview for {file_path_in_patterns_dir} (attempt {attempt + 1}): {str(e)}")
  657. if attempt < max_retries - 1:
  658. await asyncio.sleep(0.5) # Small delay before retry
  659. return {"success": True, "message": f"File {file.filename} uploaded successfully"}
  660. except Exception as e:
  661. logger.error(f"Error uploading file: {str(e)}")
  662. raise HTTPException(status_code=500, detail=str(e))
  663. @app.post("/get_theta_rho_coordinates")
  664. async def get_theta_rho_coordinates(request: GetCoordinatesRequest):
  665. """Get theta-rho coordinates for animated preview."""
  666. try:
  667. # Normalize file path for cross-platform compatibility and remove prefixes
  668. file_name = normalize_file_path(request.file_name)
  669. file_path = os.path.join(THETA_RHO_DIR, file_name)
  670. # Check file existence asynchronously
  671. exists = await asyncio.to_thread(os.path.exists, file_path)
  672. if not exists:
  673. raise HTTPException(status_code=404, detail=f"File {file_name} not found")
  674. # Parse the theta-rho file in a separate process for CPU-intensive work
  675. # This prevents blocking the motion control thread
  676. loop = asyncio.get_event_loop()
  677. coordinates = await loop.run_in_executor(process_pool, parse_theta_rho_file, file_path)
  678. if not coordinates:
  679. raise HTTPException(status_code=400, detail="No valid coordinates found in file")
  680. return {
  681. "success": True,
  682. "coordinates": coordinates,
  683. "total_points": len(coordinates)
  684. }
  685. except Exception as e:
  686. logger.error(f"Error getting coordinates for {request.file_name}: {str(e)}")
  687. raise HTTPException(status_code=500, detail=str(e))
  688. @app.post("/run_theta_rho")
  689. async def run_theta_rho(request: ThetaRhoRequest, background_tasks: BackgroundTasks):
  690. if not request.file_name:
  691. logger.warning('Run theta-rho request received without file name')
  692. raise HTTPException(status_code=400, detail="No file name provided")
  693. file_path = None
  694. if 'clear' in request.file_name:
  695. logger.info(f'Clear pattern file: {request.file_name.split(".")[0]}')
  696. file_path = pattern_manager.get_clear_pattern_file(request.file_name.split('.')[0])
  697. logger.info(f'Clear pattern file: {file_path}')
  698. if not file_path:
  699. # Normalize file path for cross-platform compatibility
  700. normalized_file_name = normalize_file_path(request.file_name)
  701. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  702. if not os.path.exists(file_path):
  703. logger.error(f'Theta-rho file not found: {file_path}')
  704. raise HTTPException(status_code=404, detail="File not found")
  705. try:
  706. if not (state.conn.is_connected() if state.conn else False):
  707. logger.warning("Attempted to run a pattern without a connection")
  708. raise HTTPException(status_code=400, detail="Connection not established")
  709. if pattern_manager.pattern_lock.locked():
  710. logger.warning("Attempted to run a pattern while another is already running")
  711. raise HTTPException(status_code=409, detail="Another pattern is already running")
  712. files_to_run = [file_path]
  713. logger.info(f'Running theta-rho file: {request.file_name} with pre_execution={request.pre_execution}')
  714. # Only include clear_pattern if it's not "none"
  715. kwargs = {}
  716. if request.pre_execution != "none":
  717. kwargs['clear_pattern'] = request.pre_execution
  718. # Pass arguments properly
  719. background_tasks.add_task(
  720. pattern_manager.run_theta_rho_files,
  721. files_to_run, # First positional argument
  722. **kwargs # Spread keyword arguments
  723. )
  724. return {"success": True}
  725. except HTTPException as http_exc:
  726. logger.error(f'Failed to run theta-rho file {request.file_name}: {http_exc.detail}')
  727. raise http_exc
  728. except Exception as e:
  729. logger.error(f'Failed to run theta-rho file {request.file_name}: {str(e)}')
  730. raise HTTPException(status_code=500, detail=str(e))
  731. @app.post("/stop_execution")
  732. async def stop_execution():
  733. if not (state.conn.is_connected() if state.conn else False):
  734. logger.warning("Attempted to stop without a connection")
  735. raise HTTPException(status_code=400, detail="Connection not established")
  736. await pattern_manager.stop_actions()
  737. return {"success": True}
  738. @app.post("/send_home")
  739. async def send_home():
  740. try:
  741. if not (state.conn.is_connected() if state.conn else False):
  742. logger.warning("Attempted to move to home without a connection")
  743. raise HTTPException(status_code=400, detail="Connection not established")
  744. # Run homing with 15 second timeout
  745. success = await asyncio.to_thread(connection_manager.home)
  746. if not success:
  747. logger.error("Homing failed or timed out")
  748. raise HTTPException(status_code=500, detail="Homing failed or timed out after 15 seconds")
  749. return {"success": True}
  750. except HTTPException:
  751. raise
  752. except Exception as e:
  753. logger.error(f"Failed to send home command: {str(e)}")
  754. raise HTTPException(status_code=500, detail=str(e))
  755. @app.post("/run_theta_rho_file/{file_name}")
  756. async def run_specific_theta_rho_file(file_name: str):
  757. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_name)
  758. if not os.path.exists(file_path):
  759. raise HTTPException(status_code=404, detail="File not found")
  760. if not (state.conn.is_connected() if state.conn else False):
  761. logger.warning("Attempted to run a pattern without a connection")
  762. raise HTTPException(status_code=400, detail="Connection not established")
  763. pattern_manager.run_theta_rho_file(file_path)
  764. return {"success": True}
  765. class DeleteFileRequest(BaseModel):
  766. file_name: str
  767. @app.post("/delete_theta_rho_file")
  768. async def delete_theta_rho_file(request: DeleteFileRequest):
  769. if not request.file_name:
  770. logger.warning("Delete theta-rho file request received without filename")
  771. raise HTTPException(status_code=400, detail="No file name provided")
  772. # Normalize file path for cross-platform compatibility
  773. normalized_file_name = normalize_file_path(request.file_name)
  774. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  775. # Check file existence asynchronously
  776. exists = await asyncio.to_thread(os.path.exists, file_path)
  777. if not exists:
  778. logger.error(f"Attempted to delete non-existent file: {file_path}")
  779. raise HTTPException(status_code=404, detail="File not found")
  780. try:
  781. # Delete the pattern file asynchronously
  782. await asyncio.to_thread(os.remove, file_path)
  783. logger.info(f"Successfully deleted theta-rho file: {request.file_name}")
  784. # Clean up cached preview image and metadata asynchronously
  785. from modules.core.cache_manager import delete_pattern_cache
  786. cache_cleanup_success = await asyncio.to_thread(delete_pattern_cache, normalized_file_name)
  787. if cache_cleanup_success:
  788. logger.info(f"Successfully cleaned up cache for {request.file_name}")
  789. else:
  790. logger.warning(f"Cache cleanup failed for {request.file_name}, but pattern was deleted")
  791. return {"success": True, "cache_cleanup": cache_cleanup_success}
  792. except Exception as e:
  793. logger.error(f"Failed to delete theta-rho file {request.file_name}: {str(e)}")
  794. raise HTTPException(status_code=500, detail=str(e))
  795. @app.post("/move_to_center")
  796. async def move_to_center():
  797. try:
  798. if not (state.conn.is_connected() if state.conn else False):
  799. logger.warning("Attempted to move to center without a connection")
  800. raise HTTPException(status_code=400, detail="Connection not established")
  801. logger.info("Moving device to center position")
  802. await pattern_manager.reset_theta()
  803. await pattern_manager.move_polar(0, 0)
  804. return {"success": True}
  805. except Exception as e:
  806. logger.error(f"Failed to move to center: {str(e)}")
  807. raise HTTPException(status_code=500, detail=str(e))
  808. @app.post("/move_to_perimeter")
  809. async def move_to_perimeter():
  810. try:
  811. if not (state.conn.is_connected() if state.conn else False):
  812. logger.warning("Attempted to move to perimeter without a connection")
  813. raise HTTPException(status_code=400, detail="Connection not established")
  814. await pattern_manager.reset_theta()
  815. await pattern_manager.move_polar(0, 1)
  816. return {"success": True}
  817. except Exception as e:
  818. logger.error(f"Failed to move to perimeter: {str(e)}")
  819. raise HTTPException(status_code=500, detail=str(e))
  820. @app.post("/preview_thr")
  821. async def preview_thr(request: DeleteFileRequest):
  822. if not request.file_name:
  823. logger.warning("Preview theta-rho request received without filename")
  824. raise HTTPException(status_code=400, detail="No file name provided")
  825. # Normalize file path for cross-platform compatibility
  826. normalized_file_name = normalize_file_path(request.file_name)
  827. # Construct the full path to the pattern file to check existence
  828. pattern_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  829. # Check file existence asynchronously
  830. exists = await asyncio.to_thread(os.path.exists, pattern_file_path)
  831. if not exists:
  832. logger.error(f"Attempted to preview non-existent pattern file: {pattern_file_path}")
  833. raise HTTPException(status_code=404, detail="Pattern file not found")
  834. try:
  835. cache_path = get_cache_path(normalized_file_name)
  836. # Check cache existence asynchronously
  837. cache_exists = await asyncio.to_thread(os.path.exists, cache_path)
  838. if not cache_exists:
  839. logger.info(f"Cache miss for {request.file_name}. Generating preview...")
  840. # Attempt to generate the preview if it's missing
  841. success = await generate_image_preview(normalized_file_name)
  842. cache_exists_after = await asyncio.to_thread(os.path.exists, cache_path)
  843. if not success or not cache_exists_after:
  844. logger.error(f"Failed to generate or find preview for {request.file_name} after attempting generation.")
  845. raise HTTPException(status_code=500, detail="Failed to generate preview image.")
  846. # Try to get coordinates from metadata cache first
  847. metadata = get_pattern_metadata(normalized_file_name)
  848. if metadata:
  849. first_coord_obj = metadata.get('first_coordinate')
  850. last_coord_obj = metadata.get('last_coordinate')
  851. else:
  852. # Fallback to parsing file if metadata not cached (shouldn't happen after initial cache)
  853. logger.debug(f"Metadata cache miss for {request.file_name}, parsing file")
  854. coordinates = await asyncio.to_thread(parse_theta_rho_file, pattern_file_path)
  855. first_coord = coordinates[0] if coordinates else None
  856. last_coord = coordinates[-1] if coordinates else None
  857. # Format coordinates as objects with x and y properties
  858. first_coord_obj = {"x": first_coord[0], "y": first_coord[1]} if first_coord else None
  859. last_coord_obj = {"x": last_coord[0], "y": last_coord[1]} if last_coord else None
  860. # Return JSON with preview URL and coordinates
  861. # URL encode the file_name for the preview URL
  862. # Handle both forward slashes and backslashes for cross-platform compatibility
  863. encoded_filename = normalized_file_name.replace('\\', '--').replace('/', '--')
  864. return {
  865. "preview_url": f"/preview/{encoded_filename}",
  866. "first_coordinate": first_coord_obj,
  867. "last_coordinate": last_coord_obj
  868. }
  869. except HTTPException:
  870. raise
  871. except Exception as e:
  872. logger.error(f"Failed to generate or serve preview for {request.file_name}: {str(e)}")
  873. raise HTTPException(status_code=500, detail=f"Failed to serve preview image: {str(e)}")
  874. @app.get("/preview/{encoded_filename}")
  875. async def serve_preview(encoded_filename: str):
  876. """Serve a preview image for a pattern file."""
  877. # Decode the filename by replacing -- with the original path separators
  878. # First try forward slash (most common case), then backslash if needed
  879. file_name = encoded_filename.replace('--', '/')
  880. # Apply normalization to handle any remaining path prefixes
  881. file_name = normalize_file_path(file_name)
  882. # Check if the decoded path exists, if not try backslash decoding
  883. cache_path = get_cache_path(file_name)
  884. if not os.path.exists(cache_path):
  885. # Try with backslash for Windows paths
  886. file_name_backslash = encoded_filename.replace('--', '\\')
  887. file_name_backslash = normalize_file_path(file_name_backslash)
  888. cache_path_backslash = get_cache_path(file_name_backslash)
  889. if os.path.exists(cache_path_backslash):
  890. file_name = file_name_backslash
  891. cache_path = cache_path_backslash
  892. # cache_path is already determined above in the decoding logic
  893. if not os.path.exists(cache_path):
  894. logger.error(f"Preview image not found for {file_name}")
  895. raise HTTPException(status_code=404, detail="Preview image not found")
  896. # Add caching headers
  897. headers = {
  898. "Cache-Control": "public, max-age=31536000", # Cache for 1 year
  899. "Content-Type": "image/webp",
  900. "Accept-Ranges": "bytes"
  901. }
  902. return FileResponse(
  903. cache_path,
  904. media_type="image/webp",
  905. headers=headers
  906. )
  907. @app.post("/send_coordinate")
  908. async def send_coordinate(request: CoordinateRequest):
  909. if not (state.conn.is_connected() if state.conn else False):
  910. logger.warning("Attempted to send coordinate without a connection")
  911. raise HTTPException(status_code=400, detail="Connection not established")
  912. try:
  913. logger.debug(f"Sending coordinate: theta={request.theta}, rho={request.rho}")
  914. await pattern_manager.move_polar(request.theta, request.rho)
  915. return {"success": True}
  916. except Exception as e:
  917. logger.error(f"Failed to send coordinate: {str(e)}")
  918. raise HTTPException(status_code=500, detail=str(e))
  919. @app.get("/download/{filename}")
  920. async def download_file(filename: str):
  921. return FileResponse(
  922. os.path.join(pattern_manager.THETA_RHO_DIR, filename),
  923. filename=filename
  924. )
  925. @app.get("/serial_status")
  926. async def serial_status():
  927. connected = state.conn.is_connected() if state.conn else False
  928. port = state.port
  929. logger.debug(f"Serial status check - connected: {connected}, port: {port}")
  930. return {
  931. "connected": connected,
  932. "port": port,
  933. "preferred_port": state.preferred_port
  934. }
  935. @app.get("/api/preferred-port")
  936. async def get_preferred_port():
  937. """Get the currently configured preferred port for auto-connect."""
  938. return {
  939. "preferred_port": state.preferred_port
  940. }
  941. @app.post("/api/preferred-port")
  942. async def set_preferred_port(request: Request):
  943. """Set the preferred port for auto-connect."""
  944. data = await request.json()
  945. preferred_port = data.get("preferred_port")
  946. # Allow setting to None to clear the preference
  947. if preferred_port == "" or preferred_port == "none":
  948. preferred_port = None
  949. state.preferred_port = preferred_port
  950. state.save()
  951. logger.info(f"Preferred port set to: {preferred_port}")
  952. return {
  953. "success": True,
  954. "preferred_port": state.preferred_port
  955. }
  956. @app.post("/pause_execution")
  957. async def pause_execution():
  958. if pattern_manager.pause_execution():
  959. return {"success": True, "message": "Execution paused"}
  960. raise HTTPException(status_code=500, detail="Failed to pause execution")
  961. @app.post("/resume_execution")
  962. async def resume_execution():
  963. if pattern_manager.resume_execution():
  964. return {"success": True, "message": "Execution resumed"}
  965. raise HTTPException(status_code=500, detail="Failed to resume execution")
  966. # Playlist endpoints
  967. @app.get("/list_all_playlists")
  968. async def list_all_playlists():
  969. playlist_names = playlist_manager.list_all_playlists()
  970. return playlist_names
  971. @app.get("/get_playlist")
  972. async def get_playlist(name: str):
  973. if not name:
  974. raise HTTPException(status_code=400, detail="Missing playlist name parameter")
  975. playlist = playlist_manager.get_playlist(name)
  976. if not playlist:
  977. raise HTTPException(status_code=404, detail=f"Playlist '{name}' not found")
  978. return playlist
  979. @app.post("/create_playlist")
  980. async def create_playlist(request: PlaylistRequest):
  981. success = playlist_manager.create_playlist(request.playlist_name, request.files)
  982. return {
  983. "success": success,
  984. "message": f"Playlist '{request.playlist_name}' created/updated"
  985. }
  986. @app.post("/modify_playlist")
  987. async def modify_playlist(request: PlaylistRequest):
  988. success = playlist_manager.modify_playlist(request.playlist_name, request.files)
  989. return {
  990. "success": success,
  991. "message": f"Playlist '{request.playlist_name}' updated"
  992. }
  993. @app.delete("/delete_playlist")
  994. async def delete_playlist(request: DeletePlaylistRequest):
  995. success = playlist_manager.delete_playlist(request.playlist_name)
  996. if not success:
  997. raise HTTPException(
  998. status_code=404,
  999. detail=f"Playlist '{request.playlist_name}' not found"
  1000. )
  1001. return {
  1002. "success": True,
  1003. "message": f"Playlist '{request.playlist_name}' deleted"
  1004. }
  1005. @app.post("/rename_playlist")
  1006. async def rename_playlist(request: RenamePlaylistRequest):
  1007. """Rename an existing playlist."""
  1008. success, message = playlist_manager.rename_playlist(request.old_name, request.new_name)
  1009. if not success:
  1010. raise HTTPException(
  1011. status_code=400,
  1012. detail=message
  1013. )
  1014. return {
  1015. "success": True,
  1016. "message": message,
  1017. "new_name": request.new_name
  1018. }
  1019. class AddToPlaylistRequest(BaseModel):
  1020. playlist_name: str
  1021. pattern: str
  1022. @app.post("/add_to_playlist")
  1023. async def add_to_playlist(request: AddToPlaylistRequest):
  1024. success = playlist_manager.add_to_playlist(request.playlist_name, request.pattern)
  1025. if not success:
  1026. raise HTTPException(status_code=404, detail="Playlist not found")
  1027. return {"success": True}
  1028. @app.post("/run_playlist")
  1029. async def run_playlist_endpoint(request: PlaylistRequest):
  1030. """Run a playlist with specified parameters."""
  1031. try:
  1032. if not (state.conn.is_connected() if state.conn else False):
  1033. logger.warning("Attempted to run a playlist without a connection")
  1034. raise HTTPException(status_code=400, detail="Connection not established")
  1035. if not os.path.exists(playlist_manager.PLAYLISTS_FILE):
  1036. raise HTTPException(status_code=404, detail=f"Playlist '{request.playlist_name}' not found")
  1037. # Start the playlist execution
  1038. success, message = await playlist_manager.run_playlist(
  1039. request.playlist_name,
  1040. pause_time=request.pause_time,
  1041. clear_pattern=request.clear_pattern,
  1042. run_mode=request.run_mode,
  1043. shuffle=request.shuffle
  1044. )
  1045. if not success:
  1046. raise HTTPException(status_code=409, detail=message)
  1047. return {"message": f"Started playlist: {request.playlist_name}"}
  1048. except Exception as e:
  1049. logger.error(f"Error running playlist: {e}")
  1050. raise HTTPException(status_code=500, detail=str(e))
  1051. @app.post("/set_speed")
  1052. async def set_speed(request: SpeedRequest):
  1053. try:
  1054. if not (state.conn.is_connected() if state.conn else False):
  1055. logger.warning("Attempted to change speed without a connection")
  1056. raise HTTPException(status_code=400, detail="Connection not established")
  1057. if request.speed <= 0:
  1058. logger.warning(f"Invalid speed value received: {request.speed}")
  1059. raise HTTPException(status_code=400, detail="Invalid speed value")
  1060. state.speed = request.speed
  1061. return {"success": True, "speed": request.speed}
  1062. except Exception as e:
  1063. logger.error(f"Failed to set speed: {str(e)}")
  1064. raise HTTPException(status_code=500, detail=str(e))
  1065. @app.get("/check_software_update")
  1066. async def check_updates():
  1067. update_info = update_manager.check_git_updates()
  1068. return update_info
  1069. @app.post("/update_software")
  1070. async def update_software():
  1071. logger.info("Starting software update process")
  1072. success, error_message, error_log = update_manager.update_software()
  1073. if success:
  1074. logger.info("Software update completed successfully")
  1075. return {"success": True}
  1076. else:
  1077. logger.error(f"Software update failed: {error_message}\nDetails: {error_log}")
  1078. raise HTTPException(
  1079. status_code=500,
  1080. detail={
  1081. "error": error_message,
  1082. "details": error_log
  1083. }
  1084. )
  1085. @app.post("/set_wled_ip")
  1086. async def set_wled_ip(request: WLEDRequest):
  1087. """Legacy endpoint for backward compatibility - sets WLED as LED provider"""
  1088. state.wled_ip = request.wled_ip
  1089. state.led_provider = "wled" if request.wled_ip else "none"
  1090. state.led_controller = LEDInterface("wled", request.wled_ip) if request.wled_ip else None
  1091. if state.led_controller:
  1092. state.led_controller.effect_idle()
  1093. _start_idle_led_timeout()
  1094. state.save()
  1095. logger.info(f"WLED IP updated: {request.wled_ip}")
  1096. return {"success": True, "wled_ip": state.wled_ip}
  1097. @app.get("/get_wled_ip")
  1098. async def get_wled_ip():
  1099. """Legacy endpoint for backward compatibility"""
  1100. if not state.wled_ip:
  1101. raise HTTPException(status_code=404, detail="No WLED IP set")
  1102. return {"success": True, "wled_ip": state.wled_ip}
  1103. @app.post("/set_led_config")
  1104. async def set_led_config(request: LEDConfigRequest):
  1105. """Configure LED provider (WLED, DW LEDs, or none)"""
  1106. if request.provider not in ["wled", "dw_leds", "none"]:
  1107. raise HTTPException(status_code=400, detail="Invalid provider. Must be 'wled', 'dw_leds', or 'none'")
  1108. state.led_provider = request.provider
  1109. if request.provider == "wled":
  1110. if not request.ip_address:
  1111. raise HTTPException(status_code=400, detail="IP address required for WLED")
  1112. state.wled_ip = request.ip_address
  1113. state.led_controller = LEDInterface("wled", request.ip_address)
  1114. logger.info(f"LED provider set to WLED at {request.ip_address}")
  1115. elif request.provider == "dw_leds":
  1116. # Check if hardware settings changed (requires restart)
  1117. old_gpio_pin = state.dw_led_gpio_pin
  1118. old_pixel_order = state.dw_led_pixel_order
  1119. hardware_changed = (
  1120. old_gpio_pin != (request.gpio_pin or 12) or
  1121. old_pixel_order != (request.pixel_order or "GRB")
  1122. )
  1123. # Stop existing DW LED controller if hardware settings changed
  1124. if hardware_changed and state.led_controller and state.led_provider == "dw_leds":
  1125. logger.info("Hardware settings changed, stopping existing LED controller...")
  1126. controller = state.led_controller.get_controller()
  1127. if controller and hasattr(controller, 'stop'):
  1128. try:
  1129. controller.stop()
  1130. logger.info("LED controller stopped successfully")
  1131. except Exception as e:
  1132. logger.error(f"Error stopping LED controller: {e}")
  1133. state.dw_led_num_leds = request.num_leds or 60
  1134. state.dw_led_gpio_pin = request.gpio_pin or 12
  1135. state.dw_led_pixel_order = request.pixel_order or "GRB"
  1136. state.dw_led_brightness = request.brightness or 35
  1137. state.wled_ip = None
  1138. # Create new LED controller with updated settings
  1139. state.led_controller = LEDInterface(
  1140. "dw_leds",
  1141. num_leds=state.dw_led_num_leds,
  1142. gpio_pin=state.dw_led_gpio_pin,
  1143. pixel_order=state.dw_led_pixel_order,
  1144. brightness=state.dw_led_brightness / 100.0,
  1145. speed=state.dw_led_speed,
  1146. intensity=state.dw_led_intensity
  1147. )
  1148. restart_msg = " (restarted)" if hardware_changed else ""
  1149. logger.info(f"DW LEDs configured{restart_msg}: {state.dw_led_num_leds} LEDs on GPIO{state.dw_led_gpio_pin}, pixel order: {state.dw_led_pixel_order}")
  1150. # Check if initialization succeeded by checking status
  1151. status = state.led_controller.check_status()
  1152. if not status.get("connected", False) and status.get("error"):
  1153. error_msg = status["error"]
  1154. logger.warning(f"DW LED initialization failed: {error_msg}, but configuration saved for testing")
  1155. state.led_controller = None
  1156. # Keep the provider setting for testing purposes
  1157. # state.led_provider remains "dw_leds" so settings can be saved/tested
  1158. # Save state even with error
  1159. state.save()
  1160. # Return success with warning instead of error
  1161. return {
  1162. "success": True,
  1163. "warning": error_msg,
  1164. "hardware_available": False,
  1165. "provider": state.led_provider,
  1166. "dw_led_num_leds": state.dw_led_num_leds,
  1167. "dw_led_gpio_pin": state.dw_led_gpio_pin,
  1168. "dw_led_pixel_order": state.dw_led_pixel_order,
  1169. "dw_led_brightness": state.dw_led_brightness
  1170. }
  1171. else: # none
  1172. state.wled_ip = None
  1173. state.led_controller = None
  1174. logger.info("LED provider disabled")
  1175. # Show idle effect if controller is configured
  1176. if state.led_controller:
  1177. state.led_controller.effect_idle()
  1178. _start_idle_led_timeout()
  1179. state.save()
  1180. return {
  1181. "success": True,
  1182. "provider": state.led_provider,
  1183. "wled_ip": state.wled_ip,
  1184. "dw_led_num_leds": state.dw_led_num_leds,
  1185. "dw_led_gpio_pin": state.dw_led_gpio_pin,
  1186. "dw_led_brightness": state.dw_led_brightness
  1187. }
  1188. @app.get("/get_led_config")
  1189. async def get_led_config():
  1190. """Get current LED provider configuration"""
  1191. # Auto-detect provider for backward compatibility with existing installations
  1192. provider = state.led_provider
  1193. if not provider or provider == "none":
  1194. # If no provider set but we have IPs configured, auto-detect
  1195. if state.wled_ip:
  1196. provider = "wled"
  1197. state.led_provider = "wled"
  1198. state.save()
  1199. logger.info("Auto-detected WLED provider from existing configuration")
  1200. else:
  1201. provider = "none"
  1202. return {
  1203. "success": True,
  1204. "provider": provider,
  1205. "wled_ip": state.wled_ip,
  1206. "dw_led_num_leds": state.dw_led_num_leds,
  1207. "dw_led_gpio_pin": state.dw_led_gpio_pin,
  1208. "dw_led_pixel_order": state.dw_led_pixel_order,
  1209. "dw_led_brightness": state.dw_led_brightness,
  1210. "dw_led_idle_effect": state.dw_led_idle_effect,
  1211. "dw_led_playing_effect": state.dw_led_playing_effect
  1212. }
  1213. @app.post("/skip_pattern")
  1214. async def skip_pattern():
  1215. if not state.current_playlist:
  1216. raise HTTPException(status_code=400, detail="No playlist is currently running")
  1217. state.skip_requested = True
  1218. return {"success": True}
  1219. @app.get("/api/custom_clear_patterns")
  1220. async def get_custom_clear_patterns():
  1221. """Get the currently configured custom clear patterns."""
  1222. return {
  1223. "success": True,
  1224. "custom_clear_from_in": state.custom_clear_from_in,
  1225. "custom_clear_from_out": state.custom_clear_from_out
  1226. }
  1227. @app.post("/api/custom_clear_patterns")
  1228. async def set_custom_clear_patterns(request: dict):
  1229. """Set custom clear patterns for clear_from_in and clear_from_out."""
  1230. try:
  1231. # Validate that the patterns exist if they're provided
  1232. if "custom_clear_from_in" in request and request["custom_clear_from_in"]:
  1233. pattern_path = os.path.join(pattern_manager.THETA_RHO_DIR, request["custom_clear_from_in"])
  1234. if not os.path.exists(pattern_path):
  1235. raise HTTPException(status_code=400, detail=f"Pattern file not found: {request['custom_clear_from_in']}")
  1236. state.custom_clear_from_in = request["custom_clear_from_in"]
  1237. elif "custom_clear_from_in" in request:
  1238. state.custom_clear_from_in = None
  1239. if "custom_clear_from_out" in request and request["custom_clear_from_out"]:
  1240. pattern_path = os.path.join(pattern_manager.THETA_RHO_DIR, request["custom_clear_from_out"])
  1241. if not os.path.exists(pattern_path):
  1242. raise HTTPException(status_code=400, detail=f"Pattern file not found: {request['custom_clear_from_out']}")
  1243. state.custom_clear_from_out = request["custom_clear_from_out"]
  1244. elif "custom_clear_from_out" in request:
  1245. state.custom_clear_from_out = None
  1246. state.save()
  1247. logger.info(f"Custom clear patterns updated - in: {state.custom_clear_from_in}, out: {state.custom_clear_from_out}")
  1248. return {
  1249. "success": True,
  1250. "custom_clear_from_in": state.custom_clear_from_in,
  1251. "custom_clear_from_out": state.custom_clear_from_out
  1252. }
  1253. except Exception as e:
  1254. logger.error(f"Failed to set custom clear patterns: {str(e)}")
  1255. raise HTTPException(status_code=500, detail=str(e))
  1256. @app.get("/api/clear_pattern_speed")
  1257. async def get_clear_pattern_speed():
  1258. """Get the current clearing pattern speed setting."""
  1259. return {
  1260. "success": True,
  1261. "clear_pattern_speed": state.clear_pattern_speed,
  1262. "effective_speed": state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  1263. }
  1264. @app.post("/api/clear_pattern_speed")
  1265. async def set_clear_pattern_speed(request: dict):
  1266. """Set the clearing pattern speed."""
  1267. try:
  1268. # If speed is None or "none", use default behavior (state.speed)
  1269. speed_value = request.get("clear_pattern_speed")
  1270. if speed_value is None or speed_value == "none" or speed_value == "":
  1271. speed = None
  1272. else:
  1273. speed = int(speed_value)
  1274. # Validate speed range (same as regular speed limits) only if speed is not None
  1275. if speed is not None and not (50 <= speed <= 2000):
  1276. raise HTTPException(status_code=400, detail="Speed must be between 50 and 2000")
  1277. state.clear_pattern_speed = speed
  1278. state.save()
  1279. logger.info(f"Clear pattern speed set to {speed if speed is not None else 'default (state.speed)'}")
  1280. return {
  1281. "success": True,
  1282. "clear_pattern_speed": state.clear_pattern_speed,
  1283. "effective_speed": state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  1284. }
  1285. except ValueError:
  1286. raise HTTPException(status_code=400, detail="Invalid speed value")
  1287. except Exception as e:
  1288. logger.error(f"Failed to set clear pattern speed: {str(e)}")
  1289. raise HTTPException(status_code=500, detail=str(e))
  1290. @app.get("/api/app-name")
  1291. async def get_app_name():
  1292. """Get current application name."""
  1293. return {"app_name": state.app_name}
  1294. @app.post("/api/app-name")
  1295. async def set_app_name(request: dict):
  1296. """Update application name."""
  1297. app_name = request.get("app_name", "").strip()
  1298. if not app_name:
  1299. app_name = "Dune Weaver" # Reset to default if empty
  1300. state.app_name = app_name
  1301. state.save()
  1302. logger.info(f"Application name updated to: {app_name}")
  1303. return {"success": True, "app_name": app_name}
  1304. @app.get("/api/mqtt-config")
  1305. async def get_mqtt_config():
  1306. """Get current MQTT configuration.
  1307. Note: Password is not returned for security reasons.
  1308. """
  1309. from modules.mqtt import get_mqtt_handler
  1310. handler = get_mqtt_handler()
  1311. return {
  1312. "enabled": state.mqtt_enabled,
  1313. "broker": state.mqtt_broker,
  1314. "port": state.mqtt_port,
  1315. "username": state.mqtt_username,
  1316. # Password is intentionally omitted for security
  1317. "has_password": bool(state.mqtt_password),
  1318. "client_id": state.mqtt_client_id,
  1319. "discovery_prefix": state.mqtt_discovery_prefix,
  1320. "device_id": state.mqtt_device_id,
  1321. "device_name": state.mqtt_device_name,
  1322. "connected": handler.is_connected if hasattr(handler, 'is_connected') else False,
  1323. "is_mock": handler.__class__.__name__ == 'MockMQTTHandler'
  1324. }
  1325. @app.post("/api/mqtt-config")
  1326. async def set_mqtt_config(request: dict):
  1327. """Update MQTT configuration. Requires restart to take effect."""
  1328. try:
  1329. # Update state with new values
  1330. state.mqtt_enabled = request.get("enabled", False)
  1331. state.mqtt_broker = request.get("broker", "").strip()
  1332. state.mqtt_port = int(request.get("port", 1883))
  1333. state.mqtt_username = request.get("username", "").strip()
  1334. state.mqtt_password = request.get("password", "").strip()
  1335. state.mqtt_client_id = request.get("client_id", "dune_weaver").strip()
  1336. state.mqtt_discovery_prefix = request.get("discovery_prefix", "homeassistant").strip()
  1337. state.mqtt_device_id = request.get("device_id", "dune_weaver").strip()
  1338. state.mqtt_device_name = request.get("device_name", "Dune Weaver").strip()
  1339. # Validate required fields when enabled
  1340. if state.mqtt_enabled and not state.mqtt_broker:
  1341. return JSONResponse(
  1342. content={"success": False, "message": "Broker address is required when MQTT is enabled"},
  1343. status_code=400
  1344. )
  1345. state.save()
  1346. logger.info(f"MQTT configuration updated. Enabled: {state.mqtt_enabled}, Broker: {state.mqtt_broker}")
  1347. return {
  1348. "success": True,
  1349. "message": "MQTT configuration saved. Restart the application for changes to take effect.",
  1350. "requires_restart": True
  1351. }
  1352. except ValueError as e:
  1353. return JSONResponse(
  1354. content={"success": False, "message": f"Invalid value: {str(e)}"},
  1355. status_code=400
  1356. )
  1357. except Exception as e:
  1358. logger.error(f"Failed to update MQTT config: {str(e)}")
  1359. return JSONResponse(
  1360. content={"success": False, "message": str(e)},
  1361. status_code=500
  1362. )
  1363. @app.post("/api/mqtt-test")
  1364. async def test_mqtt_connection(request: dict):
  1365. """Test MQTT connection with provided settings."""
  1366. import paho.mqtt.client as mqtt_client
  1367. broker = request.get("broker", "").strip()
  1368. port = int(request.get("port", 1883))
  1369. username = request.get("username", "").strip()
  1370. password = request.get("password", "").strip()
  1371. client_id = request.get("client_id", "dune_weaver_test").strip()
  1372. if not broker:
  1373. return JSONResponse(
  1374. content={"success": False, "message": "Broker address is required"},
  1375. status_code=400
  1376. )
  1377. try:
  1378. # Create a test client
  1379. client = mqtt_client.Client(client_id=client_id + "_test")
  1380. if username:
  1381. client.username_pw_set(username, password)
  1382. # Connection result
  1383. connection_result = {"connected": False, "error": None}
  1384. def on_connect(client, userdata, flags, rc):
  1385. if rc == 0:
  1386. connection_result["connected"] = True
  1387. else:
  1388. error_messages = {
  1389. 1: "Incorrect protocol version",
  1390. 2: "Invalid client identifier",
  1391. 3: "Server unavailable",
  1392. 4: "Bad username or password",
  1393. 5: "Not authorized"
  1394. }
  1395. connection_result["error"] = error_messages.get(rc, f"Connection failed with code {rc}")
  1396. client.on_connect = on_connect
  1397. # Try to connect with timeout
  1398. client.connect_async(broker, port, keepalive=10)
  1399. client.loop_start()
  1400. # Wait for connection result (max 5 seconds)
  1401. import time
  1402. start_time = time.time()
  1403. while time.time() - start_time < 5:
  1404. if connection_result["connected"] or connection_result["error"]:
  1405. break
  1406. await asyncio.sleep(0.1)
  1407. client.loop_stop()
  1408. client.disconnect()
  1409. if connection_result["connected"]:
  1410. return {"success": True, "message": "Successfully connected to MQTT broker"}
  1411. elif connection_result["error"]:
  1412. return JSONResponse(
  1413. content={"success": False, "message": connection_result["error"]},
  1414. status_code=400
  1415. )
  1416. else:
  1417. return JSONResponse(
  1418. content={"success": False, "message": "Connection timed out. Check broker address and port."},
  1419. status_code=400
  1420. )
  1421. except Exception as e:
  1422. logger.error(f"MQTT test connection failed: {str(e)}")
  1423. return JSONResponse(
  1424. content={"success": False, "message": str(e)},
  1425. status_code=500
  1426. )
  1427. @app.post("/preview_thr_batch")
  1428. async def preview_thr_batch(request: dict):
  1429. start = time.time()
  1430. if not request.get("file_names"):
  1431. logger.warning("Batch preview request received without filenames")
  1432. raise HTTPException(status_code=400, detail="No file names provided")
  1433. file_names = request["file_names"]
  1434. if not isinstance(file_names, list):
  1435. raise HTTPException(status_code=400, detail="file_names must be a list")
  1436. headers = {
  1437. "Cache-Control": "public, max-age=3600", # Cache for 1 hour
  1438. "Content-Type": "application/json"
  1439. }
  1440. async def process_single_file(file_name):
  1441. """Process a single file and return its preview data."""
  1442. t1 = time.time()
  1443. try:
  1444. # Normalize file path for cross-platform compatibility
  1445. normalized_file_name = normalize_file_path(file_name)
  1446. pattern_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  1447. # Check file existence asynchronously
  1448. exists = await asyncio.to_thread(os.path.exists, pattern_file_path)
  1449. if not exists:
  1450. logger.warning(f"Pattern file not found: {pattern_file_path}")
  1451. return file_name, {"error": "Pattern file not found"}
  1452. cache_path = get_cache_path(normalized_file_name)
  1453. # Check cache existence asynchronously
  1454. cache_exists = await asyncio.to_thread(os.path.exists, cache_path)
  1455. if not cache_exists:
  1456. logger.info(f"Cache miss for {file_name}. Generating preview...")
  1457. success = await generate_image_preview(normalized_file_name)
  1458. cache_exists_after = await asyncio.to_thread(os.path.exists, cache_path)
  1459. if not success or not cache_exists_after:
  1460. logger.error(f"Failed to generate or find preview for {file_name}")
  1461. return file_name, {"error": "Failed to generate preview"}
  1462. metadata = get_pattern_metadata(normalized_file_name)
  1463. if metadata:
  1464. first_coord_obj = metadata.get('first_coordinate')
  1465. last_coord_obj = metadata.get('last_coordinate')
  1466. else:
  1467. logger.debug(f"Metadata cache miss for {file_name}, parsing file")
  1468. # Use process pool for CPU-intensive parsing
  1469. loop = asyncio.get_event_loop()
  1470. coordinates = await loop.run_in_executor(process_pool, parse_theta_rho_file, pattern_file_path)
  1471. first_coord = coordinates[0] if coordinates else None
  1472. last_coord = coordinates[-1] if coordinates else None
  1473. first_coord_obj = {"x": first_coord[0], "y": first_coord[1]} if first_coord else None
  1474. last_coord_obj = {"x": last_coord[0], "y": last_coord[1]} if last_coord else None
  1475. # Read image file asynchronously
  1476. image_data = await asyncio.to_thread(lambda: open(cache_path, 'rb').read())
  1477. image_b64 = base64.b64encode(image_data).decode('utf-8')
  1478. result = {
  1479. "image_data": f"data:image/webp;base64,{image_b64}",
  1480. "first_coordinate": first_coord_obj,
  1481. "last_coordinate": last_coord_obj
  1482. }
  1483. logger.debug(f"Processed {file_name} in {time.time() - t1:.2f}s")
  1484. return file_name, result
  1485. except Exception as e:
  1486. logger.error(f"Error processing {file_name}: {str(e)}")
  1487. return file_name, {"error": str(e)}
  1488. # Process all files concurrently
  1489. tasks = [process_single_file(file_name) for file_name in file_names]
  1490. file_results = await asyncio.gather(*tasks)
  1491. # Convert results to dictionary
  1492. results = dict(file_results)
  1493. logger.info(f"Total batch processing time: {time.time() - start:.2f}s for {len(file_names)} files")
  1494. return JSONResponse(content=results, headers=headers)
  1495. @app.get("/playlists")
  1496. async def playlists(request: Request):
  1497. logger.debug("Rendering playlists page")
  1498. return templates.TemplateResponse("playlists.html", {"request": request, "app_name": state.app_name})
  1499. @app.get("/image2sand")
  1500. async def image2sand(request: Request):
  1501. return templates.TemplateResponse("image2sand.html", {"request": request, "app_name": state.app_name})
  1502. @app.get("/led")
  1503. async def led_control_page(request: Request):
  1504. return templates.TemplateResponse("led.html", {"request": request, "app_name": state.app_name})
  1505. # DW LED control endpoints
  1506. @app.get("/api/dw_leds/status")
  1507. async def dw_leds_status():
  1508. """Get DW LED controller status"""
  1509. if not state.led_controller or state.led_provider != "dw_leds":
  1510. return {"connected": False, "message": "DW LEDs not configured"}
  1511. try:
  1512. return state.led_controller.check_status()
  1513. except Exception as e:
  1514. logger.error(f"Failed to check DW LED status: {str(e)}")
  1515. return {"connected": False, "message": str(e)}
  1516. @app.post("/api/dw_leds/power")
  1517. async def dw_leds_power(request: dict):
  1518. """Control DW LED power (0=off, 1=on, 2=toggle)"""
  1519. if not state.led_controller or state.led_provider != "dw_leds":
  1520. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  1521. state_value = request.get("state", 1)
  1522. if state_value not in [0, 1, 2]:
  1523. raise HTTPException(status_code=400, detail="State must be 0 (off), 1 (on), or 2 (toggle)")
  1524. try:
  1525. result = state.led_controller.set_power(state_value)
  1526. # Reset idle timeout when LEDs are manually powered on (only if idle timeout is enabled)
  1527. # This prevents idle timeout from immediately turning them back off
  1528. if state_value in [1, 2] and state.dw_led_idle_timeout_enabled: # Power on or toggle
  1529. state.dw_led_last_activity_time = time.time()
  1530. logger.debug(f"LED activity time reset due to manual power on")
  1531. return result
  1532. except Exception as e:
  1533. logger.error(f"Failed to set DW LED power: {str(e)}")
  1534. raise HTTPException(status_code=500, detail=str(e))
  1535. @app.post("/api/dw_leds/brightness")
  1536. async def dw_leds_brightness(request: dict):
  1537. """Set DW LED brightness (0-100)"""
  1538. if not state.led_controller or state.led_provider != "dw_leds":
  1539. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  1540. value = request.get("value", 50)
  1541. if not 0 <= value <= 100:
  1542. raise HTTPException(status_code=400, detail="Brightness must be between 0 and 100")
  1543. try:
  1544. controller = state.led_controller.get_controller()
  1545. result = controller.set_brightness(value)
  1546. # Update state if successful
  1547. if result.get("connected"):
  1548. state.dw_led_brightness = value
  1549. state.save()
  1550. return result
  1551. except Exception as e:
  1552. logger.error(f"Failed to set DW LED brightness: {str(e)}")
  1553. raise HTTPException(status_code=500, detail=str(e))
  1554. @app.post("/api/dw_leds/color")
  1555. async def dw_leds_color(request: dict):
  1556. """Set solid color (manual UI control - always powers on LEDs)"""
  1557. if not state.led_controller or state.led_provider != "dw_leds":
  1558. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  1559. # Accept both formats: {"r": 255, "g": 0, "b": 0} or {"color": [255, 0, 0]}
  1560. if "color" in request:
  1561. color = request["color"]
  1562. if not isinstance(color, list) or len(color) != 3:
  1563. raise HTTPException(status_code=400, detail="Color must be [R, G, B] array")
  1564. r, g, b = color[0], color[1], color[2]
  1565. elif "r" in request and "g" in request and "b" in request:
  1566. r = request["r"]
  1567. g = request["g"]
  1568. b = request["b"]
  1569. else:
  1570. raise HTTPException(status_code=400, detail="Color must include r, g, b fields or color array")
  1571. try:
  1572. controller = state.led_controller.get_controller()
  1573. # Power on LEDs when user manually sets color via UI
  1574. controller.set_power(1)
  1575. # Reset idle timeout for manual interaction (only if idle timeout is enabled)
  1576. if state.dw_led_idle_timeout_enabled:
  1577. state.dw_led_last_activity_time = time.time()
  1578. return controller.set_color(r, g, b)
  1579. except Exception as e:
  1580. logger.error(f"Failed to set DW LED color: {str(e)}")
  1581. raise HTTPException(status_code=500, detail=str(e))
  1582. @app.post("/api/dw_leds/colors")
  1583. async def dw_leds_colors(request: dict):
  1584. """Set effect colors (color1, color2, color3) - manual UI control - always powers on LEDs"""
  1585. if not state.led_controller or state.led_provider != "dw_leds":
  1586. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  1587. # Parse colors from request
  1588. color1 = None
  1589. color2 = None
  1590. color3 = None
  1591. if "color1" in request:
  1592. c = request["color1"]
  1593. if isinstance(c, list) and len(c) == 3:
  1594. color1 = tuple(c)
  1595. else:
  1596. raise HTTPException(status_code=400, detail="color1 must be [R, G, B] array")
  1597. if "color2" in request:
  1598. c = request["color2"]
  1599. if isinstance(c, list) and len(c) == 3:
  1600. color2 = tuple(c)
  1601. else:
  1602. raise HTTPException(status_code=400, detail="color2 must be [R, G, B] array")
  1603. if "color3" in request:
  1604. c = request["color3"]
  1605. if isinstance(c, list) and len(c) == 3:
  1606. color3 = tuple(c)
  1607. else:
  1608. raise HTTPException(status_code=400, detail="color3 must be [R, G, B] array")
  1609. if not any([color1, color2, color3]):
  1610. raise HTTPException(status_code=400, detail="Must provide at least one color")
  1611. try:
  1612. controller = state.led_controller.get_controller()
  1613. # Power on LEDs when user manually sets colors via UI
  1614. controller.set_power(1)
  1615. # Reset idle timeout for manual interaction (only if idle timeout is enabled)
  1616. if state.dw_led_idle_timeout_enabled:
  1617. state.dw_led_last_activity_time = time.time()
  1618. return controller.set_colors(color1=color1, color2=color2, color3=color3)
  1619. except Exception as e:
  1620. logger.error(f"Failed to set DW LED colors: {str(e)}")
  1621. raise HTTPException(status_code=500, detail=str(e))
  1622. @app.get("/api/dw_leds/effects")
  1623. async def dw_leds_effects():
  1624. """Get list of available effects"""
  1625. if not state.led_controller or state.led_provider != "dw_leds":
  1626. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  1627. try:
  1628. controller = state.led_controller.get_controller()
  1629. effects = controller.get_effects()
  1630. # Convert tuples to lists for JSON serialization
  1631. effects_list = [[eid, name] for eid, name in effects]
  1632. return {
  1633. "success": True,
  1634. "effects": effects_list
  1635. }
  1636. except Exception as e:
  1637. logger.error(f"Failed to get DW LED effects: {str(e)}")
  1638. raise HTTPException(status_code=500, detail=str(e))
  1639. @app.get("/api/dw_leds/palettes")
  1640. async def dw_leds_palettes():
  1641. """Get list of available palettes"""
  1642. if not state.led_controller or state.led_provider != "dw_leds":
  1643. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  1644. try:
  1645. controller = state.led_controller.get_controller()
  1646. palettes = controller.get_palettes()
  1647. # Convert tuples to lists for JSON serialization
  1648. palettes_list = [[pid, name] for pid, name in palettes]
  1649. return {
  1650. "success": True,
  1651. "palettes": palettes_list
  1652. }
  1653. except Exception as e:
  1654. logger.error(f"Failed to get DW LED palettes: {str(e)}")
  1655. raise HTTPException(status_code=500, detail=str(e))
  1656. @app.post("/api/dw_leds/effect")
  1657. async def dw_leds_effect(request: dict):
  1658. """Set effect by ID (manual UI control - always powers on LEDs)"""
  1659. if not state.led_controller or state.led_provider != "dw_leds":
  1660. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  1661. effect_id = request.get("effect_id", 0)
  1662. speed = request.get("speed")
  1663. intensity = request.get("intensity")
  1664. try:
  1665. controller = state.led_controller.get_controller()
  1666. # Power on LEDs when user manually sets effect via UI
  1667. controller.set_power(1)
  1668. # Reset idle timeout for manual interaction (only if idle timeout is enabled)
  1669. if state.dw_led_idle_timeout_enabled:
  1670. state.dw_led_last_activity_time = time.time()
  1671. return controller.set_effect(effect_id, speed=speed, intensity=intensity)
  1672. except Exception as e:
  1673. logger.error(f"Failed to set DW LED effect: {str(e)}")
  1674. raise HTTPException(status_code=500, detail=str(e))
  1675. @app.post("/api/dw_leds/palette")
  1676. async def dw_leds_palette(request: dict):
  1677. """Set palette by ID (manual UI control - always powers on LEDs)"""
  1678. if not state.led_controller or state.led_provider != "dw_leds":
  1679. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  1680. palette_id = request.get("palette_id", 0)
  1681. try:
  1682. controller = state.led_controller.get_controller()
  1683. # Power on LEDs when user manually sets palette via UI
  1684. controller.set_power(1)
  1685. # Reset idle timeout for manual interaction (only if idle timeout is enabled)
  1686. if state.dw_led_idle_timeout_enabled:
  1687. state.dw_led_last_activity_time = time.time()
  1688. return controller.set_palette(palette_id)
  1689. except Exception as e:
  1690. logger.error(f"Failed to set DW LED palette: {str(e)}")
  1691. raise HTTPException(status_code=500, detail=str(e))
  1692. @app.post("/api/dw_leds/speed")
  1693. async def dw_leds_speed(request: dict):
  1694. """Set effect speed (0-255)"""
  1695. if not state.led_controller or state.led_provider != "dw_leds":
  1696. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  1697. value = request.get("speed", 128)
  1698. if not 0 <= value <= 255:
  1699. raise HTTPException(status_code=400, detail="Speed must be between 0 and 255")
  1700. try:
  1701. controller = state.led_controller.get_controller()
  1702. result = controller.set_speed(value)
  1703. # Save speed to state
  1704. state.dw_led_speed = value
  1705. state.save()
  1706. return result
  1707. except Exception as e:
  1708. logger.error(f"Failed to set DW LED speed: {str(e)}")
  1709. raise HTTPException(status_code=500, detail=str(e))
  1710. @app.post("/api/dw_leds/intensity")
  1711. async def dw_leds_intensity(request: dict):
  1712. """Set effect intensity (0-255)"""
  1713. if not state.led_controller or state.led_provider != "dw_leds":
  1714. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  1715. value = request.get("intensity", 128)
  1716. if not 0 <= value <= 255:
  1717. raise HTTPException(status_code=400, detail="Intensity must be between 0 and 255")
  1718. try:
  1719. controller = state.led_controller.get_controller()
  1720. result = controller.set_intensity(value)
  1721. # Save intensity to state
  1722. state.dw_led_intensity = value
  1723. state.save()
  1724. return result
  1725. except Exception as e:
  1726. logger.error(f"Failed to set DW LED intensity: {str(e)}")
  1727. raise HTTPException(status_code=500, detail=str(e))
  1728. @app.post("/api/dw_leds/save_effect_settings")
  1729. async def dw_leds_save_effect_settings(request: dict):
  1730. """Save current LED settings as idle or playing effect"""
  1731. effect_type = request.get("type") # 'idle' or 'playing'
  1732. settings = {
  1733. "effect_id": request.get("effect_id"),
  1734. "palette_id": request.get("palette_id"),
  1735. "speed": request.get("speed"),
  1736. "intensity": request.get("intensity"),
  1737. "color1": request.get("color1"),
  1738. "color2": request.get("color2"),
  1739. "color3": request.get("color3")
  1740. }
  1741. if effect_type == "idle":
  1742. state.dw_led_idle_effect = settings
  1743. elif effect_type == "playing":
  1744. state.dw_led_playing_effect = settings
  1745. else:
  1746. raise HTTPException(status_code=400, detail="Invalid effect type. Must be 'idle' or 'playing'")
  1747. state.save()
  1748. logger.info(f"DW LED {effect_type} effect settings saved: {settings}")
  1749. return {"success": True, "type": effect_type, "settings": settings}
  1750. @app.post("/api/dw_leds/clear_effect_settings")
  1751. async def dw_leds_clear_effect_settings(request: dict):
  1752. """Clear idle or playing effect settings"""
  1753. effect_type = request.get("type") # 'idle' or 'playing'
  1754. if effect_type == "idle":
  1755. state.dw_led_idle_effect = None
  1756. elif effect_type == "playing":
  1757. state.dw_led_playing_effect = None
  1758. else:
  1759. raise HTTPException(status_code=400, detail="Invalid effect type. Must be 'idle' or 'playing'")
  1760. state.save()
  1761. logger.info(f"DW LED {effect_type} effect settings cleared")
  1762. return {"success": True, "type": effect_type}
  1763. @app.get("/api/dw_leds/get_effect_settings")
  1764. async def dw_leds_get_effect_settings():
  1765. """Get saved idle and playing effect settings"""
  1766. return {
  1767. "idle_effect": state.dw_led_idle_effect,
  1768. "playing_effect": state.dw_led_playing_effect
  1769. }
  1770. @app.post("/api/dw_leds/idle_timeout")
  1771. async def dw_leds_set_idle_timeout(request: dict):
  1772. """Configure LED idle timeout settings"""
  1773. enabled = request.get("enabled", False)
  1774. minutes = request.get("minutes", 30)
  1775. # Validate minutes (between 1 and 1440 - 24 hours)
  1776. if minutes < 1 or minutes > 1440:
  1777. raise HTTPException(status_code=400, detail="Timeout must be between 1 and 1440 minutes")
  1778. state.dw_led_idle_timeout_enabled = enabled
  1779. state.dw_led_idle_timeout_minutes = minutes
  1780. # Reset activity time when settings change
  1781. import time
  1782. state.dw_led_last_activity_time = time.time()
  1783. state.save()
  1784. logger.info(f"DW LED idle timeout configured: enabled={enabled}, minutes={minutes}")
  1785. return {
  1786. "success": True,
  1787. "enabled": enabled,
  1788. "minutes": minutes
  1789. }
  1790. @app.get("/api/dw_leds/idle_timeout")
  1791. async def dw_leds_get_idle_timeout():
  1792. """Get LED idle timeout settings"""
  1793. import time
  1794. # Calculate remaining time if timeout is active
  1795. remaining_minutes = None
  1796. if state.dw_led_idle_timeout_enabled and state.dw_led_last_activity_time:
  1797. elapsed_seconds = time.time() - state.dw_led_last_activity_time
  1798. timeout_seconds = state.dw_led_idle_timeout_minutes * 60
  1799. remaining_seconds = max(0, timeout_seconds - elapsed_seconds)
  1800. remaining_minutes = round(remaining_seconds / 60, 1)
  1801. return {
  1802. "enabled": state.dw_led_idle_timeout_enabled,
  1803. "minutes": state.dw_led_idle_timeout_minutes,
  1804. "remaining_minutes": remaining_minutes
  1805. }
  1806. @app.get("/table_control")
  1807. async def table_control(request: Request):
  1808. return templates.TemplateResponse("table_control.html", {"request": request, "app_name": state.app_name})
  1809. @app.get("/cache-progress")
  1810. async def get_cache_progress_endpoint():
  1811. """Get the current cache generation progress."""
  1812. from modules.core.cache_manager import get_cache_progress
  1813. return get_cache_progress()
  1814. @app.post("/rebuild_cache")
  1815. async def rebuild_cache_endpoint():
  1816. """Trigger a rebuild of the pattern cache."""
  1817. try:
  1818. from modules.core.cache_manager import rebuild_cache
  1819. await rebuild_cache()
  1820. return {"success": True, "message": "Cache rebuild completed successfully"}
  1821. except Exception as e:
  1822. logger.error(f"Failed to rebuild cache: {str(e)}")
  1823. raise HTTPException(status_code=500, detail=str(e))
  1824. def signal_handler(signum, frame):
  1825. """Handle shutdown signals gracefully but forcefully."""
  1826. logger.info("Received shutdown signal, cleaning up...")
  1827. try:
  1828. # Turn off all LEDs on shutdown
  1829. if state.led_controller:
  1830. state.led_controller.set_power(0)
  1831. # Run cleanup operations - need to handle async in sync context
  1832. try:
  1833. # Try to run in existing loop if available
  1834. import asyncio
  1835. loop = asyncio.get_running_loop()
  1836. # If we're in an event loop, schedule the coroutine
  1837. import concurrent.futures
  1838. with concurrent.futures.ThreadPoolExecutor() as executor:
  1839. future = executor.submit(asyncio.run, pattern_manager.stop_actions())
  1840. future.result(timeout=5.0) # Wait up to 5 seconds
  1841. except RuntimeError:
  1842. # No running loop, create a new one
  1843. import asyncio
  1844. asyncio.run(pattern_manager.stop_actions())
  1845. except Exception as cleanup_err:
  1846. logger.error(f"Error in async cleanup: {cleanup_err}")
  1847. state.save()
  1848. logger.info("Cleanup completed")
  1849. except Exception as e:
  1850. logger.error(f"Error during cleanup: {str(e)}")
  1851. finally:
  1852. logger.info("Exiting application...")
  1853. os._exit(0) # Force exit regardless of other threads
  1854. @app.get("/api/version")
  1855. async def get_version_info(force_refresh: bool = False):
  1856. """Get current and latest version information
  1857. Args:
  1858. force_refresh: If true, bypass cache and fetch fresh data from GitHub
  1859. """
  1860. try:
  1861. version_info = await version_manager.get_version_info(force_refresh=force_refresh)
  1862. return JSONResponse(content=version_info)
  1863. except Exception as e:
  1864. logger.error(f"Error getting version info: {e}")
  1865. return JSONResponse(
  1866. content={
  1867. "current": await version_manager.get_current_version(),
  1868. "latest": await version_manager.get_current_version(),
  1869. "update_available": False,
  1870. "error": "Unable to check for updates"
  1871. },
  1872. status_code=200
  1873. )
  1874. @app.post("/api/update")
  1875. async def trigger_update():
  1876. """Trigger software update (placeholder for future implementation)"""
  1877. try:
  1878. # For now, just return the GitHub release URL
  1879. version_info = await version_manager.get_version_info()
  1880. if version_info.get("latest_release"):
  1881. return JSONResponse(content={
  1882. "success": False,
  1883. "message": "Automatic updates not implemented yet",
  1884. "manual_update_url": version_info["latest_release"].get("html_url"),
  1885. "instructions": "Please visit the GitHub release page to download and install the update manually"
  1886. })
  1887. else:
  1888. return JSONResponse(content={
  1889. "success": False,
  1890. "message": "No updates available"
  1891. })
  1892. except Exception as e:
  1893. logger.error(f"Error triggering update: {e}")
  1894. return JSONResponse(
  1895. content={"success": False, "message": "Failed to check for updates"},
  1896. status_code=500
  1897. )
  1898. @app.post("/api/system/shutdown")
  1899. async def shutdown_system():
  1900. """Shutdown the system"""
  1901. try:
  1902. logger.warning("Shutdown initiated via API")
  1903. # Schedule shutdown command after a short delay to allow response to be sent
  1904. def delayed_shutdown():
  1905. time.sleep(2) # Give time for response to be sent
  1906. try:
  1907. # Use systemctl to shutdown the host (via mounted systemd socket)
  1908. subprocess.run(["systemctl", "poweroff"], check=True)
  1909. logger.info("Host shutdown command executed successfully via systemctl")
  1910. except FileNotFoundError:
  1911. logger.error("systemctl command not found - ensure systemd volumes are mounted")
  1912. except Exception as e:
  1913. logger.error(f"Error executing host shutdown command: {e}")
  1914. import threading
  1915. shutdown_thread = threading.Thread(target=delayed_shutdown)
  1916. shutdown_thread.start()
  1917. return {"success": True, "message": "System shutdown initiated"}
  1918. except Exception as e:
  1919. logger.error(f"Error initiating shutdown: {e}")
  1920. return JSONResponse(
  1921. content={"success": False, "message": str(e)},
  1922. status_code=500
  1923. )
  1924. @app.post("/api/system/restart")
  1925. async def restart_system():
  1926. """Restart the Docker containers using docker compose"""
  1927. try:
  1928. logger.warning("Restart initiated via API")
  1929. # Schedule restart command after a short delay to allow response to be sent
  1930. def delayed_restart():
  1931. time.sleep(2) # Give time for response to be sent
  1932. try:
  1933. # Use docker compose restart to restart the containers
  1934. subprocess.run(["docker", "compose", "restart"], check=True)
  1935. logger.info("Docker compose restart command executed successfully")
  1936. except FileNotFoundError:
  1937. logger.error("docker command not found")
  1938. except Exception as e:
  1939. logger.error(f"Error executing docker compose restart: {e}")
  1940. import threading
  1941. restart_thread = threading.Thread(target=delayed_restart)
  1942. restart_thread.start()
  1943. return {"success": True, "message": "System restart initiated"}
  1944. except Exception as e:
  1945. logger.error(f"Error initiating restart: {e}")
  1946. return JSONResponse(
  1947. content={"success": False, "message": str(e)},
  1948. status_code=500
  1949. )
  1950. def entrypoint():
  1951. import uvicorn
  1952. logger.info("Starting FastAPI server on port 8080...")
  1953. uvicorn.run(app, host="0.0.0.0", port=8080, workers=1) # Set workers to 1 to avoid multiple signal handlers
  1954. if __name__ == "__main__":
  1955. entrypoint()