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