main.py 165 KB

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