main.py 143 KB

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