main.py 160 KB

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