main.py 152 KB

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