main.py 160 KB

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