main.py 93 KB

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