1
0

main.py 121 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929
  1. from fastapi import FastAPI, UploadFile, File, HTTPException, BackgroundTasks, WebSocket, WebSocketDisconnect, Request
  2. from fastapi.responses import JSONResponse, FileResponse, Response
  3. from fastapi.staticfiles import StaticFiles
  4. from fastapi.templating import Jinja2Templates
  5. from pydantic import BaseModel
  6. from typing import List, Optional, Tuple, Dict, Any, Union
  7. import atexit
  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. from modules.core import process_pool as pool_module
  36. # Get log level from environment variable, default to INFO
  37. log_level_str = os.getenv('LOG_LEVEL', 'INFO').upper()
  38. log_level = getattr(logging, log_level_str, logging.INFO)
  39. logging.basicConfig(
  40. level=log_level,
  41. format='%(asctime)s - %(name)s:%(lineno)d - %(levelname)s - %(message)s',
  42. handlers=[
  43. logging.StreamHandler(),
  44. ]
  45. )
  46. # Initialize memory log handler for web UI log viewer
  47. init_memory_handler(max_entries=500)
  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 normalize_file_path(file_path: str) -> str:
  63. """Normalize file path separators for consistent cross-platform handling."""
  64. if not file_path:
  65. return ''
  66. # First normalize path separators
  67. normalized = file_path.replace('\\', '/')
  68. # Remove only the patterns directory prefix from the beginning, not patterns within the path
  69. if normalized.startswith('./patterns/'):
  70. normalized = normalized[11:]
  71. elif normalized.startswith('patterns/'):
  72. normalized = normalized[9:]
  73. return normalized
  74. @asynccontextmanager
  75. async def lifespan(app: FastAPI):
  76. # Startup
  77. logger.info("Starting Dune Weaver application...")
  78. # Register signal handlers
  79. signal.signal(signal.SIGINT, signal_handler)
  80. signal.signal(signal.SIGTERM, signal_handler)
  81. # Initialize shared process pool for CPU-intensive tasks
  82. pool_module.init_pool()
  83. # Pin main process to CPUs 1-N to keep CPU 0 dedicated to motion/LED
  84. from modules.core import scheduling
  85. background_cpus = scheduling.get_background_cpus()
  86. if background_cpus:
  87. scheduling.pin_to_cpus(background_cpus)
  88. logger.info(f"FastAPI main process pinned to CPUs {sorted(background_cpus)}")
  89. else:
  90. logger.info("Single-core system detected, skipping CPU pinning")
  91. try:
  92. connection_manager.connect_device()
  93. except Exception as e:
  94. logger.warning(f"Failed to auto-connect to serial port: {str(e)}")
  95. # Initialize LED controller based on saved configuration
  96. try:
  97. # Auto-detect provider for backward compatibility with existing installations
  98. if not state.led_provider or state.led_provider == "none":
  99. if state.wled_ip:
  100. state.led_provider = "wled"
  101. logger.info("Auto-detected WLED provider from existing configuration")
  102. # Initialize the appropriate controller
  103. if state.led_provider == "wled" and state.wled_ip:
  104. state.led_controller = LEDInterface("wled", state.wled_ip)
  105. logger.info(f"LED controller initialized: WLED at {state.wled_ip}")
  106. elif state.led_provider == "dw_leds":
  107. state.led_controller = LEDInterface(
  108. "dw_leds",
  109. num_leds=state.dw_led_num_leds,
  110. gpio_pin=state.dw_led_gpio_pin,
  111. pixel_order=state.dw_led_pixel_order,
  112. brightness=state.dw_led_brightness / 100.0,
  113. speed=state.dw_led_speed,
  114. intensity=state.dw_led_intensity
  115. )
  116. 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})")
  117. else:
  118. state.led_controller = None
  119. logger.info("LED controller not configured")
  120. # Save if provider was auto-detected
  121. if state.led_provider and state.wled_ip:
  122. state.save()
  123. except Exception as e:
  124. logger.warning(f"Failed to initialize LED controller: {str(e)}")
  125. state.led_controller = None
  126. # Check if auto_play mode is enabled and auto-play playlist (right after connection attempt)
  127. if state.auto_play_enabled and state.auto_play_playlist:
  128. logger.info(f"auto_play mode enabled, checking for connection before auto-playing playlist: {state.auto_play_playlist}")
  129. try:
  130. # Check if we have a valid connection before starting playlist
  131. if state.conn and hasattr(state.conn, 'is_connected') and state.conn.is_connected():
  132. logger.info(f"Connection available, starting auto-play playlist: {state.auto_play_playlist} with options: run_mode={state.auto_play_run_mode}, pause_time={state.auto_play_pause_time}, clear_pattern={state.auto_play_clear_pattern}, shuffle={state.auto_play_shuffle}")
  133. asyncio.create_task(playlist_manager.run_playlist(
  134. state.auto_play_playlist,
  135. pause_time=state.auto_play_pause_time,
  136. clear_pattern=state.auto_play_clear_pattern,
  137. run_mode=state.auto_play_run_mode,
  138. shuffle=state.auto_play_shuffle
  139. ))
  140. else:
  141. logger.warning("No hardware connection available, skipping auto_play mode auto-play")
  142. except Exception as e:
  143. logger.error(f"Failed to auto-play auto_play playlist: {str(e)}")
  144. try:
  145. mqtt_handler = mqtt.init_mqtt()
  146. except Exception as e:
  147. logger.warning(f"Failed to initialize MQTT: {str(e)}")
  148. # Schedule cache generation check for later (non-blocking startup)
  149. async def delayed_cache_check():
  150. """Check and generate cache in background."""
  151. try:
  152. logger.info("Starting cache check...")
  153. from modules.core.cache_manager import is_cache_generation_needed_async, generate_cache_background
  154. if await is_cache_generation_needed_async():
  155. logger.info("Cache generation needed, starting background task...")
  156. asyncio.create_task(generate_cache_background()) # Don't await - run in background
  157. else:
  158. logger.info("Cache is up to date, skipping generation")
  159. except Exception as e:
  160. logger.warning(f"Failed during cache generation: {str(e)}")
  161. # Start cache check in background immediately
  162. asyncio.create_task(delayed_cache_check())
  163. # Start idle timeout monitor
  164. async def idle_timeout_monitor():
  165. """Monitor LED idle timeout and turn off LEDs when timeout expires."""
  166. import time
  167. while True:
  168. try:
  169. await asyncio.sleep(30) # Check every 30 seconds
  170. if not state.dw_led_idle_timeout_enabled:
  171. continue
  172. if not state.led_controller or not state.led_controller.is_configured:
  173. continue
  174. # Check if we're currently playing a pattern
  175. is_playing = bool(state.current_playing_file or state.current_playlist)
  176. if is_playing:
  177. # Reset activity time when playing
  178. state.dw_led_last_activity_time = time.time()
  179. continue
  180. # If no activity time set, initialize it
  181. if state.dw_led_last_activity_time is None:
  182. state.dw_led_last_activity_time = time.time()
  183. continue
  184. # Calculate idle duration
  185. idle_seconds = time.time() - state.dw_led_last_activity_time
  186. timeout_seconds = state.dw_led_idle_timeout_minutes * 60
  187. # Turn off LEDs if timeout expired
  188. if idle_seconds >= timeout_seconds:
  189. status = state.led_controller.check_status()
  190. # Check both "power" (WLED) and "power_on" (DW LEDs) keys
  191. is_powered_on = status.get("power", False) or status.get("power_on", False)
  192. if is_powered_on: # Only turn off if currently on
  193. logger.info(f"Idle timeout ({state.dw_led_idle_timeout_minutes} minutes) expired, turning off LEDs")
  194. state.led_controller.set_power(0)
  195. # Reset activity time to prevent repeated turn-off attempts
  196. state.dw_led_last_activity_time = time.time()
  197. except Exception as e:
  198. logger.error(f"Error in idle timeout monitor: {e}")
  199. await asyncio.sleep(60) # Wait longer on error
  200. asyncio.create_task(idle_timeout_monitor())
  201. yield # This separates startup from shutdown code
  202. # Shutdown
  203. logger.info("Shutting down Dune Weaver application...")
  204. # Shutdown process pool
  205. pool_module.shutdown_pool(wait=True)
  206. app = FastAPI(lifespan=lifespan)
  207. templates = Jinja2Templates(directory="templates")
  208. app.mount("/static", StaticFiles(directory="static"), name="static")
  209. # Global semaphore to limit concurrent preview processing
  210. # Prevents resource exhaustion when loading many previews simultaneously
  211. preview_semaphore = asyncio.Semaphore(5)
  212. # Pydantic models for request/response validation
  213. class ConnectRequest(BaseModel):
  214. port: Optional[str] = None
  215. class auto_playModeRequest(BaseModel):
  216. enabled: bool
  217. playlist: Optional[str] = None
  218. run_mode: Optional[str] = "loop"
  219. pause_time: Optional[float] = 5.0
  220. clear_pattern: Optional[str] = "adaptive"
  221. shuffle: Optional[bool] = False
  222. class TimeSlot(BaseModel):
  223. start_time: str # HH:MM format
  224. end_time: str # HH:MM format
  225. days: str # "daily", "weekdays", "weekends", or "custom"
  226. custom_days: Optional[List[str]] = [] # ["monday", "tuesday", etc.]
  227. class ScheduledPauseRequest(BaseModel):
  228. enabled: bool
  229. control_wled: Optional[bool] = False
  230. finish_pattern: Optional[bool] = False # Finish current pattern before pausing
  231. timezone: Optional[str] = None # IANA timezone or None for system default
  232. time_slots: List[TimeSlot] = []
  233. class CoordinateRequest(BaseModel):
  234. theta: float
  235. rho: float
  236. class PlaylistRequest(BaseModel):
  237. playlist_name: str
  238. files: List[str] = []
  239. pause_time: float = 0
  240. clear_pattern: Optional[str] = None
  241. run_mode: str = "single"
  242. shuffle: bool = False
  243. class PlaylistRunRequest(BaseModel):
  244. playlist_name: str
  245. pause_time: Optional[float] = 0
  246. clear_pattern: Optional[str] = None
  247. run_mode: Optional[str] = "single"
  248. shuffle: Optional[bool] = False
  249. start_time: Optional[str] = None
  250. end_time: Optional[str] = None
  251. class SpeedRequest(BaseModel):
  252. speed: float
  253. class WLEDRequest(BaseModel):
  254. wled_ip: Optional[str] = None
  255. class LEDConfigRequest(BaseModel):
  256. provider: str # "wled", "dw_leds", or "none"
  257. ip_address: Optional[str] = None # For WLED only
  258. # DW LED specific fields
  259. num_leds: Optional[int] = None
  260. gpio_pin: Optional[int] = None
  261. pixel_order: Optional[str] = None
  262. brightness: Optional[int] = None
  263. class DeletePlaylistRequest(BaseModel):
  264. playlist_name: str
  265. class RenamePlaylistRequest(BaseModel):
  266. old_name: str
  267. new_name: str
  268. class ThetaRhoRequest(BaseModel):
  269. file_name: str
  270. pre_execution: Optional[str] = "none"
  271. class GetCoordinatesRequest(BaseModel):
  272. file_name: str
  273. # ============================================================================
  274. # Unified Settings Models
  275. # ============================================================================
  276. class AppSettingsUpdate(BaseModel):
  277. name: Optional[str] = None
  278. custom_logo: Optional[str] = None # Filename or empty string to clear (favicon auto-generated)
  279. class ConnectionSettingsUpdate(BaseModel):
  280. preferred_port: Optional[str] = None
  281. class PatternSettingsUpdate(BaseModel):
  282. clear_pattern_speed: Optional[int] = None
  283. custom_clear_from_in: Optional[str] = None
  284. custom_clear_from_out: Optional[str] = None
  285. class AutoPlaySettingsUpdate(BaseModel):
  286. enabled: Optional[bool] = None
  287. playlist: Optional[str] = None
  288. run_mode: Optional[str] = None
  289. pause_time: Optional[float] = None
  290. clear_pattern: Optional[str] = None
  291. shuffle: Optional[bool] = None
  292. class ScheduledPauseSettingsUpdate(BaseModel):
  293. enabled: Optional[bool] = None
  294. control_wled: Optional[bool] = None
  295. finish_pattern: Optional[bool] = None
  296. timezone: Optional[str] = None # IANA timezone (e.g., "America/New_York") or None for system default
  297. time_slots: Optional[List[TimeSlot]] = None
  298. class HomingSettingsUpdate(BaseModel):
  299. mode: Optional[int] = None
  300. angular_offset_degrees: Optional[float] = None
  301. auto_home_enabled: Optional[bool] = None
  302. auto_home_after_patterns: Optional[int] = None
  303. class DwLedSettingsUpdate(BaseModel):
  304. num_leds: Optional[int] = None
  305. gpio_pin: Optional[int] = None
  306. pixel_order: Optional[str] = None
  307. brightness: Optional[int] = None
  308. speed: Optional[int] = None
  309. intensity: Optional[int] = None
  310. idle_effect: Optional[dict] = None
  311. playing_effect: Optional[dict] = None
  312. idle_timeout_enabled: Optional[bool] = None
  313. idle_timeout_minutes: Optional[int] = None
  314. class LedSettingsUpdate(BaseModel):
  315. provider: Optional[str] = None # "none", "wled", "dw_leds"
  316. wled_ip: Optional[str] = None
  317. dw_led: Optional[DwLedSettingsUpdate] = None
  318. class MqttSettingsUpdate(BaseModel):
  319. enabled: Optional[bool] = None
  320. broker: Optional[str] = None
  321. port: Optional[int] = None
  322. username: Optional[str] = None
  323. password: Optional[str] = None # Write-only, never returned in GET
  324. client_id: Optional[str] = None
  325. discovery_prefix: Optional[str] = None
  326. device_id: Optional[str] = None
  327. device_name: Optional[str] = None
  328. class MachineSettingsUpdate(BaseModel):
  329. table_type_override: Optional[str] = None # Override detected table type, or empty string/"auto" to clear
  330. class SettingsUpdate(BaseModel):
  331. """Request model for PATCH /api/settings - all fields optional for partial updates"""
  332. app: Optional[AppSettingsUpdate] = None
  333. connection: Optional[ConnectionSettingsUpdate] = None
  334. patterns: Optional[PatternSettingsUpdate] = None
  335. auto_play: Optional[AutoPlaySettingsUpdate] = None
  336. scheduled_pause: Optional[ScheduledPauseSettingsUpdate] = None
  337. homing: Optional[HomingSettingsUpdate] = None
  338. led: Optional[LedSettingsUpdate] = None
  339. mqtt: Optional[MqttSettingsUpdate] = None
  340. machine: Optional[MachineSettingsUpdate] = None
  341. # Store active WebSocket connections
  342. active_status_connections = set()
  343. active_cache_progress_connections = set()
  344. @app.websocket("/ws/status")
  345. async def websocket_status_endpoint(websocket: WebSocket):
  346. await websocket.accept()
  347. active_status_connections.add(websocket)
  348. try:
  349. while True:
  350. status = pattern_manager.get_status()
  351. try:
  352. await websocket.send_json({
  353. "type": "status_update",
  354. "data": status
  355. })
  356. except RuntimeError as e:
  357. if "close message has been sent" in str(e):
  358. break
  359. raise
  360. await asyncio.sleep(1)
  361. except WebSocketDisconnect:
  362. pass
  363. finally:
  364. active_status_connections.discard(websocket)
  365. try:
  366. await websocket.close()
  367. except RuntimeError:
  368. pass
  369. async def broadcast_status_update(status: dict):
  370. """Broadcast status update to all connected clients."""
  371. disconnected = set()
  372. for websocket in active_status_connections:
  373. try:
  374. await websocket.send_json({
  375. "type": "status_update",
  376. "data": status
  377. })
  378. except WebSocketDisconnect:
  379. disconnected.add(websocket)
  380. except RuntimeError:
  381. disconnected.add(websocket)
  382. active_status_connections.difference_update(disconnected)
  383. async def broadcast_patterns_updated(pattern_file: str = None):
  384. """Broadcast pattern update notification to all connected clients.
  385. This notifies touchscreen and other clients that patterns have changed,
  386. so they can refresh their pattern lists.
  387. Args:
  388. pattern_file: Optional specific pattern that was added/updated
  389. """
  390. disconnected = set()
  391. message = {
  392. "type": "patterns_updated",
  393. "data": {
  394. "pattern_file": pattern_file
  395. }
  396. }
  397. for websocket in active_status_connections:
  398. try:
  399. await websocket.send_json(message)
  400. except WebSocketDisconnect:
  401. disconnected.add(websocket)
  402. except RuntimeError:
  403. disconnected.add(websocket)
  404. active_status_connections.difference_update(disconnected)
  405. logger.info(f"Broadcast patterns_updated notification for: {pattern_file}")
  406. @app.websocket("/ws/cache-progress")
  407. async def websocket_cache_progress_endpoint(websocket: WebSocket):
  408. from modules.core.cache_manager import get_cache_progress
  409. await websocket.accept()
  410. active_cache_progress_connections.add(websocket)
  411. try:
  412. while True:
  413. progress = get_cache_progress()
  414. try:
  415. await websocket.send_json({
  416. "type": "cache_progress",
  417. "data": progress
  418. })
  419. except RuntimeError as e:
  420. if "close message has been sent" in str(e):
  421. break
  422. raise
  423. await asyncio.sleep(1.0) # Update every 1 second (reduced frequency for better performance)
  424. except WebSocketDisconnect:
  425. pass
  426. finally:
  427. active_cache_progress_connections.discard(websocket)
  428. try:
  429. await websocket.close()
  430. except RuntimeError:
  431. pass
  432. # WebSocket endpoint for real-time log streaming
  433. @app.websocket("/ws/logs")
  434. async def websocket_logs_endpoint(websocket: WebSocket):
  435. """Stream application logs in real-time via WebSocket."""
  436. await websocket.accept()
  437. handler = get_memory_handler()
  438. if not handler:
  439. await websocket.close()
  440. return
  441. # Subscribe to log updates
  442. log_queue = handler.subscribe()
  443. try:
  444. while True:
  445. try:
  446. # Wait for new log entry with timeout
  447. log_entry = await asyncio.wait_for(log_queue.get(), timeout=30.0)
  448. await websocket.send_json({
  449. "type": "log_entry",
  450. "data": log_entry
  451. })
  452. except asyncio.TimeoutError:
  453. # Send heartbeat to keep connection alive
  454. await websocket.send_json({"type": "heartbeat"})
  455. except RuntimeError as e:
  456. if "close message has been sent" in str(e):
  457. break
  458. raise
  459. except WebSocketDisconnect:
  460. pass
  461. finally:
  462. handler.unsubscribe(log_queue)
  463. try:
  464. await websocket.close()
  465. except RuntimeError:
  466. pass
  467. # API endpoint to retrieve logs
  468. @app.get("/api/logs", tags=["logs"])
  469. async def get_logs(limit: int = 100, level: str = None):
  470. """
  471. Retrieve application logs from memory buffer.
  472. Args:
  473. limit: Maximum number of log entries to return (default: 100, max: 500)
  474. level: Filter by log level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
  475. Returns:
  476. List of log entries with timestamp, level, logger, and message.
  477. """
  478. handler = get_memory_handler()
  479. if not handler:
  480. return {"logs": [], "error": "Log handler not initialized"}
  481. # Clamp limit to reasonable range
  482. limit = max(1, min(limit, 500))
  483. logs = handler.get_logs(limit=limit, level=level)
  484. return {"logs": logs, "count": len(logs)}
  485. @app.delete("/api/logs", tags=["logs"])
  486. async def clear_logs():
  487. """Clear all logs from the memory buffer."""
  488. handler = get_memory_handler()
  489. if handler:
  490. handler.clear()
  491. return {"status": "ok", "message": "Logs cleared"}
  492. # FastAPI routes
  493. @app.get("/")
  494. async def index(request: Request):
  495. return templates.TemplateResponse("index.html", {"request": request, "app_name": state.app_name, "custom_logo": state.custom_logo})
  496. @app.get("/settings")
  497. async def settings(request: Request):
  498. return templates.TemplateResponse("settings.html", {"request": request, "app_name": state.app_name, "custom_logo": state.custom_logo})
  499. # ============================================================================
  500. # Unified Settings API
  501. # ============================================================================
  502. @app.get("/api/settings", tags=["settings"])
  503. async def get_all_settings():
  504. """
  505. Get all application settings in a unified structure.
  506. This endpoint consolidates multiple settings endpoints into a single response.
  507. Individual settings endpoints are deprecated but still functional.
  508. """
  509. return {
  510. "app": {
  511. "name": state.app_name,
  512. "custom_logo": state.custom_logo
  513. },
  514. "connection": {
  515. "preferred_port": state.preferred_port
  516. },
  517. "patterns": {
  518. "clear_pattern_speed": state.clear_pattern_speed,
  519. "custom_clear_from_in": state.custom_clear_from_in,
  520. "custom_clear_from_out": state.custom_clear_from_out
  521. },
  522. "auto_play": {
  523. "enabled": state.auto_play_enabled,
  524. "playlist": state.auto_play_playlist,
  525. "run_mode": state.auto_play_run_mode,
  526. "pause_time": state.auto_play_pause_time,
  527. "clear_pattern": state.auto_play_clear_pattern,
  528. "shuffle": state.auto_play_shuffle
  529. },
  530. "scheduled_pause": {
  531. "enabled": state.scheduled_pause_enabled,
  532. "control_wled": state.scheduled_pause_control_wled,
  533. "finish_pattern": state.scheduled_pause_finish_pattern,
  534. "timezone": state.scheduled_pause_timezone,
  535. "time_slots": state.scheduled_pause_time_slots
  536. },
  537. "homing": {
  538. "mode": state.homing,
  539. "angular_offset_degrees": state.angular_homing_offset_degrees,
  540. "auto_home_enabled": state.auto_home_enabled,
  541. "auto_home_after_patterns": state.auto_home_after_patterns
  542. },
  543. "led": {
  544. "provider": state.led_provider,
  545. "wled_ip": state.wled_ip,
  546. "dw_led": {
  547. "num_leds": state.dw_led_num_leds,
  548. "gpio_pin": state.dw_led_gpio_pin,
  549. "pixel_order": state.dw_led_pixel_order,
  550. "brightness": state.dw_led_brightness,
  551. "speed": state.dw_led_speed,
  552. "intensity": state.dw_led_intensity,
  553. "idle_effect": state.dw_led_idle_effect,
  554. "playing_effect": state.dw_led_playing_effect,
  555. "idle_timeout_enabled": state.dw_led_idle_timeout_enabled,
  556. "idle_timeout_minutes": state.dw_led_idle_timeout_minutes
  557. }
  558. },
  559. "mqtt": {
  560. "enabled": state.mqtt_enabled,
  561. "broker": state.mqtt_broker,
  562. "port": state.mqtt_port,
  563. "username": state.mqtt_username,
  564. "has_password": bool(state.mqtt_password),
  565. "client_id": state.mqtt_client_id,
  566. "discovery_prefix": state.mqtt_discovery_prefix,
  567. "device_id": state.mqtt_device_id,
  568. "device_name": state.mqtt_device_name
  569. },
  570. "machine": {
  571. "detected_table_type": state.table_type,
  572. "table_type_override": state.table_type_override,
  573. "effective_table_type": state.table_type_override or state.table_type,
  574. "available_table_types": [
  575. {"value": "dune_weaver_mini", "label": "Dune Weaver Mini"},
  576. {"value": "dune_weaver_mini_pro", "label": "Dune Weaver Mini Pro"},
  577. {"value": "dune_weaver_mini_pro_byj", "label": "Dune Weaver Mini Pro (BYJ)"},
  578. {"value": "dune_weaver_gold", "label": "Dune Weaver Gold"},
  579. {"value": "dune_weaver", "label": "Dune Weaver"},
  580. {"value": "dune_weaver_pro", "label": "Dune Weaver Pro"}
  581. ]
  582. }
  583. }
  584. @app.patch("/api/settings", tags=["settings"])
  585. async def update_settings(settings_update: SettingsUpdate):
  586. """
  587. Partially update application settings.
  588. Only include the categories and fields you want to update.
  589. All fields are optional - only provided values will be updated.
  590. Example: {"app": {"name": "My Sand Table"}, "auto_play": {"enabled": true}}
  591. """
  592. updated_categories = []
  593. requires_restart = False
  594. led_reinit_needed = False
  595. old_led_provider = state.led_provider
  596. # App settings
  597. if settings_update.app:
  598. if settings_update.app.name is not None:
  599. state.app_name = settings_update.app.name or "Dune Weaver"
  600. if settings_update.app.custom_logo is not None:
  601. state.custom_logo = settings_update.app.custom_logo or None
  602. updated_categories.append("app")
  603. # Connection settings
  604. if settings_update.connection:
  605. if settings_update.connection.preferred_port is not None:
  606. port = settings_update.connection.preferred_port
  607. state.preferred_port = None if port in ("", "none") else port
  608. updated_categories.append("connection")
  609. # Pattern settings
  610. if settings_update.patterns:
  611. p = settings_update.patterns
  612. if p.clear_pattern_speed is not None:
  613. state.clear_pattern_speed = p.clear_pattern_speed if p.clear_pattern_speed > 0 else None
  614. if p.custom_clear_from_in is not None:
  615. state.custom_clear_from_in = p.custom_clear_from_in or None
  616. if p.custom_clear_from_out is not None:
  617. state.custom_clear_from_out = p.custom_clear_from_out or None
  618. updated_categories.append("patterns")
  619. # Auto-play settings
  620. if settings_update.auto_play:
  621. ap = settings_update.auto_play
  622. if ap.enabled is not None:
  623. state.auto_play_enabled = ap.enabled
  624. if ap.playlist is not None:
  625. state.auto_play_playlist = ap.playlist or None
  626. if ap.run_mode is not None:
  627. state.auto_play_run_mode = ap.run_mode
  628. if ap.pause_time is not None:
  629. state.auto_play_pause_time = ap.pause_time
  630. if ap.clear_pattern is not None:
  631. state.auto_play_clear_pattern = ap.clear_pattern
  632. if ap.shuffle is not None:
  633. state.auto_play_shuffle = ap.shuffle
  634. updated_categories.append("auto_play")
  635. # Scheduled pause (Still Sands) settings
  636. if settings_update.scheduled_pause:
  637. sp = settings_update.scheduled_pause
  638. if sp.enabled is not None:
  639. state.scheduled_pause_enabled = sp.enabled
  640. if sp.control_wled is not None:
  641. state.scheduled_pause_control_wled = sp.control_wled
  642. if sp.finish_pattern is not None:
  643. state.scheduled_pause_finish_pattern = sp.finish_pattern
  644. if sp.timezone is not None:
  645. # Empty string means use system default (store as None)
  646. state.scheduled_pause_timezone = sp.timezone if sp.timezone else None
  647. # Clear cached timezone in pattern_manager so it picks up the new setting
  648. from modules.core import pattern_manager
  649. pattern_manager._cached_timezone = None
  650. pattern_manager._cached_zoneinfo = None
  651. if sp.time_slots is not None:
  652. state.scheduled_pause_time_slots = [slot.model_dump() for slot in sp.time_slots]
  653. updated_categories.append("scheduled_pause")
  654. # Homing settings
  655. if settings_update.homing:
  656. h = settings_update.homing
  657. if h.mode is not None:
  658. state.homing = h.mode
  659. if h.angular_offset_degrees is not None:
  660. state.angular_homing_offset_degrees = h.angular_offset_degrees
  661. if h.auto_home_enabled is not None:
  662. state.auto_home_enabled = h.auto_home_enabled
  663. if h.auto_home_after_patterns is not None:
  664. state.auto_home_after_patterns = h.auto_home_after_patterns
  665. updated_categories.append("homing")
  666. # LED settings
  667. if settings_update.led:
  668. led = settings_update.led
  669. if led.provider is not None:
  670. state.led_provider = led.provider
  671. if led.provider != old_led_provider:
  672. led_reinit_needed = True
  673. if led.wled_ip is not None:
  674. state.wled_ip = led.wled_ip or None
  675. if led.dw_led:
  676. dw = led.dw_led
  677. if dw.num_leds is not None:
  678. state.dw_led_num_leds = dw.num_leds
  679. if dw.gpio_pin is not None:
  680. state.dw_led_gpio_pin = dw.gpio_pin
  681. if dw.pixel_order is not None:
  682. state.dw_led_pixel_order = dw.pixel_order
  683. if dw.brightness is not None:
  684. state.dw_led_brightness = dw.brightness
  685. if dw.speed is not None:
  686. state.dw_led_speed = dw.speed
  687. if dw.intensity is not None:
  688. state.dw_led_intensity = dw.intensity
  689. if dw.idle_effect is not None:
  690. state.dw_led_idle_effect = dw.idle_effect
  691. if dw.playing_effect is not None:
  692. state.dw_led_playing_effect = dw.playing_effect
  693. if dw.idle_timeout_enabled is not None:
  694. state.dw_led_idle_timeout_enabled = dw.idle_timeout_enabled
  695. if dw.idle_timeout_minutes is not None:
  696. state.dw_led_idle_timeout_minutes = dw.idle_timeout_minutes
  697. updated_categories.append("led")
  698. # MQTT settings
  699. if settings_update.mqtt:
  700. m = settings_update.mqtt
  701. if m.enabled is not None:
  702. state.mqtt_enabled = m.enabled
  703. if m.broker is not None:
  704. state.mqtt_broker = m.broker
  705. if m.port is not None:
  706. state.mqtt_port = m.port
  707. if m.username is not None:
  708. state.mqtt_username = m.username
  709. if m.password is not None:
  710. state.mqtt_password = m.password
  711. if m.client_id is not None:
  712. state.mqtt_client_id = m.client_id
  713. if m.discovery_prefix is not None:
  714. state.mqtt_discovery_prefix = m.discovery_prefix
  715. if m.device_id is not None:
  716. state.mqtt_device_id = m.device_id
  717. if m.device_name is not None:
  718. state.mqtt_device_name = m.device_name
  719. updated_categories.append("mqtt")
  720. requires_restart = True
  721. # Machine settings
  722. if settings_update.machine:
  723. m = settings_update.machine
  724. if m.table_type_override is not None:
  725. # Empty string or "auto" clears the override
  726. state.table_type_override = None if m.table_type_override in ("", "auto") else m.table_type_override
  727. updated_categories.append("machine")
  728. # Save state
  729. state.save()
  730. # Handle LED reinitialization if provider changed
  731. if led_reinit_needed:
  732. logger.info(f"LED provider changed from {old_led_provider} to {state.led_provider}, reinitialization may be needed")
  733. logger.info(f"Settings updated: {', '.join(updated_categories)}")
  734. return {
  735. "success": True,
  736. "updated_categories": updated_categories,
  737. "requires_restart": requires_restart,
  738. "led_reinit_needed": led_reinit_needed
  739. }
  740. # ============================================================================
  741. # Individual Settings Endpoints (Deprecated - use /api/settings instead)
  742. # ============================================================================
  743. @app.get("/api/auto_play-mode", deprecated=True, tags=["settings-deprecated"])
  744. async def get_auto_play_mode():
  745. """DEPRECATED: Use GET /api/settings instead. Get current auto_play mode settings."""
  746. return {
  747. "enabled": state.auto_play_enabled,
  748. "playlist": state.auto_play_playlist,
  749. "run_mode": state.auto_play_run_mode,
  750. "pause_time": state.auto_play_pause_time,
  751. "clear_pattern": state.auto_play_clear_pattern,
  752. "shuffle": state.auto_play_shuffle
  753. }
  754. @app.post("/api/auto_play-mode", deprecated=True, tags=["settings-deprecated"])
  755. async def set_auto_play_mode(request: auto_playModeRequest):
  756. """DEPRECATED: Use PATCH /api/settings instead. Update auto_play mode settings."""
  757. state.auto_play_enabled = request.enabled
  758. if request.playlist is not None:
  759. state.auto_play_playlist = request.playlist
  760. if request.run_mode is not None:
  761. state.auto_play_run_mode = request.run_mode
  762. if request.pause_time is not None:
  763. state.auto_play_pause_time = request.pause_time
  764. if request.clear_pattern is not None:
  765. state.auto_play_clear_pattern = request.clear_pattern
  766. if request.shuffle is not None:
  767. state.auto_play_shuffle = request.shuffle
  768. state.save()
  769. logger.info(f"auto_play mode {'enabled' if request.enabled else 'disabled'}, playlist: {request.playlist}")
  770. return {"success": True, "message": "auto_play mode settings updated"}
  771. @app.get("/api/scheduled-pause", deprecated=True, tags=["settings-deprecated"])
  772. async def get_scheduled_pause():
  773. """DEPRECATED: Use GET /api/settings instead. Get current Still Sands settings."""
  774. return {
  775. "enabled": state.scheduled_pause_enabled,
  776. "control_wled": state.scheduled_pause_control_wled,
  777. "finish_pattern": state.scheduled_pause_finish_pattern,
  778. "timezone": state.scheduled_pause_timezone,
  779. "time_slots": state.scheduled_pause_time_slots
  780. }
  781. @app.post("/api/scheduled-pause", deprecated=True, tags=["settings-deprecated"])
  782. async def set_scheduled_pause(request: ScheduledPauseRequest):
  783. """Update Still Sands settings."""
  784. try:
  785. # Validate time slots
  786. for i, slot in enumerate(request.time_slots):
  787. # Validate time format (HH:MM)
  788. try:
  789. start_time = datetime.strptime(slot.start_time, "%H:%M").time()
  790. end_time = datetime.strptime(slot.end_time, "%H:%M").time()
  791. except ValueError:
  792. raise HTTPException(
  793. status_code=400,
  794. detail=f"Invalid time format in slot {i+1}. Use HH:MM format."
  795. )
  796. # Validate days setting
  797. if slot.days not in ["daily", "weekdays", "weekends", "custom"]:
  798. raise HTTPException(
  799. status_code=400,
  800. detail=f"Invalid days setting in slot {i+1}. Must be 'daily', 'weekdays', 'weekends', or 'custom'."
  801. )
  802. # Validate custom days if applicable
  803. if slot.days == "custom":
  804. if not slot.custom_days or len(slot.custom_days) == 0:
  805. raise HTTPException(
  806. status_code=400,
  807. detail=f"Custom days must be specified for slot {i+1} when days is set to 'custom'."
  808. )
  809. valid_days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
  810. for day in slot.custom_days:
  811. if day not in valid_days:
  812. raise HTTPException(
  813. status_code=400,
  814. detail=f"Invalid day '{day}' in slot {i+1}. Valid days are: {', '.join(valid_days)}"
  815. )
  816. # Update state
  817. state.scheduled_pause_enabled = request.enabled
  818. state.scheduled_pause_control_wled = request.control_wled
  819. state.scheduled_pause_finish_pattern = request.finish_pattern
  820. state.scheduled_pause_timezone = request.timezone if request.timezone else None
  821. state.scheduled_pause_time_slots = [slot.model_dump() for slot in request.time_slots]
  822. state.save()
  823. # Clear cached timezone so it picks up the new setting
  824. from modules.core import pattern_manager
  825. pattern_manager._cached_timezone = None
  826. pattern_manager._cached_zoneinfo = None
  827. wled_msg = " (with WLED control)" if request.control_wled else ""
  828. finish_msg = " (finish pattern first)" if request.finish_pattern else ""
  829. tz_msg = f" (timezone: {request.timezone})" if request.timezone else ""
  830. logger.info(f"Still Sands {'enabled' if request.enabled else 'disabled'} with {len(request.time_slots)} time slots{wled_msg}{finish_msg}{tz_msg}")
  831. return {"success": True, "message": "Still Sands settings updated"}
  832. except HTTPException:
  833. raise
  834. except Exception as e:
  835. logger.error(f"Error updating Still Sands settings: {str(e)}")
  836. raise HTTPException(status_code=500, detail=f"Failed to update Still Sands settings: {str(e)}")
  837. @app.get("/api/homing-config", deprecated=True, tags=["settings-deprecated"])
  838. async def get_homing_config():
  839. """Get homing configuration (mode, compass offset, and auto-home settings)."""
  840. return {
  841. "homing_mode": state.homing,
  842. "angular_homing_offset_degrees": state.angular_homing_offset_degrees,
  843. "auto_home_enabled": state.auto_home_enabled,
  844. "auto_home_after_patterns": state.auto_home_after_patterns
  845. }
  846. class HomingConfigRequest(BaseModel):
  847. homing_mode: int = 0 # 0 = crash, 1 = sensor
  848. angular_homing_offset_degrees: float = 0.0
  849. auto_home_enabled: Optional[bool] = None
  850. auto_home_after_patterns: Optional[int] = None
  851. @app.post("/api/homing-config", deprecated=True, tags=["settings-deprecated"])
  852. async def set_homing_config(request: HomingConfigRequest):
  853. """Set homing configuration (mode, compass offset, and auto-home settings)."""
  854. try:
  855. # Validate homing mode
  856. if request.homing_mode not in [0, 1]:
  857. raise HTTPException(status_code=400, detail="Homing mode must be 0 (crash) or 1 (sensor)")
  858. state.homing = request.homing_mode
  859. state.angular_homing_offset_degrees = request.angular_homing_offset_degrees
  860. # Update auto-home settings if provided
  861. if request.auto_home_enabled is not None:
  862. state.auto_home_enabled = request.auto_home_enabled
  863. if request.auto_home_after_patterns is not None:
  864. if request.auto_home_after_patterns < 1:
  865. raise HTTPException(status_code=400, detail="Auto-home after patterns must be at least 1")
  866. state.auto_home_after_patterns = request.auto_home_after_patterns
  867. state.save()
  868. mode_name = "crash" if request.homing_mode == 0 else "sensor"
  869. logger.info(f"Homing mode set to {mode_name}, compass offset set to {request.angular_homing_offset_degrees}°")
  870. if request.auto_home_enabled is not None:
  871. logger.info(f"Auto-home enabled: {state.auto_home_enabled}, after {state.auto_home_after_patterns} patterns")
  872. return {"success": True, "message": "Homing configuration updated"}
  873. except HTTPException:
  874. raise
  875. except Exception as e:
  876. logger.error(f"Error updating homing configuration: {str(e)}")
  877. raise HTTPException(status_code=500, detail=f"Failed to update homing configuration: {str(e)}")
  878. @app.get("/list_serial_ports")
  879. async def list_ports():
  880. logger.debug("Listing available serial ports")
  881. return await asyncio.to_thread(connection_manager.list_serial_ports)
  882. @app.post("/connect")
  883. async def connect(request: ConnectRequest):
  884. if not request.port:
  885. state.conn = connection_manager.WebSocketConnection('ws://fluidnc.local:81')
  886. connection_manager.device_init()
  887. logger.info('Successfully connected to websocket ws://fluidnc.local:81')
  888. return {"success": True}
  889. try:
  890. state.conn = connection_manager.SerialConnection(request.port)
  891. connection_manager.device_init()
  892. logger.info(f'Successfully connected to serial port {request.port}')
  893. return {"success": True}
  894. except Exception as e:
  895. logger.error(f'Failed to connect to serial port {request.port}: {str(e)}')
  896. raise HTTPException(status_code=500, detail=str(e))
  897. @app.post("/disconnect")
  898. async def disconnect():
  899. try:
  900. state.conn.close()
  901. logger.info('Successfully disconnected from serial port')
  902. return {"success": True}
  903. except Exception as e:
  904. logger.error(f'Failed to disconnect serial: {str(e)}')
  905. raise HTTPException(status_code=500, detail=str(e))
  906. @app.post("/restart_connection")
  907. async def restart(request: ConnectRequest):
  908. if not request.port:
  909. logger.warning("Restart serial request received without port")
  910. raise HTTPException(status_code=400, detail="No port provided")
  911. try:
  912. logger.info(f"Restarting connection on port {request.port}")
  913. connection_manager.restart_connection()
  914. return {"success": True}
  915. except Exception as e:
  916. logger.error(f"Failed to restart serial on port {request.port}: {str(e)}")
  917. raise HTTPException(status_code=500, detail=str(e))
  918. @app.get("/list_theta_rho_files")
  919. async def list_theta_rho_files():
  920. logger.debug("Listing theta-rho files")
  921. # Run the blocking file system operation in a thread pool
  922. files = await asyncio.to_thread(pattern_manager.list_theta_rho_files)
  923. return sorted(files)
  924. @app.get("/list_theta_rho_files_with_metadata")
  925. async def list_theta_rho_files_with_metadata():
  926. """Get list of theta-rho files with metadata for sorting and filtering.
  927. Optimized to process files asynchronously and support request cancellation.
  928. """
  929. from modules.core.cache_manager import get_pattern_metadata
  930. import asyncio
  931. from concurrent.futures import ThreadPoolExecutor
  932. # Run the blocking file listing in a thread
  933. files = await asyncio.to_thread(pattern_manager.list_theta_rho_files)
  934. files_with_metadata = []
  935. # Use ThreadPoolExecutor for I/O-bound operations
  936. executor = ThreadPoolExecutor(max_workers=4)
  937. def process_file(file_path):
  938. """Process a single file and return its metadata."""
  939. try:
  940. full_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_path)
  941. # Get file stats
  942. file_stat = os.stat(full_path)
  943. # Get cached metadata (this should be fast if cached)
  944. metadata = get_pattern_metadata(file_path)
  945. # Extract full folder path from file path
  946. path_parts = file_path.split('/')
  947. if len(path_parts) > 1:
  948. # Get everything except the filename (join all folder parts)
  949. category = '/'.join(path_parts[:-1])
  950. else:
  951. category = 'root'
  952. # Get file name without extension
  953. file_name = os.path.splitext(os.path.basename(file_path))[0]
  954. # Use modification time (mtime) for "date modified"
  955. date_modified = file_stat.st_mtime
  956. return {
  957. 'path': file_path,
  958. 'name': file_name,
  959. 'category': category,
  960. 'date_modified': date_modified,
  961. 'coordinates_count': metadata.get('total_coordinates', 0) if metadata else 0
  962. }
  963. except Exception as e:
  964. logger.warning(f"Error getting metadata for {file_path}: {str(e)}")
  965. # Include file with minimal info if metadata fails
  966. path_parts = file_path.split('/')
  967. if len(path_parts) > 1:
  968. category = '/'.join(path_parts[:-1])
  969. else:
  970. category = 'root'
  971. return {
  972. 'path': file_path,
  973. 'name': os.path.splitext(os.path.basename(file_path))[0],
  974. 'category': category,
  975. 'date_modified': 0,
  976. 'coordinates_count': 0
  977. }
  978. # Load the entire metadata cache at once (async)
  979. # This is much faster than 1000+ individual metadata lookups
  980. try:
  981. import json
  982. metadata_cache_path = "metadata_cache.json"
  983. # Use async file reading to avoid blocking the event loop
  984. cache_data = await asyncio.to_thread(lambda: json.load(open(metadata_cache_path, 'r')))
  985. cache_dict = cache_data.get('data', {})
  986. logger.debug(f"Loaded metadata cache with {len(cache_dict)} entries")
  987. # Process all files using cached data only
  988. for file_path in files:
  989. try:
  990. # Extract category from path
  991. path_parts = file_path.split('/')
  992. category = '/'.join(path_parts[:-1]) if len(path_parts) > 1 else 'root'
  993. # Get file name without extension
  994. file_name = os.path.splitext(os.path.basename(file_path))[0]
  995. # Get metadata from cache
  996. cached_entry = cache_dict.get(file_path, {})
  997. if isinstance(cached_entry, dict) and 'metadata' in cached_entry:
  998. metadata = cached_entry['metadata']
  999. coords_count = metadata.get('total_coordinates', 0)
  1000. date_modified = cached_entry.get('mtime', 0)
  1001. else:
  1002. coords_count = 0
  1003. date_modified = 0
  1004. files_with_metadata.append({
  1005. 'path': file_path,
  1006. 'name': file_name,
  1007. 'category': category,
  1008. 'date_modified': date_modified,
  1009. 'coordinates_count': coords_count
  1010. })
  1011. except Exception as e:
  1012. logger.warning(f"Error processing {file_path}: {e}")
  1013. # Include file with minimal info if processing fails
  1014. path_parts = file_path.split('/')
  1015. category = '/'.join(path_parts[:-1]) if len(path_parts) > 1 else 'root'
  1016. files_with_metadata.append({
  1017. 'path': file_path,
  1018. 'name': os.path.splitext(os.path.basename(file_path))[0],
  1019. 'category': category,
  1020. 'date_modified': 0,
  1021. 'coordinates_count': 0
  1022. })
  1023. except Exception as e:
  1024. logger.error(f"Failed to load metadata cache, falling back to slow method: {e}")
  1025. # Fallback to original method if cache loading fails
  1026. # Create tasks only when needed
  1027. loop = asyncio.get_running_loop()
  1028. tasks = [loop.run_in_executor(executor, process_file, file_path) for file_path in files]
  1029. for task in asyncio.as_completed(tasks):
  1030. try:
  1031. result = await task
  1032. files_with_metadata.append(result)
  1033. except Exception as task_error:
  1034. logger.error(f"Error processing file: {str(task_error)}")
  1035. # Clean up executor
  1036. executor.shutdown(wait=False)
  1037. return files_with_metadata
  1038. @app.post("/upload_theta_rho")
  1039. async def upload_theta_rho(file: UploadFile = File(...)):
  1040. """Upload a theta-rho file."""
  1041. try:
  1042. # Save the file
  1043. # Ensure custom_patterns directory exists
  1044. custom_patterns_dir = os.path.join(pattern_manager.THETA_RHO_DIR, "custom_patterns")
  1045. os.makedirs(custom_patterns_dir, exist_ok=True)
  1046. # Use forward slashes for internal path representation to maintain consistency
  1047. file_path_in_patterns_dir = f"custom_patterns/{file.filename}"
  1048. full_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_path_in_patterns_dir)
  1049. # Save the uploaded file with proper encoding for Windows compatibility
  1050. file_content = await file.read()
  1051. try:
  1052. # First try to decode as UTF-8 and re-encode to ensure proper encoding
  1053. text_content = file_content.decode('utf-8')
  1054. with open(full_file_path, "w", encoding='utf-8') as f:
  1055. f.write(text_content)
  1056. except UnicodeDecodeError:
  1057. # If UTF-8 decoding fails, save as binary (fallback)
  1058. with open(full_file_path, "wb") as f:
  1059. f.write(file_content)
  1060. logger.info(f"File {file.filename} saved successfully")
  1061. # Generate image preview for the new file with retry logic
  1062. max_retries = 3
  1063. for attempt in range(max_retries):
  1064. try:
  1065. logger.info(f"Generating preview for {file_path_in_patterns_dir} (attempt {attempt + 1}/{max_retries})")
  1066. success = await generate_image_preview(file_path_in_patterns_dir)
  1067. if success:
  1068. logger.info(f"Preview generated successfully for {file_path_in_patterns_dir}")
  1069. break
  1070. else:
  1071. logger.warning(f"Preview generation failed for {file_path_in_patterns_dir} (attempt {attempt + 1})")
  1072. if attempt < max_retries - 1:
  1073. await asyncio.sleep(0.5) # Small delay before retry
  1074. except Exception as e:
  1075. logger.error(f"Error generating preview for {file_path_in_patterns_dir} (attempt {attempt + 1}): {str(e)}")
  1076. if attempt < max_retries - 1:
  1077. await asyncio.sleep(0.5) # Small delay before retry
  1078. # Notify connected clients (including touchscreen) about the new pattern
  1079. await broadcast_patterns_updated(file_path_in_patterns_dir)
  1080. return {"success": True, "message": f"File {file.filename} uploaded successfully"}
  1081. except Exception as e:
  1082. logger.error(f"Error uploading file: {str(e)}")
  1083. raise HTTPException(status_code=500, detail=str(e))
  1084. @app.post("/get_theta_rho_coordinates")
  1085. async def get_theta_rho_coordinates(request: GetCoordinatesRequest):
  1086. """Get theta-rho coordinates for animated preview."""
  1087. try:
  1088. # Normalize file path for cross-platform compatibility and remove prefixes
  1089. file_name = normalize_file_path(request.file_name)
  1090. file_path = os.path.join(THETA_RHO_DIR, file_name)
  1091. # Check file existence asynchronously
  1092. exists = await asyncio.to_thread(os.path.exists, file_path)
  1093. if not exists:
  1094. raise HTTPException(status_code=404, detail=f"File {file_name} not found")
  1095. # Parse the theta-rho file in a separate process for CPU-intensive work
  1096. # This prevents blocking the motion control thread
  1097. loop = asyncio.get_running_loop()
  1098. coordinates = await loop.run_in_executor(pool_module.get_pool(), parse_theta_rho_file, file_path)
  1099. if not coordinates:
  1100. raise HTTPException(status_code=400, detail="No valid coordinates found in file")
  1101. return {
  1102. "success": True,
  1103. "coordinates": coordinates,
  1104. "total_points": len(coordinates)
  1105. }
  1106. except Exception as e:
  1107. logger.error(f"Error getting coordinates for {request.file_name}: {str(e)}")
  1108. raise HTTPException(status_code=500, detail=str(e))
  1109. @app.post("/run_theta_rho")
  1110. async def run_theta_rho(request: ThetaRhoRequest, background_tasks: BackgroundTasks):
  1111. if not request.file_name:
  1112. logger.warning('Run theta-rho request received without file name')
  1113. raise HTTPException(status_code=400, detail="No file name provided")
  1114. file_path = None
  1115. if 'clear' in request.file_name:
  1116. logger.info(f'Clear pattern file: {request.file_name.split(".")[0]}')
  1117. file_path = pattern_manager.get_clear_pattern_file(request.file_name.split('.')[0])
  1118. logger.info(f'Clear pattern file: {file_path}')
  1119. if not file_path:
  1120. # Normalize file path for cross-platform compatibility
  1121. normalized_file_name = normalize_file_path(request.file_name)
  1122. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  1123. if not os.path.exists(file_path):
  1124. logger.error(f'Theta-rho file not found: {file_path}')
  1125. raise HTTPException(status_code=404, detail="File not found")
  1126. try:
  1127. if not (state.conn.is_connected() if state.conn else False):
  1128. logger.warning("Attempted to run a pattern without a connection")
  1129. raise HTTPException(status_code=400, detail="Connection not established")
  1130. if pattern_manager.pattern_lock.locked():
  1131. logger.info("Another pattern is running, stopping it first...")
  1132. await pattern_manager.stop_actions()
  1133. files_to_run = [file_path]
  1134. logger.info(f'Running theta-rho file: {request.file_name} with pre_execution={request.pre_execution}')
  1135. # Only include clear_pattern if it's not "none"
  1136. kwargs = {}
  1137. if request.pre_execution != "none":
  1138. kwargs['clear_pattern'] = request.pre_execution
  1139. # Pass arguments properly
  1140. background_tasks.add_task(
  1141. pattern_manager.run_theta_rho_files,
  1142. files_to_run, # First positional argument
  1143. **kwargs # Spread keyword arguments
  1144. )
  1145. return {"success": True}
  1146. except HTTPException as http_exc:
  1147. logger.error(f'Failed to run theta-rho file {request.file_name}: {http_exc.detail}')
  1148. raise http_exc
  1149. except Exception as e:
  1150. logger.error(f'Failed to run theta-rho file {request.file_name}: {str(e)}')
  1151. raise HTTPException(status_code=500, detail=str(e))
  1152. @app.post("/stop_execution")
  1153. async def stop_execution():
  1154. if not (state.conn.is_connected() if state.conn else False):
  1155. logger.warning("Attempted to stop without a connection")
  1156. raise HTTPException(status_code=400, detail="Connection not established")
  1157. await pattern_manager.stop_actions()
  1158. return {"success": True}
  1159. @app.post("/send_home")
  1160. async def send_home():
  1161. try:
  1162. if not (state.conn.is_connected() if state.conn else False):
  1163. logger.warning("Attempted to move to home without a connection")
  1164. raise HTTPException(status_code=400, detail="Connection not established")
  1165. # Run homing with 15 second timeout
  1166. success = await asyncio.to_thread(connection_manager.home)
  1167. if not success:
  1168. logger.error("Homing failed or timed out")
  1169. raise HTTPException(status_code=500, detail="Homing failed or timed out after 15 seconds")
  1170. return {"success": True}
  1171. except HTTPException:
  1172. raise
  1173. except Exception as e:
  1174. logger.error(f"Failed to send home command: {str(e)}")
  1175. raise HTTPException(status_code=500, detail=str(e))
  1176. @app.post("/run_theta_rho_file/{file_name}")
  1177. async def run_specific_theta_rho_file(file_name: str):
  1178. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, file_name)
  1179. if not os.path.exists(file_path):
  1180. raise HTTPException(status_code=404, detail="File not found")
  1181. if not (state.conn.is_connected() if state.conn else False):
  1182. logger.warning("Attempted to run a pattern without a connection")
  1183. raise HTTPException(status_code=400, detail="Connection not established")
  1184. pattern_manager.run_theta_rho_file(file_path)
  1185. return {"success": True}
  1186. class DeleteFileRequest(BaseModel):
  1187. file_name: str
  1188. @app.post("/delete_theta_rho_file")
  1189. async def delete_theta_rho_file(request: DeleteFileRequest):
  1190. if not request.file_name:
  1191. logger.warning("Delete theta-rho file request received without filename")
  1192. raise HTTPException(status_code=400, detail="No file name provided")
  1193. # Normalize file path for cross-platform compatibility
  1194. normalized_file_name = normalize_file_path(request.file_name)
  1195. file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  1196. # Check file existence asynchronously
  1197. exists = await asyncio.to_thread(os.path.exists, file_path)
  1198. if not exists:
  1199. logger.error(f"Attempted to delete non-existent file: {file_path}")
  1200. raise HTTPException(status_code=404, detail="File not found")
  1201. try:
  1202. # Delete the pattern file asynchronously
  1203. await asyncio.to_thread(os.remove, file_path)
  1204. logger.info(f"Successfully deleted theta-rho file: {request.file_name}")
  1205. # Clean up cached preview image and metadata asynchronously
  1206. from modules.core.cache_manager import delete_pattern_cache
  1207. cache_cleanup_success = await asyncio.to_thread(delete_pattern_cache, normalized_file_name)
  1208. if cache_cleanup_success:
  1209. logger.info(f"Successfully cleaned up cache for {request.file_name}")
  1210. else:
  1211. logger.warning(f"Cache cleanup failed for {request.file_name}, but pattern was deleted")
  1212. return {"success": True, "cache_cleanup": cache_cleanup_success}
  1213. except Exception as e:
  1214. logger.error(f"Failed to delete theta-rho file {request.file_name}: {str(e)}")
  1215. raise HTTPException(status_code=500, detail=str(e))
  1216. @app.post("/move_to_center")
  1217. async def move_to_center():
  1218. try:
  1219. if not (state.conn.is_connected() if state.conn else False):
  1220. logger.warning("Attempted to move to center without a connection")
  1221. raise HTTPException(status_code=400, detail="Connection not established")
  1222. logger.info("Moving device to center position")
  1223. await pattern_manager.reset_theta()
  1224. await pattern_manager.move_polar(0, 0)
  1225. return {"success": True}
  1226. except Exception as e:
  1227. logger.error(f"Failed to move to center: {str(e)}")
  1228. raise HTTPException(status_code=500, detail=str(e))
  1229. @app.post("/move_to_perimeter")
  1230. async def move_to_perimeter():
  1231. try:
  1232. if not (state.conn.is_connected() if state.conn else False):
  1233. logger.warning("Attempted to move to perimeter without a connection")
  1234. raise HTTPException(status_code=400, detail="Connection not established")
  1235. await pattern_manager.reset_theta()
  1236. await pattern_manager.move_polar(0, 1)
  1237. return {"success": True}
  1238. except Exception as e:
  1239. logger.error(f"Failed to move to perimeter: {str(e)}")
  1240. raise HTTPException(status_code=500, detail=str(e))
  1241. @app.post("/preview_thr")
  1242. async def preview_thr(request: DeleteFileRequest):
  1243. if not request.file_name:
  1244. logger.warning("Preview theta-rho request received without filename")
  1245. raise HTTPException(status_code=400, detail="No file name provided")
  1246. # Normalize file path for cross-platform compatibility
  1247. normalized_file_name = normalize_file_path(request.file_name)
  1248. # Construct the full path to the pattern file to check existence
  1249. pattern_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  1250. # Check file existence asynchronously
  1251. exists = await asyncio.to_thread(os.path.exists, pattern_file_path)
  1252. if not exists:
  1253. logger.error(f"Attempted to preview non-existent pattern file: {pattern_file_path}")
  1254. raise HTTPException(status_code=404, detail="Pattern file not found")
  1255. try:
  1256. cache_path = get_cache_path(normalized_file_name)
  1257. # Check cache existence asynchronously
  1258. cache_exists = await asyncio.to_thread(os.path.exists, cache_path)
  1259. if not cache_exists:
  1260. logger.info(f"Cache miss for {request.file_name}. Generating preview...")
  1261. # Attempt to generate the preview if it's missing
  1262. success = await generate_image_preview(normalized_file_name)
  1263. cache_exists_after = await asyncio.to_thread(os.path.exists, cache_path)
  1264. if not success or not cache_exists_after:
  1265. logger.error(f"Failed to generate or find preview for {request.file_name} after attempting generation.")
  1266. raise HTTPException(status_code=500, detail="Failed to generate preview image.")
  1267. # Try to get coordinates from metadata cache first
  1268. metadata = get_pattern_metadata(normalized_file_name)
  1269. if metadata:
  1270. first_coord_obj = metadata.get('first_coordinate')
  1271. last_coord_obj = metadata.get('last_coordinate')
  1272. else:
  1273. # Fallback to parsing file if metadata not cached (shouldn't happen after initial cache)
  1274. logger.debug(f"Metadata cache miss for {request.file_name}, parsing file")
  1275. coordinates = await asyncio.to_thread(parse_theta_rho_file, pattern_file_path)
  1276. first_coord = coordinates[0] if coordinates else None
  1277. last_coord = coordinates[-1] if coordinates else None
  1278. # Format coordinates as objects with x and y properties
  1279. first_coord_obj = {"x": first_coord[0], "y": first_coord[1]} if first_coord else None
  1280. last_coord_obj = {"x": last_coord[0], "y": last_coord[1]} if last_coord else None
  1281. # Return JSON with preview URL and coordinates
  1282. # URL encode the file_name for the preview URL
  1283. # Handle both forward slashes and backslashes for cross-platform compatibility
  1284. encoded_filename = normalized_file_name.replace('\\', '--').replace('/', '--')
  1285. return {
  1286. "preview_url": f"/preview/{encoded_filename}",
  1287. "first_coordinate": first_coord_obj,
  1288. "last_coordinate": last_coord_obj
  1289. }
  1290. except HTTPException:
  1291. raise
  1292. except Exception as e:
  1293. logger.error(f"Failed to generate or serve preview for {request.file_name}: {str(e)}")
  1294. raise HTTPException(status_code=500, detail=f"Failed to serve preview image: {str(e)}")
  1295. @app.get("/preview/{encoded_filename}")
  1296. async def serve_preview(encoded_filename: str):
  1297. """Serve a preview image for a pattern file."""
  1298. # Decode the filename by replacing -- with the original path separators
  1299. # First try forward slash (most common case), then backslash if needed
  1300. file_name = encoded_filename.replace('--', '/')
  1301. # Apply normalization to handle any remaining path prefixes
  1302. file_name = normalize_file_path(file_name)
  1303. # Check if the decoded path exists, if not try backslash decoding
  1304. cache_path = get_cache_path(file_name)
  1305. if not os.path.exists(cache_path):
  1306. # Try with backslash for Windows paths
  1307. file_name_backslash = encoded_filename.replace('--', '\\')
  1308. file_name_backslash = normalize_file_path(file_name_backslash)
  1309. cache_path_backslash = get_cache_path(file_name_backslash)
  1310. if os.path.exists(cache_path_backslash):
  1311. file_name = file_name_backslash
  1312. cache_path = cache_path_backslash
  1313. # cache_path is already determined above in the decoding logic
  1314. if not os.path.exists(cache_path):
  1315. logger.error(f"Preview image not found for {file_name}")
  1316. raise HTTPException(status_code=404, detail="Preview image not found")
  1317. # Add caching headers
  1318. headers = {
  1319. "Cache-Control": "public, max-age=31536000", # Cache for 1 year
  1320. "Content-Type": "image/webp",
  1321. "Accept-Ranges": "bytes"
  1322. }
  1323. return FileResponse(
  1324. cache_path,
  1325. media_type="image/webp",
  1326. headers=headers
  1327. )
  1328. @app.post("/send_coordinate")
  1329. async def send_coordinate(request: CoordinateRequest):
  1330. if not (state.conn.is_connected() if state.conn else False):
  1331. logger.warning("Attempted to send coordinate without a connection")
  1332. raise HTTPException(status_code=400, detail="Connection not established")
  1333. try:
  1334. logger.debug(f"Sending coordinate: theta={request.theta}, rho={request.rho}")
  1335. await pattern_manager.move_polar(request.theta, request.rho)
  1336. return {"success": True}
  1337. except Exception as e:
  1338. logger.error(f"Failed to send coordinate: {str(e)}")
  1339. raise HTTPException(status_code=500, detail=str(e))
  1340. @app.get("/download/{filename}")
  1341. async def download_file(filename: str):
  1342. return FileResponse(
  1343. os.path.join(pattern_manager.THETA_RHO_DIR, filename),
  1344. filename=filename
  1345. )
  1346. @app.get("/serial_status")
  1347. async def serial_status():
  1348. connected = state.conn.is_connected() if state.conn else False
  1349. port = state.port
  1350. logger.debug(f"Serial status check - connected: {connected}, port: {port}")
  1351. return {
  1352. "connected": connected,
  1353. "port": port,
  1354. "preferred_port": state.preferred_port
  1355. }
  1356. @app.get("/api/preferred-port", deprecated=True, tags=["settings-deprecated"])
  1357. async def get_preferred_port():
  1358. """Get the currently configured preferred port for auto-connect."""
  1359. return {
  1360. "preferred_port": state.preferred_port
  1361. }
  1362. @app.post("/api/preferred-port", deprecated=True, tags=["settings-deprecated"])
  1363. async def set_preferred_port(request: Request):
  1364. """Set the preferred port for auto-connect."""
  1365. data = await request.json()
  1366. preferred_port = data.get("preferred_port")
  1367. # Allow setting to None to clear the preference
  1368. if preferred_port == "" or preferred_port == "none":
  1369. preferred_port = None
  1370. state.preferred_port = preferred_port
  1371. state.save()
  1372. logger.info(f"Preferred port set to: {preferred_port}")
  1373. return {
  1374. "success": True,
  1375. "preferred_port": state.preferred_port
  1376. }
  1377. @app.post("/pause_execution")
  1378. async def pause_execution():
  1379. if pattern_manager.pause_execution():
  1380. return {"success": True, "message": "Execution paused"}
  1381. raise HTTPException(status_code=500, detail="Failed to pause execution")
  1382. @app.post("/resume_execution")
  1383. async def resume_execution():
  1384. if pattern_manager.resume_execution():
  1385. return {"success": True, "message": "Execution resumed"}
  1386. raise HTTPException(status_code=500, detail="Failed to resume execution")
  1387. # Playlist endpoints
  1388. @app.get("/list_all_playlists")
  1389. async def list_all_playlists():
  1390. playlist_names = playlist_manager.list_all_playlists()
  1391. return playlist_names
  1392. @app.get("/get_playlist")
  1393. async def get_playlist(name: str):
  1394. if not name:
  1395. raise HTTPException(status_code=400, detail="Missing playlist name parameter")
  1396. playlist = playlist_manager.get_playlist(name)
  1397. if not playlist:
  1398. raise HTTPException(status_code=404, detail=f"Playlist '{name}' not found")
  1399. return playlist
  1400. @app.post("/create_playlist")
  1401. async def create_playlist(request: PlaylistRequest):
  1402. success = playlist_manager.create_playlist(request.playlist_name, request.files)
  1403. return {
  1404. "success": success,
  1405. "message": f"Playlist '{request.playlist_name}' created/updated"
  1406. }
  1407. @app.post("/modify_playlist")
  1408. async def modify_playlist(request: PlaylistRequest):
  1409. success = playlist_manager.modify_playlist(request.playlist_name, request.files)
  1410. return {
  1411. "success": success,
  1412. "message": f"Playlist '{request.playlist_name}' updated"
  1413. }
  1414. @app.delete("/delete_playlist")
  1415. async def delete_playlist(request: DeletePlaylistRequest):
  1416. success = playlist_manager.delete_playlist(request.playlist_name)
  1417. if not success:
  1418. raise HTTPException(
  1419. status_code=404,
  1420. detail=f"Playlist '{request.playlist_name}' not found"
  1421. )
  1422. return {
  1423. "success": True,
  1424. "message": f"Playlist '{request.playlist_name}' deleted"
  1425. }
  1426. @app.post("/rename_playlist")
  1427. async def rename_playlist(request: RenamePlaylistRequest):
  1428. """Rename an existing playlist."""
  1429. success, message = playlist_manager.rename_playlist(request.old_name, request.new_name)
  1430. if not success:
  1431. raise HTTPException(
  1432. status_code=400,
  1433. detail=message
  1434. )
  1435. return {
  1436. "success": True,
  1437. "message": message,
  1438. "new_name": request.new_name
  1439. }
  1440. class AddToPlaylistRequest(BaseModel):
  1441. playlist_name: str
  1442. pattern: str
  1443. @app.post("/add_to_playlist")
  1444. async def add_to_playlist(request: AddToPlaylistRequest):
  1445. success = playlist_manager.add_to_playlist(request.playlist_name, request.pattern)
  1446. if not success:
  1447. raise HTTPException(status_code=404, detail="Playlist not found")
  1448. return {"success": True}
  1449. @app.post("/run_playlist")
  1450. async def run_playlist_endpoint(request: PlaylistRequest):
  1451. """Run a playlist with specified parameters."""
  1452. try:
  1453. if not (state.conn.is_connected() if state.conn else False):
  1454. logger.warning("Attempted to run a playlist without a connection")
  1455. raise HTTPException(status_code=400, detail="Connection not established")
  1456. if not os.path.exists(playlist_manager.PLAYLISTS_FILE):
  1457. raise HTTPException(status_code=404, detail=f"Playlist '{request.playlist_name}' not found")
  1458. # Start the playlist execution
  1459. success, message = await playlist_manager.run_playlist(
  1460. request.playlist_name,
  1461. pause_time=request.pause_time,
  1462. clear_pattern=request.clear_pattern,
  1463. run_mode=request.run_mode,
  1464. shuffle=request.shuffle
  1465. )
  1466. if not success:
  1467. raise HTTPException(status_code=409, detail=message)
  1468. return {"message": f"Started playlist: {request.playlist_name}"}
  1469. except Exception as e:
  1470. logger.error(f"Error running playlist: {e}")
  1471. raise HTTPException(status_code=500, detail=str(e))
  1472. @app.post("/set_speed")
  1473. async def set_speed(request: SpeedRequest):
  1474. try:
  1475. if not (state.conn.is_connected() if state.conn else False):
  1476. logger.warning("Attempted to change speed without a connection")
  1477. raise HTTPException(status_code=400, detail="Connection not established")
  1478. if request.speed <= 0:
  1479. logger.warning(f"Invalid speed value received: {request.speed}")
  1480. raise HTTPException(status_code=400, detail="Invalid speed value")
  1481. state.speed = request.speed
  1482. return {"success": True, "speed": request.speed}
  1483. except Exception as e:
  1484. logger.error(f"Failed to set speed: {str(e)}")
  1485. raise HTTPException(status_code=500, detail=str(e))
  1486. @app.get("/check_software_update")
  1487. async def check_updates():
  1488. update_info = update_manager.check_git_updates()
  1489. return update_info
  1490. @app.post("/update_software")
  1491. async def update_software():
  1492. logger.info("Starting software update process")
  1493. success, error_message, error_log = update_manager.update_software()
  1494. if success:
  1495. logger.info("Software update completed successfully")
  1496. return {"success": True}
  1497. else:
  1498. logger.error(f"Software update failed: {error_message}\nDetails: {error_log}")
  1499. raise HTTPException(
  1500. status_code=500,
  1501. detail={
  1502. "error": error_message,
  1503. "details": error_log
  1504. }
  1505. )
  1506. @app.post("/set_wled_ip")
  1507. async def set_wled_ip(request: WLEDRequest):
  1508. """Legacy endpoint for backward compatibility - sets WLED as LED provider"""
  1509. state.wled_ip = request.wled_ip
  1510. state.led_provider = "wled" if request.wled_ip else "none"
  1511. state.led_controller = LEDInterface("wled", request.wled_ip) if request.wled_ip else None
  1512. if state.led_controller:
  1513. state.led_controller.effect_idle()
  1514. _start_idle_led_timeout()
  1515. state.save()
  1516. logger.info(f"WLED IP updated: {request.wled_ip}")
  1517. return {"success": True, "wled_ip": state.wled_ip}
  1518. @app.get("/get_wled_ip")
  1519. async def get_wled_ip():
  1520. """Legacy endpoint for backward compatibility"""
  1521. if not state.wled_ip:
  1522. raise HTTPException(status_code=404, detail="No WLED IP set")
  1523. return {"success": True, "wled_ip": state.wled_ip}
  1524. @app.post("/set_led_config", deprecated=True, tags=["settings-deprecated"])
  1525. async def set_led_config(request: LEDConfigRequest):
  1526. """DEPRECATED: Use PATCH /api/settings instead. Configure LED provider (WLED, DW LEDs, or none)"""
  1527. if request.provider not in ["wled", "dw_leds", "none"]:
  1528. raise HTTPException(status_code=400, detail="Invalid provider. Must be 'wled', 'dw_leds', or 'none'")
  1529. state.led_provider = request.provider
  1530. if request.provider == "wled":
  1531. if not request.ip_address:
  1532. raise HTTPException(status_code=400, detail="IP address required for WLED")
  1533. state.wled_ip = request.ip_address
  1534. state.led_controller = LEDInterface("wled", request.ip_address)
  1535. logger.info(f"LED provider set to WLED at {request.ip_address}")
  1536. elif request.provider == "dw_leds":
  1537. # Check if hardware settings changed (requires restart)
  1538. old_gpio_pin = state.dw_led_gpio_pin
  1539. old_pixel_order = state.dw_led_pixel_order
  1540. hardware_changed = (
  1541. old_gpio_pin != (request.gpio_pin or 12) or
  1542. old_pixel_order != (request.pixel_order or "GRB")
  1543. )
  1544. # Stop existing DW LED controller if hardware settings changed
  1545. if hardware_changed and state.led_controller and state.led_provider == "dw_leds":
  1546. logger.info("Hardware settings changed, stopping existing LED controller...")
  1547. controller = state.led_controller.get_controller()
  1548. if controller and hasattr(controller, 'stop'):
  1549. try:
  1550. controller.stop()
  1551. logger.info("LED controller stopped successfully")
  1552. except Exception as e:
  1553. logger.error(f"Error stopping LED controller: {e}")
  1554. state.dw_led_num_leds = request.num_leds or 60
  1555. state.dw_led_gpio_pin = request.gpio_pin or 12
  1556. state.dw_led_pixel_order = request.pixel_order or "GRB"
  1557. state.dw_led_brightness = request.brightness or 35
  1558. state.wled_ip = None
  1559. # Create new LED controller with updated settings
  1560. state.led_controller = LEDInterface(
  1561. "dw_leds",
  1562. num_leds=state.dw_led_num_leds,
  1563. gpio_pin=state.dw_led_gpio_pin,
  1564. pixel_order=state.dw_led_pixel_order,
  1565. brightness=state.dw_led_brightness / 100.0,
  1566. speed=state.dw_led_speed,
  1567. intensity=state.dw_led_intensity
  1568. )
  1569. restart_msg = " (restarted)" if hardware_changed else ""
  1570. 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}")
  1571. # Check if initialization succeeded by checking status
  1572. status = state.led_controller.check_status()
  1573. if not status.get("connected", False) and status.get("error"):
  1574. error_msg = status["error"]
  1575. logger.warning(f"DW LED initialization failed: {error_msg}, but configuration saved for testing")
  1576. state.led_controller = None
  1577. # Keep the provider setting for testing purposes
  1578. # state.led_provider remains "dw_leds" so settings can be saved/tested
  1579. # Save state even with error
  1580. state.save()
  1581. # Return success with warning instead of error
  1582. return {
  1583. "success": True,
  1584. "warning": error_msg,
  1585. "hardware_available": False,
  1586. "provider": state.led_provider,
  1587. "dw_led_num_leds": state.dw_led_num_leds,
  1588. "dw_led_gpio_pin": state.dw_led_gpio_pin,
  1589. "dw_led_pixel_order": state.dw_led_pixel_order,
  1590. "dw_led_brightness": state.dw_led_brightness
  1591. }
  1592. else: # none
  1593. state.wled_ip = None
  1594. state.led_controller = None
  1595. logger.info("LED provider disabled")
  1596. # Show idle effect if controller is configured
  1597. if state.led_controller:
  1598. state.led_controller.effect_idle()
  1599. _start_idle_led_timeout()
  1600. state.save()
  1601. return {
  1602. "success": True,
  1603. "provider": state.led_provider,
  1604. "wled_ip": state.wled_ip,
  1605. "dw_led_num_leds": state.dw_led_num_leds,
  1606. "dw_led_gpio_pin": state.dw_led_gpio_pin,
  1607. "dw_led_brightness": state.dw_led_brightness
  1608. }
  1609. @app.get("/get_led_config", deprecated=True, tags=["settings-deprecated"])
  1610. async def get_led_config():
  1611. """DEPRECATED: Use GET /api/settings instead. Get current LED provider configuration"""
  1612. # Auto-detect provider for backward compatibility with existing installations
  1613. provider = state.led_provider
  1614. if not provider or provider == "none":
  1615. # If no provider set but we have IPs configured, auto-detect
  1616. if state.wled_ip:
  1617. provider = "wled"
  1618. state.led_provider = "wled"
  1619. state.save()
  1620. logger.info("Auto-detected WLED provider from existing configuration")
  1621. else:
  1622. provider = "none"
  1623. return {
  1624. "success": True,
  1625. "provider": provider,
  1626. "wled_ip": state.wled_ip,
  1627. "dw_led_num_leds": state.dw_led_num_leds,
  1628. "dw_led_gpio_pin": state.dw_led_gpio_pin,
  1629. "dw_led_pixel_order": state.dw_led_pixel_order,
  1630. "dw_led_brightness": state.dw_led_brightness,
  1631. "dw_led_idle_effect": state.dw_led_idle_effect,
  1632. "dw_led_playing_effect": state.dw_led_playing_effect
  1633. }
  1634. @app.post("/skip_pattern")
  1635. async def skip_pattern():
  1636. if not state.current_playlist:
  1637. raise HTTPException(status_code=400, detail="No playlist is currently running")
  1638. state.skip_requested = True
  1639. return {"success": True}
  1640. @app.get("/api/custom_clear_patterns", deprecated=True, tags=["settings-deprecated"])
  1641. async def get_custom_clear_patterns():
  1642. """Get the currently configured custom clear patterns."""
  1643. return {
  1644. "success": True,
  1645. "custom_clear_from_in": state.custom_clear_from_in,
  1646. "custom_clear_from_out": state.custom_clear_from_out
  1647. }
  1648. @app.post("/api/custom_clear_patterns", deprecated=True, tags=["settings-deprecated"])
  1649. async def set_custom_clear_patterns(request: dict):
  1650. """Set custom clear patterns for clear_from_in and clear_from_out."""
  1651. try:
  1652. # Validate that the patterns exist if they're provided
  1653. if "custom_clear_from_in" in request and request["custom_clear_from_in"]:
  1654. pattern_path = os.path.join(pattern_manager.THETA_RHO_DIR, request["custom_clear_from_in"])
  1655. if not os.path.exists(pattern_path):
  1656. raise HTTPException(status_code=400, detail=f"Pattern file not found: {request['custom_clear_from_in']}")
  1657. state.custom_clear_from_in = request["custom_clear_from_in"]
  1658. elif "custom_clear_from_in" in request:
  1659. state.custom_clear_from_in = None
  1660. if "custom_clear_from_out" in request and request["custom_clear_from_out"]:
  1661. pattern_path = os.path.join(pattern_manager.THETA_RHO_DIR, request["custom_clear_from_out"])
  1662. if not os.path.exists(pattern_path):
  1663. raise HTTPException(status_code=400, detail=f"Pattern file not found: {request['custom_clear_from_out']}")
  1664. state.custom_clear_from_out = request["custom_clear_from_out"]
  1665. elif "custom_clear_from_out" in request:
  1666. state.custom_clear_from_out = None
  1667. state.save()
  1668. logger.info(f"Custom clear patterns updated - in: {state.custom_clear_from_in}, out: {state.custom_clear_from_out}")
  1669. return {
  1670. "success": True,
  1671. "custom_clear_from_in": state.custom_clear_from_in,
  1672. "custom_clear_from_out": state.custom_clear_from_out
  1673. }
  1674. except Exception as e:
  1675. logger.error(f"Failed to set custom clear patterns: {str(e)}")
  1676. raise HTTPException(status_code=500, detail=str(e))
  1677. @app.get("/api/clear_pattern_speed", deprecated=True, tags=["settings-deprecated"])
  1678. async def get_clear_pattern_speed():
  1679. """Get the current clearing pattern speed setting."""
  1680. return {
  1681. "success": True,
  1682. "clear_pattern_speed": state.clear_pattern_speed,
  1683. "effective_speed": state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  1684. }
  1685. @app.post("/api/clear_pattern_speed", deprecated=True, tags=["settings-deprecated"])
  1686. async def set_clear_pattern_speed(request: dict):
  1687. """DEPRECATED: Use PATCH /api/settings instead. Set the clearing pattern speed."""
  1688. try:
  1689. # If speed is None or "none", use default behavior (state.speed)
  1690. speed_value = request.get("clear_pattern_speed")
  1691. if speed_value is None or speed_value == "none" or speed_value == "":
  1692. speed = None
  1693. else:
  1694. speed = int(speed_value)
  1695. # Validate speed range (same as regular speed limits) only if speed is not None
  1696. if speed is not None and not (50 <= speed <= 2000):
  1697. raise HTTPException(status_code=400, detail="Speed must be between 50 and 2000")
  1698. state.clear_pattern_speed = speed
  1699. state.save()
  1700. logger.info(f"Clear pattern speed set to {speed if speed is not None else 'default (state.speed)'}")
  1701. return {
  1702. "success": True,
  1703. "clear_pattern_speed": state.clear_pattern_speed,
  1704. "effective_speed": state.clear_pattern_speed if state.clear_pattern_speed is not None else state.speed
  1705. }
  1706. except ValueError:
  1707. raise HTTPException(status_code=400, detail="Invalid speed value")
  1708. except Exception as e:
  1709. logger.error(f"Failed to set clear pattern speed: {str(e)}")
  1710. raise HTTPException(status_code=500, detail=str(e))
  1711. @app.get("/api/app-name", deprecated=True, tags=["settings-deprecated"])
  1712. async def get_app_name():
  1713. """DEPRECATED: Use GET /api/settings instead. Get current application name."""
  1714. return {"app_name": state.app_name}
  1715. @app.post("/api/app-name", deprecated=True, tags=["settings-deprecated"])
  1716. async def set_app_name(request: dict):
  1717. """DEPRECATED: Use PATCH /api/settings instead. Update application name."""
  1718. app_name = request.get("app_name", "").strip()
  1719. if not app_name:
  1720. app_name = "Dune Weaver" # Reset to default if empty
  1721. state.app_name = app_name
  1722. state.save()
  1723. logger.info(f"Application name updated to: {app_name}")
  1724. return {"success": True, "app_name": app_name}
  1725. # ============================================================================
  1726. # Custom Branding Upload Endpoints
  1727. # ============================================================================
  1728. CUSTOM_BRANDING_DIR = os.path.join("static", "custom")
  1729. ALLOWED_IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".gif", ".webp", ".svg"}
  1730. MAX_LOGO_SIZE = 5 * 1024 * 1024 # 5MB
  1731. def generate_favicon_from_logo(logo_path: str, favicon_path: str) -> bool:
  1732. """Generate a circular-cropped favicon from the uploaded logo using PIL.
  1733. Creates a multi-size ICO file (16x16, 32x32, 48x48) with circular crop.
  1734. Returns True on success, False on failure.
  1735. """
  1736. try:
  1737. from PIL import Image, ImageDraw
  1738. def create_circular_image(img, size):
  1739. """Create a circular-cropped image at the specified size."""
  1740. # Resize to target size
  1741. resized = img.resize((size, size), Image.Resampling.LANCZOS)
  1742. # Create circular mask
  1743. mask = Image.new('L', (size, size), 0)
  1744. draw = ImageDraw.Draw(mask)
  1745. draw.ellipse((0, 0, size - 1, size - 1), fill=255)
  1746. # Apply circular mask - create transparent background
  1747. output = Image.new('RGBA', (size, size), (0, 0, 0, 0))
  1748. output.paste(resized, (0, 0), mask)
  1749. return output
  1750. with Image.open(logo_path) as img:
  1751. # Convert to RGBA if needed
  1752. if img.mode != 'RGBA':
  1753. img = img.convert('RGBA')
  1754. # Crop to square (center crop)
  1755. width, height = img.size
  1756. min_dim = min(width, height)
  1757. left = (width - min_dim) // 2
  1758. top = (height - min_dim) // 2
  1759. img = img.crop((left, top, left + min_dim, top + min_dim))
  1760. # Create circular images at each favicon size
  1761. sizes = [48, 32, 16]
  1762. circular_images = [create_circular_image(img, size) for size in sizes]
  1763. # Save as ICO - first image is the main one, rest are appended
  1764. circular_images[0].save(
  1765. favicon_path,
  1766. format='ICO',
  1767. append_images=circular_images[1:],
  1768. sizes=[(s, s) for s in sizes]
  1769. )
  1770. return True
  1771. except Exception as e:
  1772. logger.error(f"Failed to generate favicon: {str(e)}")
  1773. return False
  1774. @app.post("/api/upload-logo", tags=["settings"])
  1775. async def upload_logo(file: UploadFile = File(...)):
  1776. """Upload a custom logo image.
  1777. Supported formats: PNG, JPG, JPEG, GIF, WebP, SVG
  1778. Maximum size: 5MB
  1779. The uploaded file will be stored and used as the application logo.
  1780. A favicon will be automatically generated from the logo.
  1781. """
  1782. try:
  1783. # Validate file extension
  1784. file_ext = os.path.splitext(file.filename)[1].lower()
  1785. if file_ext not in ALLOWED_IMAGE_EXTENSIONS:
  1786. raise HTTPException(
  1787. status_code=400,
  1788. detail=f"Invalid file type. Allowed: {', '.join(ALLOWED_IMAGE_EXTENSIONS)}"
  1789. )
  1790. # Read and validate file size
  1791. content = await file.read()
  1792. if len(content) > MAX_LOGO_SIZE:
  1793. raise HTTPException(
  1794. status_code=400,
  1795. detail=f"File too large. Maximum size: {MAX_LOGO_SIZE // (1024*1024)}MB"
  1796. )
  1797. # Ensure custom branding directory exists
  1798. os.makedirs(CUSTOM_BRANDING_DIR, exist_ok=True)
  1799. # Delete old logo and favicon if they exist
  1800. if state.custom_logo:
  1801. old_logo_path = os.path.join(CUSTOM_BRANDING_DIR, state.custom_logo)
  1802. if os.path.exists(old_logo_path):
  1803. os.remove(old_logo_path)
  1804. # Also remove old favicon
  1805. old_favicon_path = os.path.join(CUSTOM_BRANDING_DIR, "favicon.ico")
  1806. if os.path.exists(old_favicon_path):
  1807. os.remove(old_favicon_path)
  1808. # Generate a unique filename to prevent caching issues
  1809. import uuid
  1810. filename = f"logo-{uuid.uuid4().hex[:8]}{file_ext}"
  1811. file_path = os.path.join(CUSTOM_BRANDING_DIR, filename)
  1812. # Save the logo file
  1813. with open(file_path, "wb") as f:
  1814. f.write(content)
  1815. # Generate favicon from logo (for non-SVG files)
  1816. favicon_generated = False
  1817. if file_ext != ".svg":
  1818. favicon_path = os.path.join(CUSTOM_BRANDING_DIR, "favicon.ico")
  1819. favicon_generated = generate_favicon_from_logo(file_path, favicon_path)
  1820. # Update state
  1821. state.custom_logo = filename
  1822. state.save()
  1823. logger.info(f"Custom logo uploaded: {filename}, favicon generated: {favicon_generated}")
  1824. return {
  1825. "success": True,
  1826. "filename": filename,
  1827. "url": f"/static/custom/{filename}",
  1828. "favicon_generated": favicon_generated
  1829. }
  1830. except HTTPException:
  1831. raise
  1832. except Exception as e:
  1833. logger.error(f"Error uploading logo: {str(e)}")
  1834. raise HTTPException(status_code=500, detail=str(e))
  1835. @app.delete("/api/custom-logo", tags=["settings"])
  1836. async def delete_custom_logo():
  1837. """Remove custom logo and favicon, reverting to defaults."""
  1838. try:
  1839. if state.custom_logo:
  1840. # Remove logo
  1841. logo_path = os.path.join(CUSTOM_BRANDING_DIR, state.custom_logo)
  1842. if os.path.exists(logo_path):
  1843. os.remove(logo_path)
  1844. # Remove generated favicon
  1845. favicon_path = os.path.join(CUSTOM_BRANDING_DIR, "favicon.ico")
  1846. if os.path.exists(favicon_path):
  1847. os.remove(favicon_path)
  1848. state.custom_logo = None
  1849. state.save()
  1850. logger.info("Custom logo and favicon removed")
  1851. return {"success": True}
  1852. except Exception as e:
  1853. logger.error(f"Error removing logo: {str(e)}")
  1854. raise HTTPException(status_code=500, detail=str(e))
  1855. @app.get("/api/mqtt-config", deprecated=True, tags=["settings-deprecated"])
  1856. async def get_mqtt_config():
  1857. """DEPRECATED: Use GET /api/settings instead. Get current MQTT configuration.
  1858. Note: Password is not returned for security reasons.
  1859. """
  1860. from modules.mqtt import get_mqtt_handler
  1861. handler = get_mqtt_handler()
  1862. return {
  1863. "enabled": state.mqtt_enabled,
  1864. "broker": state.mqtt_broker,
  1865. "port": state.mqtt_port,
  1866. "username": state.mqtt_username,
  1867. # Password is intentionally omitted for security
  1868. "has_password": bool(state.mqtt_password),
  1869. "client_id": state.mqtt_client_id,
  1870. "discovery_prefix": state.mqtt_discovery_prefix,
  1871. "device_id": state.mqtt_device_id,
  1872. "device_name": state.mqtt_device_name,
  1873. "connected": handler.is_connected if hasattr(handler, 'is_connected') else False,
  1874. "is_mock": handler.__class__.__name__ == 'MockMQTTHandler'
  1875. }
  1876. @app.post("/api/mqtt-config", deprecated=True, tags=["settings-deprecated"])
  1877. async def set_mqtt_config(request: dict):
  1878. """DEPRECATED: Use PATCH /api/settings instead. Update MQTT configuration. Requires restart to take effect."""
  1879. try:
  1880. # Update state with new values
  1881. state.mqtt_enabled = request.get("enabled", False)
  1882. state.mqtt_broker = (request.get("broker") or "").strip()
  1883. state.mqtt_port = int(request.get("port") or 1883)
  1884. state.mqtt_username = (request.get("username") or "").strip()
  1885. state.mqtt_password = (request.get("password") or "").strip()
  1886. state.mqtt_client_id = (request.get("client_id") or "dune_weaver").strip()
  1887. state.mqtt_discovery_prefix = (request.get("discovery_prefix") or "homeassistant").strip()
  1888. state.mqtt_device_id = (request.get("device_id") or "dune_weaver").strip()
  1889. state.mqtt_device_name = (request.get("device_name") or "Dune Weaver").strip()
  1890. # Validate required fields when enabled
  1891. if state.mqtt_enabled and not state.mqtt_broker:
  1892. return JSONResponse(
  1893. content={"success": False, "message": "Broker address is required when MQTT is enabled"},
  1894. status_code=400
  1895. )
  1896. state.save()
  1897. logger.info(f"MQTT configuration updated. Enabled: {state.mqtt_enabled}, Broker: {state.mqtt_broker}")
  1898. return {
  1899. "success": True,
  1900. "message": "MQTT configuration saved. Restart the application for changes to take effect.",
  1901. "requires_restart": True
  1902. }
  1903. except ValueError as e:
  1904. return JSONResponse(
  1905. content={"success": False, "message": f"Invalid value: {str(e)}"},
  1906. status_code=400
  1907. )
  1908. except Exception as e:
  1909. logger.error(f"Failed to update MQTT config: {str(e)}")
  1910. return JSONResponse(
  1911. content={"success": False, "message": str(e)},
  1912. status_code=500
  1913. )
  1914. @app.post("/api/mqtt-test")
  1915. async def test_mqtt_connection(request: dict):
  1916. """Test MQTT connection with provided settings."""
  1917. import paho.mqtt.client as mqtt_client
  1918. broker = (request.get("broker") or "").strip()
  1919. port = int(request.get("port") or 1883)
  1920. username = (request.get("username") or "").strip()
  1921. password = (request.get("password") or "").strip()
  1922. client_id = (request.get("client_id") or "dune_weaver_test").strip()
  1923. if not broker:
  1924. return JSONResponse(
  1925. content={"success": False, "message": "Broker address is required"},
  1926. status_code=400
  1927. )
  1928. try:
  1929. # Create a test client
  1930. client = mqtt_client.Client(client_id=client_id + "_test")
  1931. if username:
  1932. client.username_pw_set(username, password)
  1933. # Connection result
  1934. connection_result = {"connected": False, "error": None}
  1935. def on_connect(client, userdata, flags, rc):
  1936. if rc == 0:
  1937. connection_result["connected"] = True
  1938. else:
  1939. error_messages = {
  1940. 1: "Incorrect protocol version",
  1941. 2: "Invalid client identifier",
  1942. 3: "Server unavailable",
  1943. 4: "Bad username or password",
  1944. 5: "Not authorized"
  1945. }
  1946. connection_result["error"] = error_messages.get(rc, f"Connection failed with code {rc}")
  1947. client.on_connect = on_connect
  1948. # Try to connect with timeout
  1949. client.connect_async(broker, port, keepalive=10)
  1950. client.loop_start()
  1951. # Wait for connection result (max 5 seconds)
  1952. import time
  1953. start_time = time.time()
  1954. while time.time() - start_time < 5:
  1955. if connection_result["connected"] or connection_result["error"]:
  1956. break
  1957. await asyncio.sleep(0.1)
  1958. client.loop_stop()
  1959. client.disconnect()
  1960. if connection_result["connected"]:
  1961. return {"success": True, "message": "Successfully connected to MQTT broker"}
  1962. elif connection_result["error"]:
  1963. return JSONResponse(
  1964. content={"success": False, "message": connection_result["error"]},
  1965. status_code=400
  1966. )
  1967. else:
  1968. return JSONResponse(
  1969. content={"success": False, "message": "Connection timed out. Check broker address and port."},
  1970. status_code=400
  1971. )
  1972. except Exception as e:
  1973. logger.error(f"MQTT test connection failed: {str(e)}")
  1974. return JSONResponse(
  1975. content={"success": False, "message": str(e)},
  1976. status_code=500
  1977. )
  1978. def _read_and_encode_preview(cache_path: str) -> str:
  1979. """Read preview image from disk and encode as base64.
  1980. Combines file I/O and base64 encoding in a single function
  1981. to be run in executor, reducing context switches.
  1982. """
  1983. with open(cache_path, 'rb') as f:
  1984. image_data = f.read()
  1985. return base64.b64encode(image_data).decode('utf-8')
  1986. @app.post("/preview_thr_batch")
  1987. async def preview_thr_batch(request: dict):
  1988. start = time.time()
  1989. if not request.get("file_names"):
  1990. logger.warning("Batch preview request received without filenames")
  1991. raise HTTPException(status_code=400, detail="No file names provided")
  1992. file_names = request["file_names"]
  1993. if not isinstance(file_names, list):
  1994. raise HTTPException(status_code=400, detail="file_names must be a list")
  1995. headers = {
  1996. "Cache-Control": "public, max-age=3600", # Cache for 1 hour
  1997. "Content-Type": "application/json"
  1998. }
  1999. async def process_single_file(file_name):
  2000. """Process a single file and return its preview data."""
  2001. # Acquire semaphore to limit concurrent processing
  2002. async with preview_semaphore:
  2003. t1 = time.time()
  2004. try:
  2005. # Normalize file path for cross-platform compatibility
  2006. normalized_file_name = normalize_file_path(file_name)
  2007. pattern_file_path = os.path.join(pattern_manager.THETA_RHO_DIR, normalized_file_name)
  2008. # Check file existence asynchronously
  2009. exists = await asyncio.to_thread(os.path.exists, pattern_file_path)
  2010. if not exists:
  2011. logger.warning(f"Pattern file not found: {pattern_file_path}")
  2012. return file_name, {"error": "Pattern file not found"}
  2013. cache_path = get_cache_path(normalized_file_name)
  2014. # Check cache existence asynchronously
  2015. cache_exists = await asyncio.to_thread(os.path.exists, cache_path)
  2016. if not cache_exists:
  2017. logger.info(f"Cache miss for {file_name}. Generating preview...")
  2018. success = await generate_image_preview(normalized_file_name)
  2019. cache_exists_after = await asyncio.to_thread(os.path.exists, cache_path)
  2020. if not success or not cache_exists_after:
  2021. logger.error(f"Failed to generate or find preview for {file_name}")
  2022. return file_name, {"error": "Failed to generate preview"}
  2023. metadata = get_pattern_metadata(normalized_file_name)
  2024. if metadata:
  2025. first_coord_obj = metadata.get('first_coordinate')
  2026. last_coord_obj = metadata.get('last_coordinate')
  2027. else:
  2028. logger.debug(f"Metadata cache miss for {file_name}, parsing file")
  2029. # Use process pool for CPU-intensive parsing
  2030. loop = asyncio.get_running_loop()
  2031. coordinates = await loop.run_in_executor(pool_module.get_pool(), parse_theta_rho_file, pattern_file_path)
  2032. first_coord = coordinates[0] if coordinates else None
  2033. last_coord = coordinates[-1] if coordinates else None
  2034. first_coord_obj = {"x": first_coord[0], "y": first_coord[1]} if first_coord else None
  2035. last_coord_obj = {"x": last_coord[0], "y": last_coord[1]} if last_coord else None
  2036. # Read image file and encode in executor to avoid blocking event loop
  2037. loop = asyncio.get_running_loop()
  2038. image_b64 = await loop.run_in_executor(None, _read_and_encode_preview, cache_path)
  2039. result = {
  2040. "image_data": f"data:image/webp;base64,{image_b64}",
  2041. "first_coordinate": first_coord_obj,
  2042. "last_coordinate": last_coord_obj
  2043. }
  2044. logger.debug(f"Processed {file_name} in {time.time() - t1:.2f}s")
  2045. return file_name, result
  2046. except Exception as e:
  2047. logger.error(f"Error processing {file_name}: {str(e)}")
  2048. return file_name, {"error": str(e)}
  2049. # Process all files concurrently
  2050. tasks = [process_single_file(file_name) for file_name in file_names]
  2051. file_results = await asyncio.gather(*tasks)
  2052. # Convert results to dictionary
  2053. results = dict(file_results)
  2054. logger.info(f"Total batch processing time: {time.time() - start:.2f}s for {len(file_names)} files")
  2055. return JSONResponse(content=results, headers=headers)
  2056. @app.get("/playlists")
  2057. async def playlists(request: Request):
  2058. logger.debug("Rendering playlists page")
  2059. return templates.TemplateResponse("playlists.html", {"request": request, "app_name": state.app_name, "custom_logo": state.custom_logo})
  2060. @app.get("/image2sand")
  2061. async def image2sand(request: Request):
  2062. return templates.TemplateResponse("image2sand.html", {"request": request, "app_name": state.app_name, "custom_logo": state.custom_logo})
  2063. @app.get("/led")
  2064. async def led_control_page(request: Request):
  2065. return templates.TemplateResponse("led.html", {"request": request, "app_name": state.app_name, "custom_logo": state.custom_logo})
  2066. # DW LED control endpoints
  2067. @app.get("/api/dw_leds/status")
  2068. async def dw_leds_status():
  2069. """Get DW LED controller status"""
  2070. if not state.led_controller or state.led_provider != "dw_leds":
  2071. return {"connected": False, "message": "DW LEDs not configured"}
  2072. try:
  2073. return state.led_controller.check_status()
  2074. except Exception as e:
  2075. logger.error(f"Failed to check DW LED status: {str(e)}")
  2076. return {"connected": False, "message": str(e)}
  2077. @app.post("/api/dw_leds/power")
  2078. async def dw_leds_power(request: dict):
  2079. """Control DW LED power (0=off, 1=on, 2=toggle)"""
  2080. if not state.led_controller or state.led_provider != "dw_leds":
  2081. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2082. state_value = request.get("state", 1)
  2083. if state_value not in [0, 1, 2]:
  2084. raise HTTPException(status_code=400, detail="State must be 0 (off), 1 (on), or 2 (toggle)")
  2085. try:
  2086. result = state.led_controller.set_power(state_value)
  2087. # Reset idle timeout when LEDs are manually powered on (only if idle timeout is enabled)
  2088. # This prevents idle timeout from immediately turning them back off
  2089. if state_value in [1, 2] and state.dw_led_idle_timeout_enabled: # Power on or toggle
  2090. state.dw_led_last_activity_time = time.time()
  2091. logger.debug(f"LED activity time reset due to manual power on")
  2092. return result
  2093. except Exception as e:
  2094. logger.error(f"Failed to set DW LED power: {str(e)}")
  2095. raise HTTPException(status_code=500, detail=str(e))
  2096. @app.post("/api/dw_leds/brightness")
  2097. async def dw_leds_brightness(request: dict):
  2098. """Set DW LED brightness (0-100)"""
  2099. if not state.led_controller or state.led_provider != "dw_leds":
  2100. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2101. value = request.get("value", 50)
  2102. if not 0 <= value <= 100:
  2103. raise HTTPException(status_code=400, detail="Brightness must be between 0 and 100")
  2104. try:
  2105. controller = state.led_controller.get_controller()
  2106. result = controller.set_brightness(value)
  2107. # Update state if successful
  2108. if result.get("connected"):
  2109. state.dw_led_brightness = value
  2110. state.save()
  2111. return result
  2112. except Exception as e:
  2113. logger.error(f"Failed to set DW LED brightness: {str(e)}")
  2114. raise HTTPException(status_code=500, detail=str(e))
  2115. @app.post("/api/dw_leds/color")
  2116. async def dw_leds_color(request: dict):
  2117. """Set solid color (manual UI control - always powers on LEDs)"""
  2118. if not state.led_controller or state.led_provider != "dw_leds":
  2119. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2120. # Accept both formats: {"r": 255, "g": 0, "b": 0} or {"color": [255, 0, 0]}
  2121. if "color" in request:
  2122. color = request["color"]
  2123. if not isinstance(color, list) or len(color) != 3:
  2124. raise HTTPException(status_code=400, detail="Color must be [R, G, B] array")
  2125. r, g, b = color[0], color[1], color[2]
  2126. elif "r" in request and "g" in request and "b" in request:
  2127. r = request["r"]
  2128. g = request["g"]
  2129. b = request["b"]
  2130. else:
  2131. raise HTTPException(status_code=400, detail="Color must include r, g, b fields or color array")
  2132. try:
  2133. controller = state.led_controller.get_controller()
  2134. # Power on LEDs when user manually sets color via UI
  2135. controller.set_power(1)
  2136. # Reset idle timeout for manual interaction (only if idle timeout is enabled)
  2137. if state.dw_led_idle_timeout_enabled:
  2138. state.dw_led_last_activity_time = time.time()
  2139. return controller.set_color(r, g, b)
  2140. except Exception as e:
  2141. logger.error(f"Failed to set DW LED color: {str(e)}")
  2142. raise HTTPException(status_code=500, detail=str(e))
  2143. @app.post("/api/dw_leds/colors")
  2144. async def dw_leds_colors(request: dict):
  2145. """Set effect colors (color1, color2, color3) - manual UI control - always powers on LEDs"""
  2146. if not state.led_controller or state.led_provider != "dw_leds":
  2147. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2148. # Parse colors from request
  2149. color1 = None
  2150. color2 = None
  2151. color3 = None
  2152. if "color1" in request:
  2153. c = request["color1"]
  2154. if isinstance(c, list) and len(c) == 3:
  2155. color1 = tuple(c)
  2156. else:
  2157. raise HTTPException(status_code=400, detail="color1 must be [R, G, B] array")
  2158. if "color2" in request:
  2159. c = request["color2"]
  2160. if isinstance(c, list) and len(c) == 3:
  2161. color2 = tuple(c)
  2162. else:
  2163. raise HTTPException(status_code=400, detail="color2 must be [R, G, B] array")
  2164. if "color3" in request:
  2165. c = request["color3"]
  2166. if isinstance(c, list) and len(c) == 3:
  2167. color3 = tuple(c)
  2168. else:
  2169. raise HTTPException(status_code=400, detail="color3 must be [R, G, B] array")
  2170. if not any([color1, color2, color3]):
  2171. raise HTTPException(status_code=400, detail="Must provide at least one color")
  2172. try:
  2173. controller = state.led_controller.get_controller()
  2174. # Power on LEDs when user manually sets colors via UI
  2175. controller.set_power(1)
  2176. # Reset idle timeout for manual interaction (only if idle timeout is enabled)
  2177. if state.dw_led_idle_timeout_enabled:
  2178. state.dw_led_last_activity_time = time.time()
  2179. return controller.set_colors(color1=color1, color2=color2, color3=color3)
  2180. except Exception as e:
  2181. logger.error(f"Failed to set DW LED colors: {str(e)}")
  2182. raise HTTPException(status_code=500, detail=str(e))
  2183. @app.get("/api/dw_leds/effects")
  2184. async def dw_leds_effects():
  2185. """Get list of available effects"""
  2186. if not state.led_controller or state.led_provider != "dw_leds":
  2187. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2188. try:
  2189. controller = state.led_controller.get_controller()
  2190. effects = controller.get_effects()
  2191. # Convert tuples to lists for JSON serialization
  2192. effects_list = [[eid, name] for eid, name in effects]
  2193. return {
  2194. "success": True,
  2195. "effects": effects_list
  2196. }
  2197. except Exception as e:
  2198. logger.error(f"Failed to get DW LED effects: {str(e)}")
  2199. raise HTTPException(status_code=500, detail=str(e))
  2200. @app.get("/api/dw_leds/palettes")
  2201. async def dw_leds_palettes():
  2202. """Get list of available palettes"""
  2203. if not state.led_controller or state.led_provider != "dw_leds":
  2204. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2205. try:
  2206. controller = state.led_controller.get_controller()
  2207. palettes = controller.get_palettes()
  2208. # Convert tuples to lists for JSON serialization
  2209. palettes_list = [[pid, name] for pid, name in palettes]
  2210. return {
  2211. "success": True,
  2212. "palettes": palettes_list
  2213. }
  2214. except Exception as e:
  2215. logger.error(f"Failed to get DW LED palettes: {str(e)}")
  2216. raise HTTPException(status_code=500, detail=str(e))
  2217. @app.post("/api/dw_leds/effect")
  2218. async def dw_leds_effect(request: dict):
  2219. """Set effect by ID (manual UI control - always powers on LEDs)"""
  2220. if not state.led_controller or state.led_provider != "dw_leds":
  2221. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2222. effect_id = request.get("effect_id", 0)
  2223. speed = request.get("speed")
  2224. intensity = request.get("intensity")
  2225. try:
  2226. controller = state.led_controller.get_controller()
  2227. # Power on LEDs when user manually sets effect via UI
  2228. controller.set_power(1)
  2229. # Reset idle timeout for manual interaction (only if idle timeout is enabled)
  2230. if state.dw_led_idle_timeout_enabled:
  2231. state.dw_led_last_activity_time = time.time()
  2232. return controller.set_effect(effect_id, speed=speed, intensity=intensity)
  2233. except Exception as e:
  2234. logger.error(f"Failed to set DW LED effect: {str(e)}")
  2235. raise HTTPException(status_code=500, detail=str(e))
  2236. @app.post("/api/dw_leds/palette")
  2237. async def dw_leds_palette(request: dict):
  2238. """Set palette by ID (manual UI control - always powers on LEDs)"""
  2239. if not state.led_controller or state.led_provider != "dw_leds":
  2240. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2241. palette_id = request.get("palette_id", 0)
  2242. try:
  2243. controller = state.led_controller.get_controller()
  2244. # Power on LEDs when user manually sets palette via UI
  2245. controller.set_power(1)
  2246. # Reset idle timeout for manual interaction (only if idle timeout is enabled)
  2247. if state.dw_led_idle_timeout_enabled:
  2248. state.dw_led_last_activity_time = time.time()
  2249. return controller.set_palette(palette_id)
  2250. except Exception as e:
  2251. logger.error(f"Failed to set DW LED palette: {str(e)}")
  2252. raise HTTPException(status_code=500, detail=str(e))
  2253. @app.post("/api/dw_leds/speed")
  2254. async def dw_leds_speed(request: dict):
  2255. """Set effect speed (0-255)"""
  2256. if not state.led_controller or state.led_provider != "dw_leds":
  2257. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2258. value = request.get("speed", 128)
  2259. if not 0 <= value <= 255:
  2260. raise HTTPException(status_code=400, detail="Speed must be between 0 and 255")
  2261. try:
  2262. controller = state.led_controller.get_controller()
  2263. result = controller.set_speed(value)
  2264. # Save speed to state
  2265. state.dw_led_speed = value
  2266. state.save()
  2267. return result
  2268. except Exception as e:
  2269. logger.error(f"Failed to set DW LED speed: {str(e)}")
  2270. raise HTTPException(status_code=500, detail=str(e))
  2271. @app.post("/api/dw_leds/intensity")
  2272. async def dw_leds_intensity(request: dict):
  2273. """Set effect intensity (0-255)"""
  2274. if not state.led_controller or state.led_provider != "dw_leds":
  2275. raise HTTPException(status_code=400, detail="DW LEDs not configured")
  2276. value = request.get("intensity", 128)
  2277. if not 0 <= value <= 255:
  2278. raise HTTPException(status_code=400, detail="Intensity must be between 0 and 255")
  2279. try:
  2280. controller = state.led_controller.get_controller()
  2281. result = controller.set_intensity(value)
  2282. # Save intensity to state
  2283. state.dw_led_intensity = value
  2284. state.save()
  2285. return result
  2286. except Exception as e:
  2287. logger.error(f"Failed to set DW LED intensity: {str(e)}")
  2288. raise HTTPException(status_code=500, detail=str(e))
  2289. @app.post("/api/dw_leds/save_effect_settings")
  2290. async def dw_leds_save_effect_settings(request: dict):
  2291. """Save current LED settings as idle or playing effect"""
  2292. effect_type = request.get("type") # 'idle' or 'playing'
  2293. settings = {
  2294. "effect_id": request.get("effect_id"),
  2295. "palette_id": request.get("palette_id"),
  2296. "speed": request.get("speed"),
  2297. "intensity": request.get("intensity"),
  2298. "color1": request.get("color1"),
  2299. "color2": request.get("color2"),
  2300. "color3": request.get("color3")
  2301. }
  2302. if effect_type == "idle":
  2303. state.dw_led_idle_effect = settings
  2304. elif effect_type == "playing":
  2305. state.dw_led_playing_effect = settings
  2306. else:
  2307. raise HTTPException(status_code=400, detail="Invalid effect type. Must be 'idle' or 'playing'")
  2308. state.save()
  2309. logger.info(f"DW LED {effect_type} effect settings saved: {settings}")
  2310. return {"success": True, "type": effect_type, "settings": settings}
  2311. @app.post("/api/dw_leds/clear_effect_settings")
  2312. async def dw_leds_clear_effect_settings(request: dict):
  2313. """Clear idle or playing effect settings"""
  2314. effect_type = request.get("type") # 'idle' or 'playing'
  2315. if effect_type == "idle":
  2316. state.dw_led_idle_effect = None
  2317. elif effect_type == "playing":
  2318. state.dw_led_playing_effect = None
  2319. else:
  2320. raise HTTPException(status_code=400, detail="Invalid effect type. Must be 'idle' or 'playing'")
  2321. state.save()
  2322. logger.info(f"DW LED {effect_type} effect settings cleared")
  2323. return {"success": True, "type": effect_type}
  2324. @app.get("/api/dw_leds/get_effect_settings")
  2325. async def dw_leds_get_effect_settings():
  2326. """Get saved idle and playing effect settings"""
  2327. return {
  2328. "idle_effect": state.dw_led_idle_effect,
  2329. "playing_effect": state.dw_led_playing_effect
  2330. }
  2331. @app.post("/api/dw_leds/idle_timeout")
  2332. async def dw_leds_set_idle_timeout(request: dict):
  2333. """Configure LED idle timeout settings"""
  2334. enabled = request.get("enabled", False)
  2335. minutes = request.get("minutes", 30)
  2336. # Validate minutes (between 1 and 1440 - 24 hours)
  2337. if minutes < 1 or minutes > 1440:
  2338. raise HTTPException(status_code=400, detail="Timeout must be between 1 and 1440 minutes")
  2339. state.dw_led_idle_timeout_enabled = enabled
  2340. state.dw_led_idle_timeout_minutes = minutes
  2341. # Reset activity time when settings change
  2342. import time
  2343. state.dw_led_last_activity_time = time.time()
  2344. state.save()
  2345. logger.info(f"DW LED idle timeout configured: enabled={enabled}, minutes={minutes}")
  2346. return {
  2347. "success": True,
  2348. "enabled": enabled,
  2349. "minutes": minutes
  2350. }
  2351. @app.get("/api/dw_leds/idle_timeout")
  2352. async def dw_leds_get_idle_timeout():
  2353. """Get LED idle timeout settings"""
  2354. import time
  2355. # Calculate remaining time if timeout is active
  2356. remaining_minutes = None
  2357. if state.dw_led_idle_timeout_enabled and state.dw_led_last_activity_time:
  2358. elapsed_seconds = time.time() - state.dw_led_last_activity_time
  2359. timeout_seconds = state.dw_led_idle_timeout_minutes * 60
  2360. remaining_seconds = max(0, timeout_seconds - elapsed_seconds)
  2361. remaining_minutes = round(remaining_seconds / 60, 1)
  2362. return {
  2363. "enabled": state.dw_led_idle_timeout_enabled,
  2364. "minutes": state.dw_led_idle_timeout_minutes,
  2365. "remaining_minutes": remaining_minutes
  2366. }
  2367. @app.get("/table_control")
  2368. async def table_control(request: Request):
  2369. return templates.TemplateResponse("table_control.html", {"request": request, "app_name": state.app_name, "custom_logo": state.custom_logo})
  2370. @app.get("/cache-progress")
  2371. async def get_cache_progress_endpoint():
  2372. """Get the current cache generation progress."""
  2373. from modules.core.cache_manager import get_cache_progress
  2374. return get_cache_progress()
  2375. @app.post("/rebuild_cache")
  2376. async def rebuild_cache_endpoint():
  2377. """Trigger a rebuild of the pattern cache."""
  2378. try:
  2379. from modules.core.cache_manager import rebuild_cache
  2380. await rebuild_cache()
  2381. return {"success": True, "message": "Cache rebuild completed successfully"}
  2382. except Exception as e:
  2383. logger.error(f"Failed to rebuild cache: {str(e)}")
  2384. raise HTTPException(status_code=500, detail=str(e))
  2385. def signal_handler(signum, frame):
  2386. """Handle shutdown signals gracefully."""
  2387. logger.info("Received shutdown signal, cleaning up...")
  2388. try:
  2389. # Turn off all LEDs on shutdown
  2390. if state.led_controller:
  2391. state.led_controller.set_power(0)
  2392. # Shutdown process pool to prevent semaphore leaks
  2393. pool_module.shutdown_pool(wait=False, cancel_futures=True)
  2394. # Stop pattern manager motion controller
  2395. pattern_manager.motion_controller.stop()
  2396. # Set stop flags to halt any running patterns
  2397. state.stop_requested = True
  2398. state.pause_requested = False
  2399. state.save()
  2400. logger.info("Cleanup completed")
  2401. except Exception as e:
  2402. logger.error(f"Error during cleanup: {str(e)}")
  2403. finally:
  2404. logger.info("Exiting application...")
  2405. # Use os._exit after cleanup is complete to avoid async stack tracebacks
  2406. # This is safe because we've already: shut down process pool, stopped motion controller, saved state
  2407. os._exit(0)
  2408. @app.get("/api/version")
  2409. async def get_version_info(force_refresh: bool = False):
  2410. """Get current and latest version information
  2411. Args:
  2412. force_refresh: If true, bypass cache and fetch fresh data from GitHub
  2413. """
  2414. try:
  2415. version_info = await version_manager.get_version_info(force_refresh=force_refresh)
  2416. return JSONResponse(content=version_info)
  2417. except Exception as e:
  2418. logger.error(f"Error getting version info: {e}")
  2419. return JSONResponse(
  2420. content={
  2421. "current": await version_manager.get_current_version(),
  2422. "latest": await version_manager.get_current_version(),
  2423. "update_available": False,
  2424. "error": "Unable to check for updates"
  2425. },
  2426. status_code=200
  2427. )
  2428. @app.post("/api/update")
  2429. async def trigger_update():
  2430. """Trigger software update (placeholder for future implementation)"""
  2431. try:
  2432. # For now, just return the GitHub release URL
  2433. version_info = await version_manager.get_version_info()
  2434. if version_info.get("latest_release"):
  2435. return JSONResponse(content={
  2436. "success": False,
  2437. "message": "Automatic updates not implemented yet",
  2438. "manual_update_url": version_info["latest_release"].get("html_url"),
  2439. "instructions": "Please visit the GitHub release page to download and install the update manually"
  2440. })
  2441. else:
  2442. return JSONResponse(content={
  2443. "success": False,
  2444. "message": "No updates available"
  2445. })
  2446. except Exception as e:
  2447. logger.error(f"Error triggering update: {e}")
  2448. return JSONResponse(
  2449. content={"success": False, "message": "Failed to check for updates"},
  2450. status_code=500
  2451. )
  2452. @app.post("/api/system/shutdown")
  2453. async def shutdown_system():
  2454. """Shutdown the system"""
  2455. try:
  2456. logger.warning("Shutdown initiated via API")
  2457. # Schedule shutdown command after a short delay to allow response to be sent
  2458. def delayed_shutdown():
  2459. time.sleep(2) # Give time for response to be sent
  2460. try:
  2461. # Use systemctl to shutdown the host (via mounted systemd socket)
  2462. subprocess.run(["systemctl", "poweroff"], check=True)
  2463. logger.info("Host shutdown command executed successfully via systemctl")
  2464. except FileNotFoundError:
  2465. logger.error("systemctl command not found - ensure systemd volumes are mounted")
  2466. except Exception as e:
  2467. logger.error(f"Error executing host shutdown command: {e}")
  2468. import threading
  2469. shutdown_thread = threading.Thread(target=delayed_shutdown)
  2470. shutdown_thread.start()
  2471. return {"success": True, "message": "System shutdown initiated"}
  2472. except Exception as e:
  2473. logger.error(f"Error initiating shutdown: {e}")
  2474. return JSONResponse(
  2475. content={"success": False, "message": str(e)},
  2476. status_code=500
  2477. )
  2478. @app.post("/api/system/restart")
  2479. async def restart_system():
  2480. """Restart the Docker containers using docker compose"""
  2481. try:
  2482. logger.warning("Restart initiated via API")
  2483. # Schedule restart command after a short delay to allow response to be sent
  2484. def delayed_restart():
  2485. time.sleep(2) # Give time for response to be sent
  2486. try:
  2487. # Use docker restart directly with container name
  2488. # This is simpler and doesn't require the compose file path
  2489. subprocess.run(["docker", "restart", "dune-weaver"], check=True)
  2490. logger.info("Docker restart command executed successfully")
  2491. except FileNotFoundError:
  2492. logger.error("docker command not found")
  2493. except Exception as e:
  2494. logger.error(f"Error executing docker restart: {e}")
  2495. import threading
  2496. restart_thread = threading.Thread(target=delayed_restart)
  2497. restart_thread.start()
  2498. return {"success": True, "message": "System restart initiated"}
  2499. except Exception as e:
  2500. logger.error(f"Error initiating restart: {e}")
  2501. return JSONResponse(
  2502. content={"success": False, "message": str(e)},
  2503. status_code=500
  2504. )
  2505. def entrypoint():
  2506. import uvicorn
  2507. logger.info("Starting FastAPI server on port 8080...")
  2508. uvicorn.run(app, host="0.0.0.0", port=8080, workers=1) # Set workers to 1 to avoid multiple signal handlers
  2509. if __name__ == "__main__":
  2510. entrypoint()