main.py 120 KB

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