1
0

main.py 117 KB

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