main.py 163 KB

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