1
0

main.py 119 KB

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