main.py 156 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361
  1. import asyncio
  2. import logging
  3. from contextlib import asynccontextmanager
  4. from datetime import datetime, timedelta, timezone
  5. from logging.handlers import RotatingFileHandler
  6. # =============================================================================
  7. # Dependency Check - runs before other imports to give helpful error messages
  8. # =============================================================================
  9. def _start_error_server(missing_packages: list):
  10. """Start a minimal HTTP server to display dependency errors in browser."""
  11. import os
  12. import signal
  13. from http.server import BaseHTTPRequestHandler, HTTPServer
  14. packages_html = "".join(f"<li><code>{p}</code></li>" for p in missing_packages)
  15. html = f"""<!DOCTYPE html>
  16. <html>
  17. <head>
  18. <title>Bambuddy - Setup Required</title>
  19. <style>
  20. body {{
  21. font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  22. background: #0f172a; color: #e2e8f0;
  23. display: flex; justify-content: center; align-items: center;
  24. min-height: 100vh; margin: 0; padding: 20px; box-sizing: border-box;
  25. }}
  26. .container {{
  27. background: #1e293b; border-radius: 12px; padding: 40px;
  28. max-width: 600px; text-align: center; box-shadow: 0 4px 20px rgba(0,0,0,0.3);
  29. }}
  30. h1 {{ color: #f87171; margin-bottom: 10px; }}
  31. h2 {{ color: #94a3b8; font-weight: normal; margin-top: 0; }}
  32. .packages {{
  33. background: #0f172a; border-radius: 8px; padding: 20px;
  34. margin: 20px 0; text-align: left;
  35. }}
  36. .packages ul {{ margin: 0; padding-left: 20px; }}
  37. .packages li {{ color: #fbbf24; margin: 8px 0; }}
  38. .command {{
  39. background: #0f172a; border-radius: 8px; padding: 15px 20px;
  40. margin: 15px 0; font-family: monospace; color: #4ade80;
  41. text-align: left; overflow-x: auto;
  42. }}
  43. .note {{ color: #94a3b8; font-size: 14px; margin-top: 20px; }}
  44. </style>
  45. </head>
  46. <body>
  47. <div class="container">
  48. <h1>Setup Required</h1>
  49. <h2>Missing Python packages</h2>
  50. <div class="packages"><ul>{packages_html}</ul></div>
  51. <p>To fix, run this command on your server:</p>
  52. <div class="command">pip install -r requirements.txt</div>
  53. <p>Or if using a virtual environment:</p>
  54. <div class="command">./venv/bin/pip install -r requirements.txt</div>
  55. <p class="note">After installing, restart Bambuddy:<br>
  56. <code>sudo systemctl restart bambuddy</code></p>
  57. </div>
  58. </body>
  59. </html>"""
  60. class ErrorHandler(BaseHTTPRequestHandler):
  61. def do_GET(self):
  62. self.send_response(503)
  63. self.send_header("Content-type", "text/html")
  64. self.end_headers()
  65. self.wfile.write(html.encode())
  66. def log_message(self, format, *args):
  67. print(f"[Error Server] {args[0]}")
  68. port = int(os.environ.get("PORT", 8000))
  69. print(f"\nStarting error server on http://0.0.0.0:{port}")
  70. print("Visit this URL in your browser to see the error details.\n")
  71. server = HTTPServer(("0.0.0.0", port), ErrorHandler) # nosec B104
  72. def shutdown(signum, frame):
  73. print("\nShutting down error server...")
  74. raise SystemExit(0)
  75. signal.signal(signal.SIGTERM, shutdown)
  76. signal.signal(signal.SIGINT, shutdown)
  77. server.serve_forever()
  78. def check_dependencies():
  79. """Check that all required packages are installed."""
  80. missing = []
  81. # Map of import name -> package name (for pip install)
  82. required = {
  83. "jwt": "PyJWT",
  84. "fastapi": "fastapi",
  85. "uvicorn": "uvicorn",
  86. "sqlalchemy": "sqlalchemy",
  87. "aiosqlite": "aiosqlite",
  88. "pydantic": "pydantic",
  89. "paho.mqtt": "paho-mqtt",
  90. }
  91. for module, package in required.items():
  92. try:
  93. __import__(module)
  94. except ImportError:
  95. missing.append(package)
  96. if missing:
  97. print("\n" + "=" * 60)
  98. print("ERROR: Missing required Python packages!")
  99. print("=" * 60)
  100. print(f"\nMissing packages: {', '.join(missing)}")
  101. print("\nTo fix, run:")
  102. print(" pip install -r requirements.txt")
  103. print("\nOr if using a virtual environment:")
  104. print(" ./venv/bin/pip install -r requirements.txt")
  105. print("=" * 60 + "\n")
  106. _start_error_server(missing)
  107. check_dependencies()
  108. # =============================================================================
  109. from fastapi import FastAPI
  110. # Import settings first for logging configuration
  111. from backend.app.core.config import APP_VERSION, settings as app_settings
  112. # Configure logging based on settings
  113. # DEBUG=true -> DEBUG level, else use LOG_LEVEL setting
  114. log_level_str = "DEBUG" if app_settings.debug else app_settings.log_level.upper()
  115. log_level = getattr(logging, log_level_str, logging.INFO)
  116. log_format = "%(asctime)s %(levelname)s [%(name)s] %(message)s"
  117. # Create root logger
  118. root_logger = logging.getLogger()
  119. root_logger.setLevel(log_level)
  120. # Console handler - always enabled
  121. console_handler = logging.StreamHandler()
  122. console_handler.setLevel(log_level)
  123. console_handler.setFormatter(logging.Formatter(log_format))
  124. root_logger.addHandler(console_handler)
  125. # File handler - only in production or if explicitly enabled
  126. if app_settings.log_to_file:
  127. log_file = app_settings.log_dir / "bambuddy.log"
  128. file_handler = RotatingFileHandler(
  129. log_file,
  130. maxBytes=5 * 1024 * 1024, # 5MB
  131. backupCount=3,
  132. encoding="utf-8",
  133. )
  134. file_handler.setLevel(log_level)
  135. file_handler.setFormatter(logging.Formatter(log_format))
  136. root_logger.addHandler(file_handler)
  137. logging.info("Logging to file: %s", log_file)
  138. # Reduce noise from third-party libraries in production
  139. if not app_settings.debug:
  140. logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
  141. logging.getLogger("httpcore").setLevel(logging.WARNING)
  142. logging.getLogger("httpx").setLevel(logging.WARNING)
  143. logging.getLogger("paho.mqtt").setLevel(logging.WARNING)
  144. logging.info("Bambuddy starting - debug=%s, log_level=%s", app_settings.debug, log_level_str)
  145. from fastapi.responses import FileResponse
  146. from fastapi.staticfiles import StaticFiles
  147. from sqlalchemy import delete, or_, select
  148. from backend.app.api.routes import (
  149. ams_history,
  150. api_keys,
  151. archives,
  152. auth,
  153. camera,
  154. cloud,
  155. discovery,
  156. external_links,
  157. filaments,
  158. firmware,
  159. github_backup,
  160. groups,
  161. inventory,
  162. kprofiles,
  163. library,
  164. local_presets,
  165. maintenance,
  166. metrics,
  167. notification_templates,
  168. notifications,
  169. pending_uploads,
  170. print_queue,
  171. printers,
  172. projects,
  173. settings as settings_routes,
  174. smart_plugs,
  175. spoolman,
  176. support,
  177. system,
  178. updates,
  179. users,
  180. webhook,
  181. websocket,
  182. )
  183. from backend.app.api.routes.maintenance import _get_printer_maintenance_internal, ensure_default_types
  184. from backend.app.api.routes.support import init_debug_logging
  185. from backend.app.core.database import async_session, init_db
  186. from backend.app.core.websocket import ws_manager
  187. from backend.app.models.smart_plug import SmartPlug
  188. from backend.app.services.archive import ArchiveService
  189. from backend.app.services.bambu_ftp import download_file_async, get_ftp_retry_settings, with_ftp_retry
  190. from backend.app.services.bambu_mqtt import PrinterState
  191. from backend.app.services.github_backup import github_backup_service
  192. from backend.app.services.homeassistant import homeassistant_service
  193. from backend.app.services.mqtt_relay import mqtt_relay
  194. from backend.app.services.mqtt_smart_plug import mqtt_smart_plug_service
  195. from backend.app.services.notification_service import notification_service
  196. from backend.app.services.print_scheduler import scheduler as print_scheduler
  197. from backend.app.services.printer_manager import (
  198. init_printer_connections,
  199. printer_manager,
  200. printer_state_to_dict,
  201. )
  202. from backend.app.services.smart_plug_manager import smart_plug_manager
  203. from backend.app.services.spoolman import close_spoolman_client, get_spoolman_client, init_spoolman_client
  204. from backend.app.services.spoolman_tracking import (
  205. cleanup_tracking as _cleanup_spoolman_tracking,
  206. report_usage as _report_spoolman_usage,
  207. store_print_data as _store_spoolman_print_data,
  208. )
  209. from backend.app.services.tasmota import tasmota_service
  210. # Track active prints: {(printer_id, filename): archive_id}
  211. _active_prints: dict[tuple[int, str], int] = {}
  212. # Track expected prints from reprint/scheduled (skip auto-archiving for these)
  213. # {(printer_id, filename): archive_id}
  214. _expected_prints: dict[tuple[int, str], int] = {}
  215. # Track starting energy for prints: {archive_id: starting_kwh}
  216. _print_energy_start: dict[int, float] = {}
  217. # Track reprints to add costs on completion: {archive_id}
  218. _reprint_archives: set[int] = set()
  219. # Track progress milestones for notifications: {printer_id: last_milestone_notified}
  220. # Milestones are 25, 50, 75. Value of 0 means no milestone notified yet for current print.
  221. _last_progress_milestone: dict[int, int] = {}
  222. # Track HMS errors that have been notified: {printer_id: set of error codes}
  223. # This prevents sending duplicate notifications for the same error
  224. _notified_hms_errors: dict[int, set[str]] = {}
  225. # Track timelapse file baselines at print start: {printer_id: set of MP4 filenames}
  226. # Used for snapshot-diff detection at print completion
  227. _timelapse_baselines: dict[int, set[str]] = {}
  228. async def _get_plug_energy(plug, db) -> dict | None:
  229. """Get energy from plug regardless of type (Tasmota, Home Assistant, or MQTT).
  230. For HA plugs, configures the service with current settings from DB.
  231. For MQTT plugs, returns data from the subscription service.
  232. """
  233. if plug.plug_type == "homeassistant":
  234. from backend.app.api.routes.settings import get_homeassistant_settings
  235. ha_settings = await get_homeassistant_settings(db)
  236. homeassistant_service.configure(ha_settings["ha_url"], ha_settings["ha_token"])
  237. return await homeassistant_service.get_energy(plug)
  238. elif plug.plug_type == "mqtt":
  239. # MQTT plugs report "today" energy, not lifetime total
  240. # For per-print tracking, we use "today" as the counter (resets at midnight)
  241. mqtt_data = mqtt_relay.smart_plug_service.get_plug_data(plug.id)
  242. if mqtt_data:
  243. return {
  244. "power": mqtt_data.power,
  245. "today": mqtt_data.energy,
  246. "total": mqtt_data.energy, # Use today as total for per-print calculations
  247. }
  248. return None
  249. else:
  250. return await tasmota_service.get_energy(plug)
  251. def register_expected_print(printer_id: int, filename: str, archive_id: int):
  252. """Register an expected print from reprint/scheduled so we don't create duplicate archives."""
  253. # Store with multiple filename variations to catch different naming patterns
  254. _expected_prints[(printer_id, filename)] = archive_id
  255. # Also store without .3mf extension if present
  256. if filename.endswith(".3mf"):
  257. base = filename[:-4]
  258. _expected_prints[(printer_id, base)] = archive_id
  259. _expected_prints[(printer_id, f"{base}.gcode")] = archive_id
  260. logging.getLogger(__name__).info(
  261. f"Registered expected print: printer={printer_id}, file={filename}, archive={archive_id}"
  262. )
  263. _last_status_broadcast: dict[int, str] = {}
  264. _nozzle_count_updated: set[int] = set() # Track printers where we've updated nozzle_count
  265. async def on_printer_status_change(printer_id: int, state: PrinterState):
  266. """Handle printer status changes - broadcast via WebSocket."""
  267. # Only broadcast if something meaningful changed (reduce WebSocket spam)
  268. # Include rounded temperatures to detect meaningful temp changes (within 1 degree)
  269. temps = state.temperatures or {}
  270. nozzle_temp = round(temps.get("nozzle", 0))
  271. bed_temp = round(temps.get("bed", 0))
  272. nozzle_2_temp = round(temps.get("nozzle_2", 0)) if "nozzle_2" in temps else ""
  273. chamber_temp = round(temps.get("chamber", 0)) if "chamber" in temps else ""
  274. # Auto-detect dual-nozzle printers from MQTT temperature data
  275. if "nozzle_2" in temps and printer_id not in _nozzle_count_updated:
  276. _nozzle_count_updated.add(printer_id)
  277. # Update nozzle_count in database
  278. async with async_session() as db:
  279. from backend.app.models.printer import Printer
  280. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  281. printer = result.scalar_one_or_none()
  282. if printer and printer.nozzle_count != 2:
  283. printer.nozzle_count = 2
  284. await db.commit()
  285. logging.getLogger(__name__).info(
  286. f"Auto-detected dual-nozzle printer {printer_id}, updated nozzle_count=2"
  287. )
  288. # Include target temps for heating phase detection
  289. bed_target = round(temps.get("bed_target", 0))
  290. nozzle_target = round(temps.get("nozzle_target", 0))
  291. # Include tray_now and vt_tray hash so external spool changes trigger broadcasts
  292. vt_tray_key = hash(str(state.raw_data.get("vt_tray", []))) if state.raw_data else 0
  293. status_key = (
  294. f"{state.connected}:{state.state}:{state.progress}:{state.layer_num}:"
  295. f"{nozzle_temp}:{bed_temp}:{nozzle_2_temp}:{chamber_temp}:"
  296. f"{state.stg_cur}:{bed_target}:{nozzle_target}:"
  297. f"{state.cooling_fan_speed}:{state.big_fan1_speed}:{state.big_fan2_speed}:"
  298. f"{state.chamber_light}:{state.active_extruder}:{state.tray_now}:{vt_tray_key}"
  299. )
  300. # MQTT relay - publish status (before dedup check - always publish to MQTT)
  301. try:
  302. printer_info = printer_manager.get_printer(printer_id)
  303. if printer_info:
  304. await mqtt_relay.on_printer_status(printer_id, state, printer_info.name, printer_info.serial_number)
  305. except Exception:
  306. pass # Don't fail status callback if MQTT fails
  307. if _last_status_broadcast.get(printer_id) == status_key:
  308. return # No change, skip WebSocket broadcast
  309. _last_status_broadcast[printer_id] = status_key
  310. # Check for progress milestone notifications (25%, 50%, 75%)
  311. progress = state.progress or 0
  312. is_printing = state.state in ("RUNNING", "PRINTING")
  313. if is_printing and progress > 0:
  314. # Determine which milestone we've reached
  315. current_milestone = 0
  316. if progress >= 75:
  317. current_milestone = 75
  318. elif progress >= 50:
  319. current_milestone = 50
  320. elif progress >= 25:
  321. current_milestone = 25
  322. last_milestone = _last_progress_milestone.get(printer_id, 0)
  323. # If we've crossed a new milestone, send notification
  324. if current_milestone > last_milestone:
  325. _last_progress_milestone[printer_id] = current_milestone
  326. try:
  327. async with async_session() as db:
  328. from backend.app.models.printer import Printer
  329. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  330. printer = result.scalar_one_or_none()
  331. printer_name = printer.name if printer else f"Printer {printer_id}"
  332. filename = state.subtask_name or state.gcode_file or "Unknown"
  333. # remaining_time is in minutes, convert to seconds for notification
  334. remaining_time_seconds = state.remaining_time * 60 if state.remaining_time else None
  335. # Capture camera snapshot for notification image attachment
  336. image_data = await _capture_snapshot_for_notification(
  337. printer_id, printer, logging.getLogger(__name__)
  338. )
  339. await notification_service.on_print_progress(
  340. printer_id,
  341. printer_name,
  342. filename,
  343. current_milestone,
  344. db,
  345. remaining_time_seconds,
  346. image_data=image_data,
  347. )
  348. except Exception as e:
  349. logging.getLogger(__name__).warning(f"Progress milestone notification failed: {e}")
  350. elif progress < 5:
  351. # Reset milestone tracking when print restarts or new print begins
  352. _last_progress_milestone[printer_id] = 0
  353. # Check for new HMS errors and send notifications
  354. current_hms_errors = getattr(state, "hms_errors", []) or []
  355. if current_hms_errors:
  356. # Build set of current error codes (using attr for uniqueness)
  357. current_error_codes = {f"{e.attr:08x}" for e in current_hms_errors}
  358. previously_notified = _notified_hms_errors.get(printer_id, set())
  359. # Find new errors that haven't been notified yet
  360. new_error_codes = current_error_codes - previously_notified
  361. # Update tracking immediately to prevent duplicate notifications from concurrent callbacks
  362. _notified_hms_errors[printer_id] = current_error_codes
  363. if new_error_codes:
  364. # Get the actual new errors for the notification
  365. # Filter to severity >= 2 (skip informational/status messages like H2D sends)
  366. new_errors = [e for e in current_hms_errors if f"{e.attr:08x}" in new_error_codes and e.severity >= 2]
  367. try:
  368. async with async_session() as db:
  369. from backend.app.models.printer import Printer
  370. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  371. printer = result.scalar_one_or_none()
  372. printer_name = printer.name if printer else f"Printer {printer_id}"
  373. # Format error details for notification
  374. # Module 0x07 = AMS/Filament, 0x05 = Nozzle, 0x0C = Motion Controller, etc.
  375. module_names = {
  376. 0x03: "Print/Task",
  377. 0x05: "Nozzle/Extruder",
  378. 0x07: "AMS/Filament",
  379. 0x0C: "Motion Controller",
  380. 0x12: "Chamber",
  381. }
  382. from backend.app.services.hms_errors import get_error_description
  383. # Capture camera snapshot once for all error notifications
  384. error_image_data = await _capture_snapshot_for_notification(
  385. printer_id, printer, logging.getLogger(__name__)
  386. )
  387. for error in new_errors:
  388. module_name = module_names.get(error.module, f"Module 0x{error.module:02X}")
  389. # Build short code like "0700_8010"
  390. # Mask to 16 bits to handle printers that send larger values
  391. error_code_int = int(error.code.replace("0x", ""), 16) if error.code else 0
  392. error_code_masked = error_code_int & 0xFFFF
  393. short_code = f"{(error.attr >> 16) & 0xFFFF:04X}_{error_code_masked:04X}"
  394. error_type = f"{module_name} Error"
  395. # Look up human-readable description
  396. description = get_error_description(short_code)
  397. error_detail = description if description else f"Error code: {short_code}"
  398. await notification_service.on_printer_error(
  399. printer_id, printer_name, error_type, db, error_detail, image_data=error_image_data
  400. )
  401. logging.getLogger(__name__).info(
  402. f"[HMS] Sent notification for {len(new_errors)} new error(s) on printer {printer_id}"
  403. )
  404. # Also publish to MQTT relay
  405. printer_info = printer_manager.get_printer(printer_id)
  406. if printer_info:
  407. errors_data = [
  408. {
  409. "code": e.code,
  410. "attr": e.attr,
  411. "module": e.module,
  412. "severity": e.severity,
  413. }
  414. for e in new_errors
  415. ]
  416. await mqtt_relay.on_printer_error(
  417. printer_id, printer_info.name, printer_info.serial_number, errors_data
  418. )
  419. except Exception as e:
  420. logging.getLogger(__name__).warning(f"HMS error notification failed: {e}")
  421. else:
  422. # No HMS errors - clear tracking so future errors get notified
  423. if printer_id in _notified_hms_errors:
  424. _notified_hms_errors.pop(printer_id, None)
  425. await ws_manager.send_printer_status(
  426. printer_id,
  427. printer_state_to_dict(state, printer_id, printer_manager.get_model(printer_id)),
  428. )
  429. def _is_bambu_uuid(tray_uuid: str) -> bool:
  430. """Check if a tray UUID looks like a valid Bambu Lab RFID UUID (non-empty, non-zero)."""
  431. return bool(tray_uuid) and tray_uuid not in ("", "0" * len(tray_uuid))
  432. async def on_ams_change(printer_id: int, ams_data: list):
  433. """Handle AMS data changes - sync to Spoolman if enabled and auto mode."""
  434. logger = logging.getLogger(__name__)
  435. # MQTT relay - publish AMS change
  436. try:
  437. printer_info = printer_manager.get_printer(printer_id)
  438. if printer_info:
  439. await mqtt_relay.on_ams_change(printer_id, printer_info.name, printer_info.serial_number, ams_data)
  440. except Exception:
  441. pass # Don't fail AMS callback if MQTT fails
  442. # Broadcast AMS change via WebSocket (bypasses status_key deduplication)
  443. # This ensures frontend gets immediate updates when AMS slots are configured
  444. try:
  445. state = printer_manager.get_status(printer_id)
  446. if state:
  447. logger.info("[Printer %s] Broadcasting AMS change via WebSocket", printer_id)
  448. await ws_manager.send_printer_status(
  449. printer_id,
  450. printer_state_to_dict(state, printer_id, printer_manager.get_model(printer_id)),
  451. )
  452. except Exception as e:
  453. logger.warning("Failed to broadcast AMS change for printer %s: %s", printer_id, e)
  454. # Auto-unlink spool assignments with stale fingerprints
  455. try:
  456. async with async_session() as db:
  457. from sqlalchemy.orm import selectinload
  458. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  459. from backend.app.models.spool_assignment import SpoolAssignment as SA
  460. result = await db.execute(select(SA).where(SA.printer_id == printer_id).options(selectinload(SA.spool)))
  461. stale = []
  462. for assignment in result.scalars().all():
  463. current_tray = _find_tray_in_ams_data(ams_data, assignment.ams_id, assignment.tray_id)
  464. if not current_tray:
  465. logger.info(
  466. "Auto-unlink: spool %d AMS%d-T%d — tray not found in AMS data (slot empty?)",
  467. assignment.spool_id,
  468. assignment.ams_id,
  469. assignment.tray_id,
  470. )
  471. stale.append(assignment) # Slot empty
  472. elif _is_bambu_uuid(current_tray.get("tray_uuid", "")):
  473. # A Bambu Lab spool is in this slot — check if it's the same spool
  474. # that's currently assigned. If yes, keep the assignment (avoids
  475. # unnecessary unlink/re-assign/ams_filament_setting cycle that clears
  476. # the printer's filament preset on every startup).
  477. tray_uuid = current_tray.get("tray_uuid", "")
  478. tag_uid = current_tray.get("tag_uid", "")
  479. spool = assignment.spool
  480. spool_matches = False
  481. if spool:
  482. if (spool.tray_uuid and spool.tray_uuid.upper() == tray_uuid.upper()) or (
  483. spool.tag_uid
  484. and tag_uid
  485. and tag_uid != "0000000000000000"
  486. and spool.tag_uid.upper() == tag_uid.upper()
  487. ):
  488. spool_matches = True
  489. if spool_matches:
  490. # Same BL spool still in slot — keep assignment, update fingerprint if needed
  491. cur_color = current_tray.get("tray_color", "")
  492. cur_type = current_tray.get("tray_type", "")
  493. fp_color = assignment.fingerprint_color or ""
  494. fp_type = assignment.fingerprint_type or ""
  495. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  496. assignment.fingerprint_color = cur_color
  497. assignment.fingerprint_type = cur_type
  498. logger.debug(
  499. "Auto-unlink: spool %d AMS%d-T%d — same BL spool, updated fingerprint",
  500. assignment.spool_id,
  501. assignment.ams_id,
  502. assignment.tray_id,
  503. )
  504. continue
  505. # Different BL spool or unrecognized — unlink so auto-assign can match
  506. logger.info(
  507. "Auto-unlink: spool %d AMS%d-T%d — different Bambu Lab spool detected (uuid=%s)",
  508. assignment.spool_id,
  509. assignment.ams_id,
  510. assignment.tray_id,
  511. tray_uuid,
  512. )
  513. stale.append(assignment)
  514. else:
  515. cur_color = current_tray.get("tray_color", "")
  516. cur_type = current_tray.get("tray_type", "")
  517. fp_color = assignment.fingerprint_color or ""
  518. fp_type = assignment.fingerprint_type or ""
  519. if cur_color.upper() != fp_color.upper() or cur_type.upper() != fp_type.upper():
  520. # Fingerprint mismatch — but check if tray now matches the
  521. # assigned spool (e.g. auto-configure changed the tray).
  522. spool = assignment.spool
  523. if spool:
  524. spool_color = (spool.rgba or "FFFFFFFF").upper()
  525. spool_type = (spool.material or "").upper()
  526. if cur_color.upper() == spool_color and cur_type.upper() == spool_type:
  527. # Tray was reconfigured to match the spool — update fingerprint
  528. logger.info(
  529. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch but tray matches spool, updating fp",
  530. assignment.spool_id,
  531. assignment.ams_id,
  532. assignment.tray_id,
  533. )
  534. assignment.fingerprint_color = cur_color
  535. assignment.fingerprint_type = cur_type
  536. continue
  537. logger.info(
  538. "Auto-unlink: spool %d AMS%d-T%d — fingerprint mismatch (cur=%s/%s fp=%s/%s spool=%s/%s)",
  539. assignment.spool_id,
  540. assignment.ams_id,
  541. assignment.tray_id,
  542. cur_color,
  543. cur_type,
  544. fp_color,
  545. fp_type,
  546. spool.rgba if spool else "?",
  547. spool.material if spool else "?",
  548. )
  549. stale.append(assignment) # Spool changed
  550. for a in stale:
  551. await db.delete(a)
  552. if stale:
  553. logger.info("Auto-unlinked %d stale spool assignments for printer %d", len(stale), printer_id)
  554. # Commit any changes (stale deletions and/or fingerprint updates)
  555. await db.commit()
  556. except Exception as e:
  557. logger.warning("Spool assignment cleanup failed: %s", e)
  558. # Auto-manage inventory spools from AMS tray data (skip if Spoolman manages AMS)
  559. try:
  560. async with async_session() as db:
  561. from backend.app.api.routes.settings import get_setting
  562. from backend.app.models.spool_assignment import SpoolAssignment as SA
  563. from backend.app.services.spool_tag_matcher import (
  564. auto_assign_spool,
  565. create_spool_from_tray,
  566. get_spool_by_tag,
  567. is_bambu_tag,
  568. is_valid_tag,
  569. )
  570. _spoolman_on = await get_setting(db, "spoolman_enabled")
  571. if not _spoolman_on or _spoolman_on.lower() != "true":
  572. for ams_unit in ams_data:
  573. if not isinstance(ams_unit, dict):
  574. continue
  575. ams_id = int(ams_unit.get("id", 0))
  576. for tray in ams_unit.get("tray", []):
  577. if not isinstance(tray, dict):
  578. continue
  579. tray_id = int(tray.get("id", 0))
  580. tag_uid = tray.get("tag_uid", "")
  581. tray_uuid = tray.get("tray_uuid", "")
  582. tray_info_idx = tray.get("tray_info_idx", "")
  583. if not tray.get("tray_type"):
  584. continue # Empty slot
  585. # Check if assignment already exists for this slot
  586. existing = await db.execute(
  587. select(SA)
  588. .options(selectinload(SA.spool))
  589. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == tray_id)
  590. )
  591. existing_assignment = existing.scalar_one_or_none()
  592. if existing_assignment:
  593. # Sync spool weight_used from AMS remain — only INCREASE, never decrease.
  594. # The AMS remain% is low-resolution (integer %, i.e. 10g steps for 1kg spool)
  595. # and must not overwrite precise values from the usage tracker (3MF/G-code).
  596. remain_raw = tray.get("remain")
  597. if remain_raw is not None and existing_assignment.spool:
  598. try:
  599. remain_val = int(remain_raw)
  600. except (TypeError, ValueError):
  601. remain_val = -1
  602. if 0 <= remain_val <= 100:
  603. lw = existing_assignment.spool.label_weight or 1000
  604. new_used = round(lw * (100 - remain_val) / 100.0, 1)
  605. current_used = existing_assignment.spool.weight_used or 0
  606. if new_used > current_used + 1:
  607. logger.info(
  608. "Weight sync: spool %d weight_used %s -> %s (remain=%d)",
  609. existing_assignment.spool_id,
  610. current_used,
  611. new_used,
  612. remain_val,
  613. )
  614. existing_assignment.spool.weight_used = new_used
  615. await db.commit()
  616. continue
  617. if is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  618. # BL spool with RFID tag: auto-match or auto-create
  619. spool = await get_spool_by_tag(db, tag_uid, tray_uuid)
  620. if not spool:
  621. spool = await create_spool_from_tray(db, tray)
  622. await auto_assign_spool(
  623. printer_id,
  624. ams_id,
  625. tray_id,
  626. spool,
  627. printer_manager,
  628. db,
  629. tray_info_idx=tray_info_idx,
  630. )
  631. await db.commit()
  632. await ws_manager.broadcast(
  633. {
  634. "type": "spool_auto_assigned",
  635. "printer_id": printer_id,
  636. "ams_id": ams_id,
  637. "tray_id": tray_id,
  638. "spool_id": spool.id,
  639. }
  640. )
  641. logger.info(
  642. "RFID auto-assigned spool %d to printer %d AMS%d-T%d",
  643. spool.id,
  644. printer_id,
  645. ams_id,
  646. tray_id,
  647. )
  648. elif is_valid_tag(tag_uid, tray_uuid):
  649. # Non-BL spool with some tag — let user choose
  650. await ws_manager.broadcast(
  651. {
  652. "type": "unknown_tag",
  653. "printer_id": printer_id,
  654. "ams_id": ams_id,
  655. "tray_id": tray_id,
  656. "tag_uid": tag_uid,
  657. "tray_uuid": tray_uuid,
  658. }
  659. )
  660. else:
  661. # No tag at all — let user choose from inventory
  662. await ws_manager.broadcast(
  663. {
  664. "type": "unknown_tag",
  665. "printer_id": printer_id,
  666. "ams_id": ams_id,
  667. "tray_id": tray_id,
  668. "tag_uid": "",
  669. "tray_uuid": "",
  670. }
  671. )
  672. except Exception as e:
  673. logger.warning("RFID spool auto-assign failed: %s", e)
  674. try:
  675. async with async_session() as db:
  676. from backend.app.api.routes.settings import get_setting
  677. from backend.app.models.printer import Printer
  678. # Check if Spoolman is enabled
  679. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  680. if not spoolman_enabled or spoolman_enabled.lower() != "true":
  681. return
  682. # Check sync mode
  683. sync_mode = await get_setting(db, "spoolman_sync_mode")
  684. if sync_mode and sync_mode != "auto":
  685. return # Only sync on auto mode
  686. # Check if weight sync is disabled
  687. disable_weight_sync_str = await get_setting(db, "spoolman_disable_weight_sync")
  688. disable_weight_sync = disable_weight_sync_str and disable_weight_sync_str.lower() == "true"
  689. # Get Spoolman URL
  690. spoolman_url = await get_setting(db, "spoolman_url")
  691. if not spoolman_url:
  692. return
  693. # Get or create Spoolman client
  694. client = await get_spoolman_client()
  695. if not client:
  696. client = await init_spoolman_client(spoolman_url)
  697. # Check if Spoolman is reachable
  698. if not await client.health_check():
  699. logger.warning("Spoolman not reachable at %s", spoolman_url)
  700. return
  701. # Get printer name for location
  702. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  703. printer = result.scalar_one_or_none()
  704. printer_name = printer.name if printer else f"Printer {printer_id}"
  705. # OPTIMIZATION: Fetch all spools once before processing trays
  706. # This eliminates redundant API calls (one per tray) when syncing multiple trays
  707. logger.debug("[Printer %s] Fetching spools cache for AMS sync...", printer_id)
  708. try:
  709. cached_spools = await client.get_spools()
  710. logger.debug("[Printer %s] Cached %d spools for batch sync", printer_id, len(cached_spools))
  711. except Exception as e:
  712. logger.error(
  713. "[Printer %s] Failed to fetch spools cache after retries, aborting AMS sync: %s",
  714. printer_id,
  715. e,
  716. )
  717. return
  718. # Load inventory weights as fallback (when AMS MQTT data lacks remain values)
  719. from sqlalchemy.orm import selectinload
  720. from backend.app.models.spool_assignment import SpoolAssignment
  721. inventory_weights: dict[tuple[int, int], float] = {}
  722. try:
  723. assign_result = await db.execute(
  724. select(SpoolAssignment)
  725. .options(selectinload(SpoolAssignment.spool))
  726. .where(SpoolAssignment.printer_id == printer_id)
  727. )
  728. for assignment in assign_result.scalars().all():
  729. spool = assignment.spool
  730. if spool and spool.label_weight > 0:
  731. remaining = max(0.0, spool.label_weight - (spool.weight_used or 0))
  732. inventory_weights[(assignment.ams_id, assignment.tray_id)] = remaining
  733. except Exception as e:
  734. logger.debug("Could not load inventory weights for printer %s: %s", printer_id, e)
  735. # Sync each AMS tray
  736. synced = 0
  737. for ams_unit in ams_data:
  738. ams_id = int(ams_unit.get("id", 0))
  739. trays = ams_unit.get("tray", [])
  740. for tray_data in trays:
  741. tray = client.parse_ams_tray(ams_id, tray_data)
  742. if not tray:
  743. continue # Empty tray
  744. try:
  745. inv_remaining = inventory_weights.get((ams_id, tray.tray_id))
  746. result = await client.sync_ams_tray(
  747. tray,
  748. printer_name,
  749. disable_weight_sync=disable_weight_sync,
  750. cached_spools=cached_spools,
  751. inventory_remaining=inv_remaining,
  752. )
  753. if result:
  754. synced += 1
  755. # If a new spool was created, add it to the cache
  756. # so subsequent trays can find it if they reference the same tag
  757. if result.get("id"):
  758. # Check if this spool already exists in cache
  759. spool_exists = any(s.get("id") == result["id"] for s in cached_spools)
  760. if not spool_exists:
  761. cached_spools.append(result)
  762. logger.debug(
  763. "[Printer %s] Added newly created spool %s to cache",
  764. printer_id,
  765. result["id"],
  766. )
  767. except Exception as e:
  768. logger.error("Error syncing AMS %s tray %s: %s", ams_id, tray.tray_id, e)
  769. if synced > 0:
  770. logger.info("Auto-synced %s AMS trays to Spoolman for printer %s", synced, printer_id)
  771. except Exception as e:
  772. logging.getLogger(__name__).warning(f"Spoolman AMS sync failed: {e}")
  773. async def _capture_snapshot_for_notification(printer_id: int, printer, logger) -> bytes | None:
  774. """Capture a camera snapshot for notification image attachment.
  775. Returns JPEG bytes (max 2.5MB) or None if capture fails or is unavailable.
  776. Uses: external camera > buffered frame > fresh capture.
  777. """
  778. if not printer:
  779. return None
  780. try:
  781. from backend.app.api.routes.settings import get_setting
  782. async with async_session() as db:
  783. capture_enabled = await get_setting(db, "capture_finish_photo")
  784. if capture_enabled is not None and capture_enabled.lower() != "true":
  785. return None
  786. # Try external camera first
  787. if printer.external_camera_enabled and printer.external_camera_url:
  788. logger.info("[SNAPSHOT] Capturing from external camera for printer %s", printer_id)
  789. from backend.app.services.external_camera import capture_frame
  790. frame_data = await capture_frame(printer.external_camera_url, printer.external_camera_type or "mjpeg")
  791. if frame_data and len(frame_data) <= 2_500_000:
  792. logger.info("[SNAPSHOT] External camera frame: %s bytes", len(frame_data))
  793. return frame_data
  794. # Try buffered frame from active stream
  795. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  796. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  797. active_chamber = [k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")]
  798. buffered_frame = get_buffered_frame(printer_id)
  799. if (active_for_printer or active_chamber) and buffered_frame:
  800. logger.info("[SNAPSHOT] Using buffered frame for printer %s: %s bytes", printer_id, len(buffered_frame))
  801. if len(buffered_frame) <= 2_500_000:
  802. return buffered_frame
  803. # Fresh capture from printer camera
  804. logger.info("[SNAPSHOT] Capturing fresh frame for printer %s", printer_id)
  805. from backend.app.services.camera import capture_camera_frame_bytes
  806. frame_data = await capture_camera_frame_bytes(
  807. printer.ip_address, printer.access_code, printer.model, timeout=15
  808. )
  809. if frame_data and len(frame_data) <= 2_500_000:
  810. logger.info("[SNAPSHOT] Fresh camera frame: %s bytes", len(frame_data))
  811. return frame_data
  812. except Exception as e:
  813. logger.warning("[SNAPSHOT] Failed to capture snapshot for printer %s: %s", printer_id, e)
  814. return None
  815. async def _send_print_start_notification(
  816. printer_id: int,
  817. data: dict,
  818. archive_data: dict | None = None,
  819. logger=None,
  820. ):
  821. """Helper to send print start notification with optional archive data."""
  822. if logger is None:
  823. logger = logging.getLogger(__name__)
  824. try:
  825. async with async_session() as db:
  826. from backend.app.models.printer import Printer
  827. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  828. printer = result.scalar_one_or_none()
  829. printer_name = printer.name if printer else f"Printer {printer_id}"
  830. # Capture camera snapshot for notification image attachment
  831. image_data = await _capture_snapshot_for_notification(printer_id, printer, logger)
  832. if image_data:
  833. if archive_data is None:
  834. archive_data = {}
  835. archive_data["image_data"] = image_data
  836. await notification_service.on_print_start(printer_id, printer_name, data, db, archive_data=archive_data)
  837. except Exception as e:
  838. logger.warning("Notification on_print_start failed: %s", e)
  839. def _load_objects_from_archive(archive, printer_id: int, logger) -> None:
  840. """Extract printable objects from an archive's 3MF file and store in printer state."""
  841. try:
  842. from backend.app.services.archive import extract_printable_objects_from_3mf
  843. file_path = app_settings.base_dir / archive.file_path
  844. if file_path.exists() and str(file_path).endswith(".3mf"):
  845. with open(file_path, "rb") as f:
  846. threemf_data = f.read()
  847. # Extract with positions for UI overlay
  848. printable_objects, bbox_all = extract_printable_objects_from_3mf(threemf_data, include_positions=True)
  849. if printable_objects:
  850. client = printer_manager.get_client(printer_id)
  851. if client:
  852. client.state.printable_objects = printable_objects
  853. client.state.printable_objects_bbox_all = bbox_all
  854. client.state.skipped_objects = []
  855. logger.info("Loaded %s printable objects for printer %s", len(printable_objects), printer_id)
  856. except Exception as e:
  857. logger.debug("Failed to extract printable objects from archive: %s", e)
  858. async def on_print_start(printer_id: int, data: dict):
  859. """Handle print start - archive the 3MF file immediately."""
  860. logger = logging.getLogger(__name__)
  861. logger.info("[CALLBACK] on_print_start called for printer %s, data keys: %s", printer_id, list(data.keys()))
  862. # Clear cached cover images so the new print's thumbnail is fetched fresh
  863. from backend.app.api.routes.printers import clear_cover_cache
  864. clear_cover_cache(printer_id)
  865. await ws_manager.send_print_start(printer_id, data)
  866. # MQTT relay - publish print start
  867. try:
  868. printer_info = printer_manager.get_printer(printer_id)
  869. if printer_info:
  870. await mqtt_relay.on_print_start(
  871. printer_id,
  872. printer_info.name,
  873. printer_info.serial_number,
  874. data.get("filename", ""),
  875. data.get("subtask_name", ""),
  876. )
  877. except Exception:
  878. pass # Don't fail print start callback if MQTT fails
  879. # Capture AMS tray remain% for filament consumption tracking (skip if Spoolman handles usage)
  880. try:
  881. async with async_session() as db:
  882. from backend.app.api.routes.settings import get_setting
  883. _spoolman_on = await get_setting(db, "spoolman_enabled")
  884. if not _spoolman_on or _spoolman_on.lower() != "true":
  885. from backend.app.services.usage_tracker import on_print_start as usage_on_print_start
  886. await usage_on_print_start(printer_id, data, printer_manager)
  887. except Exception as e:
  888. logger.warning("Usage tracker on_print_start failed: %s", e)
  889. # Track if notification was sent (to avoid sending twice)
  890. notification_sent = False
  891. # Smart plug automation: turn on plug when print starts
  892. try:
  893. async with async_session() as db:
  894. await smart_plug_manager.on_print_start(printer_id, db)
  895. except Exception as e:
  896. logger.warning("Smart plug on_print_start failed: %s", e)
  897. async with async_session() as db:
  898. from backend.app.models.printer import Printer
  899. from backend.app.services.bambu_ftp import list_files_async
  900. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  901. printer = result.scalar_one_or_none()
  902. # Plate detection check - pause if objects detected on build plate
  903. logger.info(
  904. f"[PLATE CHECK] printer_id={printer_id}, plate_detection_enabled={printer.plate_detection_enabled if printer else 'NO PRINTER'}"
  905. )
  906. if printer and printer.plate_detection_enabled:
  907. logger.info("[PLATE CHECK] ENTERING plate detection code for printer %s", printer_id)
  908. try:
  909. from backend.app.services.plate_detection import check_plate_empty
  910. # Build ROI tuple from printer settings if available
  911. roi = None
  912. if all(
  913. [
  914. printer.plate_detection_roi_x is not None,
  915. printer.plate_detection_roi_y is not None,
  916. printer.plate_detection_roi_w is not None,
  917. printer.plate_detection_roi_h is not None,
  918. ]
  919. ):
  920. roi = (
  921. printer.plate_detection_roi_x,
  922. printer.plate_detection_roi_y,
  923. printer.plate_detection_roi_w,
  924. printer.plate_detection_roi_h,
  925. )
  926. # Auto-turn on chamber light if it's off for better detection
  927. light_was_off = False
  928. client = printer_manager.get_client(printer_id)
  929. if client and client.state:
  930. light_was_off = not client.state.chamber_light
  931. if light_was_off:
  932. logger.info("[PLATE CHECK] Turning on chamber light for printer %s", printer_id)
  933. client.set_chamber_light(True)
  934. # Wait for light to physically turn on and camera to adjust exposure
  935. await asyncio.sleep(2.5)
  936. logger.info("[PLATE CHECK] Running plate detection for printer %s", printer_id)
  937. plate_result = await check_plate_empty(
  938. printer_id=printer_id,
  939. ip_address=printer.ip_address,
  940. access_code=printer.access_code,
  941. model=printer.model,
  942. include_debug_image=False,
  943. external_camera_url=printer.external_camera_url,
  944. external_camera_type=printer.external_camera_type,
  945. use_external=printer.external_camera_enabled,
  946. roi=roi,
  947. )
  948. # Restore chamber light to original state
  949. if light_was_off and client:
  950. logger.info("[PLATE CHECK] Restoring chamber light to off for printer %s", printer_id)
  951. client.set_chamber_light(False)
  952. if not plate_result.needs_calibration and not plate_result.is_empty:
  953. # Objects detected - pause the print!
  954. logger.warning(
  955. f"[PLATE CHECK] Objects detected on plate for printer {printer_id}! "
  956. f"Confidence: {plate_result.confidence:.0%}, Diff: {plate_result.difference_percent:.1f}%"
  957. )
  958. client = printer_manager.get_client(printer_id)
  959. if client:
  960. client.pause_print()
  961. logger.info("[PLATE CHECK] Print paused for printer %s", printer_id)
  962. # Send notification about plate not empty
  963. await ws_manager.broadcast(
  964. {
  965. "type": "plate_not_empty",
  966. "printer_id": printer_id,
  967. "printer_name": printer.name,
  968. "message": f"Objects detected on build plate! Print paused. (Diff: {plate_result.difference_percent:.1f}%)",
  969. }
  970. )
  971. # Also send push notification
  972. try:
  973. await notification_service.on_plate_not_empty(
  974. printer_id=printer_id,
  975. printer_name=printer.name,
  976. db=db,
  977. difference_percent=plate_result.difference_percent,
  978. )
  979. except Exception as notif_err:
  980. logger.warning("[PLATE CHECK] Failed to send notification: %s", notif_err)
  981. else:
  982. logger.info("[PLATE CHECK] Plate is empty for printer %s, proceeding with print", printer_id)
  983. except Exception as plate_err:
  984. # Don't block print on plate detection errors
  985. logger.warning("[PLATE CHECK] Plate detection failed for printer %s: %s", printer_id, plate_err)
  986. if not printer or not printer.auto_archive:
  987. # Send notification without archive data (auto-archive disabled)
  988. logger.info(
  989. f"[CALLBACK] Skipping archive - printer: {printer is not None}, auto_archive: {printer.auto_archive if printer else 'N/A'}"
  990. )
  991. if not notification_sent:
  992. await _send_print_start_notification(printer_id, data, logger=logger)
  993. return
  994. # Get the filename and subtask_name
  995. filename = data.get("filename", "")
  996. subtask_name = data.get("subtask_name", "")
  997. logger.info("[CALLBACK] Print start detected - filename: %s, subtask: %s", filename, subtask_name)
  998. # Skip calibration prints — internal printer files should not be archived
  999. # Bambu calibration gcode lives under /usr/ (e.g. /usr/etc/print/auto_cali_for_user.gcode)
  1000. if filename and filename.startswith("/usr/"):
  1001. logger.info("[CALLBACK] Skipping archive — internal printer file detected: %s", filename)
  1002. if not notification_sent:
  1003. await _send_print_start_notification(printer_id, data, logger=logger)
  1004. return
  1005. if not filename and not subtask_name:
  1006. # Send notification without archive data (no filename)
  1007. logger.info("[CALLBACK] Skipping archive - no filename or subtask_name")
  1008. if not notification_sent:
  1009. await _send_print_start_notification(printer_id, data, logger=logger)
  1010. return
  1011. # Check if this is an expected print from reprint/scheduled
  1012. # Build list of possible keys to check
  1013. expected_keys = []
  1014. if subtask_name:
  1015. expected_keys.append((printer_id, subtask_name))
  1016. expected_keys.append((printer_id, f"{subtask_name}.3mf"))
  1017. expected_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  1018. if filename:
  1019. fname = filename.split("/")[-1] if "/" in filename else filename
  1020. expected_keys.append((printer_id, fname))
  1021. # Strip extensions to match
  1022. base = fname.replace(".gcode", "").replace(".3mf", "")
  1023. expected_keys.append((printer_id, base))
  1024. expected_keys.append((printer_id, f"{base}.3mf"))
  1025. expected_archive_id = None
  1026. for key in expected_keys:
  1027. expected_archive_id = _expected_prints.pop(key, None)
  1028. if expected_archive_id:
  1029. # Clean up other possible keys for this print
  1030. for other_key in expected_keys:
  1031. _expected_prints.pop(other_key, None)
  1032. break
  1033. if expected_archive_id:
  1034. # This is a reprint/scheduled print - use existing archive, don't create new one
  1035. logger.info("Using expected archive %s for print (skipping duplicate)", expected_archive_id)
  1036. from backend.app.models.archive import PrintArchive
  1037. result = await db.execute(select(PrintArchive).where(PrintArchive.id == expected_archive_id))
  1038. archive = result.scalar_one_or_none()
  1039. if archive:
  1040. # Update archive status to printing
  1041. archive.status = "printing"
  1042. archive.started_at = datetime.now()
  1043. await db.commit()
  1044. # Track as active print
  1045. _active_prints[(printer_id, archive.filename)] = archive.id
  1046. if subtask_name:
  1047. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  1048. # Mark as reprint so we add cost on completion
  1049. _reprint_archives.add(archive.id)
  1050. logger.info("Marked archive %s as reprint for cost addition on completion", archive.id)
  1051. # Set up energy tracking
  1052. try:
  1053. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  1054. plug = plug_result.scalar_one_or_none()
  1055. logger.info(
  1056. f"[ENERGY] Print start - archive {archive.id}, printer {printer_id}, plug found: {plug is not None}"
  1057. )
  1058. if plug:
  1059. energy = await _get_plug_energy(plug, db)
  1060. logger.info("[ENERGY] Energy response from plug: %s", energy)
  1061. if energy and energy.get("total") is not None:
  1062. _print_energy_start[archive.id] = energy["total"]
  1063. logger.info(
  1064. f"[ENERGY] Recorded starting energy for archive {archive.id}: {energy['total']} kWh"
  1065. )
  1066. else:
  1067. logger.warning("[ENERGY] No 'total' in energy response for archive %s", archive.id)
  1068. else:
  1069. logger.info("[ENERGY] No smart plug found for printer %s", printer_id)
  1070. except Exception as e:
  1071. logger.warning("Failed to record starting energy: %s", e)
  1072. await ws_manager.send_archive_updated(
  1073. {
  1074. "id": archive.id,
  1075. "status": "printing",
  1076. }
  1077. )
  1078. # Send notification with archive data (reprint/scheduled)
  1079. if not notification_sent:
  1080. archive_data = {"print_time_seconds": archive.print_time_seconds}
  1081. await _send_print_start_notification(printer_id, data, archive_data, logger)
  1082. # Extract printable objects from the archived 3MF file
  1083. _load_objects_from_archive(archive, printer_id, logger)
  1084. # Store Spoolman tracking data for per-filament usage reporting
  1085. try:
  1086. await _store_spoolman_print_data(printer_id, archive.id, archive.file_path, db, printer_manager)
  1087. except Exception as e:
  1088. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  1089. return # Skip creating a new archive
  1090. # Check if there's already a "printing" archive for this printer/file
  1091. # This prevents duplicates when backend restarts during an active print
  1092. from backend.app.models.archive import PrintArchive
  1093. check_name = subtask_name or filename.split("/")[-1].replace(".gcode", "").replace(".3mf", "")
  1094. existing = await db.execute(
  1095. select(PrintArchive)
  1096. .where(PrintArchive.printer_id == printer_id)
  1097. .where(PrintArchive.status == "printing")
  1098. .where(PrintArchive.print_name.ilike(f"%{check_name}%"))
  1099. .order_by(PrintArchive.created_at.desc())
  1100. .limit(1)
  1101. )
  1102. existing_archive = existing.scalar_one_or_none()
  1103. if existing_archive:
  1104. # Check if archive is stale (older than 4 hours) - likely a failed/cancelled print
  1105. # that didn't get properly updated
  1106. archive_age = datetime.now(timezone.utc) - existing_archive.created_at.replace(tzinfo=timezone.utc)
  1107. if archive_age.total_seconds() > 4 * 60 * 60: # 4 hours
  1108. logger.warning(
  1109. f"Found stale 'printing' archive {existing_archive.id} (age: {archive_age}), "
  1110. f"marking as cancelled and creating new archive"
  1111. )
  1112. existing_archive.status = "cancelled"
  1113. existing_archive.failure_reason = "Stale - print likely cancelled or failed without status update"
  1114. await db.commit()
  1115. # Fall through to create new archive (don't return)
  1116. _existing_archive = None # Clear so we don't use stale archive
  1117. else:
  1118. logger.info(
  1119. f"Skipping duplicate - already have printing archive {existing_archive.id} for {check_name}"
  1120. )
  1121. # Track this as the active print
  1122. _active_prints[(printer_id, existing_archive.filename)] = existing_archive.id
  1123. # Also set up energy tracking if not already tracked
  1124. if existing_archive.id not in _print_energy_start:
  1125. try:
  1126. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  1127. plug = plug_result.scalar_one_or_none()
  1128. if plug:
  1129. energy = await _get_plug_energy(plug, db)
  1130. if energy and energy.get("total") is not None:
  1131. _print_energy_start[existing_archive.id] = energy["total"]
  1132. logger.info(
  1133. f"Recorded starting energy for existing archive {existing_archive.id}: {energy['total']} kWh"
  1134. )
  1135. except Exception as e:
  1136. logger.warning("Failed to record starting energy for existing archive: %s", e)
  1137. # Send notification with archive data (existing archive)
  1138. if not notification_sent:
  1139. archive_data = {"print_time_seconds": existing_archive.print_time_seconds}
  1140. await _send_print_start_notification(printer_id, data, archive_data, logger)
  1141. # Extract printable objects from the archived 3MF file
  1142. _load_objects_from_archive(existing_archive, printer_id, logger)
  1143. return
  1144. # Build list of possible 3MF filenames to try
  1145. possible_names = []
  1146. # Bambu printers typically store files as "Name.gcode.3mf"
  1147. # The subtask_name is usually the best source for the filename
  1148. if subtask_name:
  1149. # Try common Bambu naming patterns
  1150. possible_names.append(f"{subtask_name}.gcode.3mf")
  1151. possible_names.append(f"{subtask_name}.3mf")
  1152. # Try original filename with .3mf extension
  1153. if filename:
  1154. # Extract just the filename part, not the full path
  1155. fname = filename.split("/")[-1] if "/" in filename else filename
  1156. if fname.endswith(".3mf"):
  1157. possible_names.append(fname)
  1158. elif fname.endswith(".gcode"):
  1159. base = fname.rsplit(".", 1)[0]
  1160. possible_names.append(f"{base}.gcode.3mf")
  1161. possible_names.append(f"{base}.3mf")
  1162. else:
  1163. possible_names.append(f"{fname}.gcode.3mf")
  1164. possible_names.append(f"{fname}.3mf")
  1165. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  1166. space_variants = []
  1167. for name in possible_names:
  1168. if " " in name:
  1169. space_variants.append(name.replace(" ", "_"))
  1170. possible_names.extend(space_variants)
  1171. # Remove duplicates while preserving order
  1172. seen = set()
  1173. possible_names = [x for x in possible_names if not (x in seen or seen.add(x))]
  1174. logger.info("Trying filenames: %s", possible_names)
  1175. # Try to find and download the 3MF file
  1176. temp_path = None
  1177. downloaded_filename = None
  1178. # Get FTP retry settings
  1179. ftp_retry_enabled, ftp_retry_count, ftp_retry_delay, ftp_timeout = await get_ftp_retry_settings()
  1180. for try_filename in possible_names:
  1181. if not try_filename.endswith(".3mf"):
  1182. continue
  1183. remote_paths = [
  1184. f"/cache/{try_filename}",
  1185. f"/model/{try_filename}",
  1186. f"/data/{try_filename}",
  1187. f"/data/Metadata/{try_filename}",
  1188. f"/{try_filename}",
  1189. ]
  1190. temp_path = app_settings.archive_dir / "temp" / try_filename
  1191. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1192. for remote_path in remote_paths:
  1193. logger.debug("Trying FTP download: %s", remote_path)
  1194. try:
  1195. if ftp_retry_enabled:
  1196. downloaded = await with_ftp_retry(
  1197. download_file_async,
  1198. printer.ip_address,
  1199. printer.access_code,
  1200. remote_path,
  1201. temp_path,
  1202. socket_timeout=ftp_timeout,
  1203. printer_model=printer.model,
  1204. max_retries=ftp_retry_count,
  1205. retry_delay=ftp_retry_delay,
  1206. operation_name=f"Download 3MF from {remote_path}",
  1207. )
  1208. else:
  1209. downloaded = await download_file_async(
  1210. printer.ip_address,
  1211. printer.access_code,
  1212. remote_path,
  1213. temp_path,
  1214. socket_timeout=ftp_timeout,
  1215. printer_model=printer.model,
  1216. )
  1217. if downloaded:
  1218. downloaded_filename = try_filename
  1219. logger.info("Downloaded: %s", remote_path)
  1220. break
  1221. except Exception as e:
  1222. logger.debug("FTP download failed for %s: %s", remote_path, e)
  1223. if downloaded_filename:
  1224. break
  1225. # If still not found, try listing directories to find matching file
  1226. # Different printer models use different directory structures
  1227. if not downloaded_filename and (filename or subtask_name):
  1228. search_term = (subtask_name or filename).lower().replace(".gcode", "").replace(".3mf", "")
  1229. logger.info("Direct FTP download failed, searching directories for '%s'", search_term)
  1230. search_dirs = ["/cache", "/model", "/data", "/data/Metadata", "/"]
  1231. for search_dir in search_dirs:
  1232. if downloaded_filename:
  1233. break
  1234. try:
  1235. dir_files = await list_files_async(
  1236. printer.ip_address, printer.access_code, search_dir, printer_model=printer.model
  1237. )
  1238. threemf_files = [f.get("name") for f in dir_files if f.get("name", "").endswith(".3mf")]
  1239. if threemf_files:
  1240. logger.info(
  1241. f"Found {len(threemf_files)} 3MF files in {search_dir}: {threemf_files[:5]}{'...' if len(threemf_files) > 5 else ''}"
  1242. )
  1243. for f in dir_files:
  1244. if f.get("is_directory"):
  1245. continue
  1246. fname = f.get("name", "")
  1247. # Normalize both for comparison (spaces and underscores are equivalent)
  1248. fname_normalized = fname.lower().replace(" ", "_")
  1249. search_normalized = search_term.replace(" ", "_")
  1250. if fname.endswith(".3mf") and search_normalized in fname_normalized:
  1251. logger.info("Found matching file in %s: %s", search_dir, fname)
  1252. temp_path = app_settings.archive_dir / "temp" / fname
  1253. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1254. if ftp_retry_enabled:
  1255. downloaded = await with_ftp_retry(
  1256. download_file_async,
  1257. printer.ip_address,
  1258. printer.access_code,
  1259. f"{search_dir}/{fname}",
  1260. temp_path,
  1261. socket_timeout=ftp_timeout,
  1262. printer_model=printer.model,
  1263. max_retries=ftp_retry_count,
  1264. retry_delay=ftp_retry_delay,
  1265. operation_name=f"Download 3MF from {search_dir}/{fname}",
  1266. )
  1267. else:
  1268. downloaded = await download_file_async(
  1269. printer.ip_address,
  1270. printer.access_code,
  1271. f"{search_dir}/{fname}",
  1272. temp_path,
  1273. socket_timeout=ftp_timeout,
  1274. printer_model=printer.model,
  1275. )
  1276. if downloaded:
  1277. downloaded_filename = fname
  1278. logger.info("Found and downloaded from %s: %s", search_dir, fname)
  1279. break
  1280. except Exception as e:
  1281. logger.debug("Failed to list %s: %s", search_dir, e)
  1282. if not downloaded_filename or not temp_path:
  1283. logger.warning("Could not find 3MF file for print: %s", filename or subtask_name)
  1284. # Create a fallback archive without 3MF data so the print is still tracked
  1285. # This commonly happens with P1S/A1 printers where FTP has file size limitations
  1286. try:
  1287. from backend.app.models.archive import PrintArchive
  1288. # Derive print name from subtask_name or filename
  1289. print_name = subtask_name or filename
  1290. if print_name:
  1291. # Clean up the name (remove extensions, path parts)
  1292. print_name = print_name.split("/")[-1]
  1293. print_name = print_name.replace(".gcode.3mf", "").replace(".gcode", "").replace(".3mf", "")
  1294. else:
  1295. print_name = "Unknown Print"
  1296. # Create minimal archive entry
  1297. fallback_archive = PrintArchive(
  1298. printer_id=printer_id,
  1299. filename=filename or f"{print_name}.3mf",
  1300. file_path="", # Empty - no 3MF file available
  1301. file_size=0,
  1302. print_name=print_name,
  1303. status="printing",
  1304. started_at=datetime.now(),
  1305. extra_data={"no_3mf_available": True, "original_subtask": subtask_name, "_print_data": data},
  1306. )
  1307. db.add(fallback_archive)
  1308. await db.commit()
  1309. await db.refresh(fallback_archive)
  1310. logger.info("Created fallback archive %s for %s (no 3MF available)", fallback_archive.id, print_name)
  1311. # Start timelapse session if external camera is enabled
  1312. if printer.external_camera_enabled and printer.external_camera_url:
  1313. from backend.app.services.layer_timelapse import start_session
  1314. start_session(
  1315. printer_id,
  1316. fallback_archive.id,
  1317. printer.external_camera_url,
  1318. printer.external_camera_type or "mjpeg",
  1319. )
  1320. logger.info("Started layer timelapse for printer %s, archive %s", printer_id, fallback_archive.id)
  1321. # Track as active print
  1322. _active_prints[(printer_id, fallback_archive.filename)] = fallback_archive.id
  1323. if filename:
  1324. _active_prints[(printer_id, filename)] = fallback_archive.id
  1325. if subtask_name:
  1326. _active_prints[(printer_id, f"{subtask_name}.3mf")] = fallback_archive.id
  1327. _active_prints[(printer_id, subtask_name)] = fallback_archive.id
  1328. # Record starting energy if smart plug available
  1329. try:
  1330. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  1331. plug = plug_result.scalar_one_or_none()
  1332. if plug:
  1333. energy = await _get_plug_energy(plug, db)
  1334. if energy and energy.get("total") is not None:
  1335. _print_energy_start[fallback_archive.id] = energy["total"]
  1336. logger.info(
  1337. f"[ENERGY] Recorded starting energy for fallback archive {fallback_archive.id}: {energy['total']} kWh"
  1338. )
  1339. except Exception as e:
  1340. logger.warning("Failed to record starting energy for fallback: %s", e)
  1341. # Send WebSocket notification
  1342. await ws_manager.send_archive_created(
  1343. {
  1344. "id": fallback_archive.id,
  1345. "printer_id": fallback_archive.printer_id,
  1346. "filename": fallback_archive.filename,
  1347. "print_name": fallback_archive.print_name,
  1348. "status": fallback_archive.status,
  1349. }
  1350. )
  1351. # MQTT relay - publish archive created
  1352. try:
  1353. await mqtt_relay.on_archive_created(
  1354. archive_id=fallback_archive.id,
  1355. print_name=fallback_archive.print_name,
  1356. printer_name=printer.name,
  1357. status=fallback_archive.status,
  1358. )
  1359. except Exception:
  1360. pass # Don't fail if MQTT fails
  1361. # Store Spoolman tracking data (may not work for fallback since no 3MF)
  1362. try:
  1363. await _store_spoolman_print_data(
  1364. printer_id, fallback_archive.id, fallback_archive.file_path, db, printer_manager
  1365. )
  1366. except Exception as e:
  1367. logger.debug("[SPOOLMAN] Could not store tracking for fallback archive: %s", e)
  1368. # Send notification without archive data (file not found)
  1369. if not notification_sent:
  1370. await _send_print_start_notification(printer_id, data, logger=logger)
  1371. return
  1372. except Exception as e:
  1373. logger.error("Failed to create fallback archive: %s", e)
  1374. # Send notification without archive data (file not found)
  1375. if not notification_sent:
  1376. await _send_print_start_notification(printer_id, data, logger=logger)
  1377. return
  1378. try:
  1379. # Archive the file with status "printing"
  1380. service = ArchiveService(db)
  1381. archive = await service.archive_print(
  1382. printer_id=printer_id,
  1383. source_file=temp_path,
  1384. print_data={**data, "status": "printing"},
  1385. )
  1386. if archive:
  1387. # Track this active print (use both original filename and downloaded filename)
  1388. _active_prints[(printer_id, downloaded_filename)] = archive.id
  1389. if filename and filename != downloaded_filename:
  1390. _active_prints[(printer_id, filename)] = archive.id
  1391. if subtask_name:
  1392. _active_prints[(printer_id, f"{subtask_name}.3mf")] = archive.id
  1393. logger.info("Created archive %s for %s", archive.id, downloaded_filename)
  1394. # Start timelapse session if external camera is enabled
  1395. if printer.external_camera_enabled and printer.external_camera_url:
  1396. from backend.app.services.layer_timelapse import start_session
  1397. start_session(
  1398. printer_id,
  1399. archive.id,
  1400. printer.external_camera_url,
  1401. printer.external_camera_type or "mjpeg",
  1402. )
  1403. logger.info("Started layer timelapse for printer %s, archive %s", printer_id, archive.id)
  1404. # Record starting energy from smart plug if available
  1405. try:
  1406. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  1407. plug = plug_result.scalar_one_or_none()
  1408. logger.info(
  1409. f"[ENERGY] Auto-archive print start - archive {archive.id}, printer {printer_id}, plug found: {plug is not None}"
  1410. )
  1411. if plug:
  1412. energy = await _get_plug_energy(plug, db)
  1413. logger.info("[ENERGY] Auto-archive energy response: %s", energy)
  1414. if energy and energy.get("total") is not None:
  1415. _print_energy_start[archive.id] = energy["total"]
  1416. logger.info(
  1417. f"[ENERGY] Recorded starting energy for archive {archive.id}: {energy['total']} kWh"
  1418. )
  1419. else:
  1420. logger.warning("[ENERGY] No 'total' in energy response for archive %s", archive.id)
  1421. else:
  1422. logger.info("[ENERGY] No smart plug found for printer %s", printer_id)
  1423. except Exception as e:
  1424. logger.warning("Failed to record starting energy: %s", e)
  1425. await ws_manager.send_archive_created(
  1426. {
  1427. "id": archive.id,
  1428. "printer_id": archive.printer_id,
  1429. "filename": archive.filename,
  1430. "print_name": archive.print_name,
  1431. "status": archive.status,
  1432. }
  1433. )
  1434. # MQTT relay - publish archive created
  1435. try:
  1436. await mqtt_relay.on_archive_created(
  1437. archive_id=archive.id,
  1438. print_name=archive.print_name,
  1439. printer_name=printer.name,
  1440. status=archive.status,
  1441. )
  1442. except Exception:
  1443. pass # Don't fail if MQTT fails
  1444. # Send notification with archive data (new archive created)
  1445. if not notification_sent:
  1446. archive_data = {"print_time_seconds": archive.print_time_seconds}
  1447. await _send_print_start_notification(printer_id, data, archive_data, logger)
  1448. # Extract printable objects for skip object functionality
  1449. try:
  1450. from backend.app.services.archive import extract_printable_objects_from_3mf
  1451. with open(temp_path, "rb") as f:
  1452. threemf_data = f.read()
  1453. # Extract with positions for UI overlay
  1454. printable_objects, bbox_all = extract_printable_objects_from_3mf(
  1455. threemf_data, include_positions=True
  1456. )
  1457. if printable_objects:
  1458. # Store objects in printer state
  1459. client = printer_manager.get_client(printer_id)
  1460. if client:
  1461. client.state.printable_objects = printable_objects
  1462. client.state.printable_objects_bbox_all = bbox_all
  1463. client.state.skipped_objects = [] # Reset skipped objects for new print
  1464. logger.info(
  1465. "Loaded %s printable objects for printer %s", len(printable_objects), printer_id
  1466. )
  1467. except Exception as e:
  1468. logger.debug("Failed to extract printable objects: %s", e)
  1469. # Store Spoolman tracking data for per-filament usage reporting
  1470. try:
  1471. await _store_spoolman_print_data(printer_id, archive.id, archive.file_path, db, printer_manager)
  1472. except Exception as e:
  1473. logger.warning("[SPOOLMAN] Failed to store tracking data: %s", e)
  1474. # Capture timelapse file baseline for snapshot-diff on completion
  1475. try:
  1476. baseline_files, _ = await _list_timelapse_mp4s(printer)
  1477. _timelapse_baselines[printer_id] = {f.get("name", "") for f in baseline_files}
  1478. logger.info(
  1479. "[TIMELAPSE] Baseline at print start: %s MP4 files for printer %s",
  1480. len(_timelapse_baselines[printer_id]),
  1481. printer_id,
  1482. )
  1483. except Exception as e:
  1484. logger.warning("[TIMELAPSE] Failed to capture baseline at print start: %s", e)
  1485. finally:
  1486. if temp_path and temp_path.exists():
  1487. temp_path.unlink()
  1488. async def _list_timelapse_mp4s(printer) -> tuple[list[dict], str | None]:
  1489. """List MP4 files from printer's timelapse directory.
  1490. Returns (mp4_files, found_path) where mp4_files is a list of file dicts
  1491. and found_path is the directory where they were found, or ([], None).
  1492. """
  1493. from backend.app.services.bambu_ftp import list_files_async
  1494. logger = logging.getLogger(__name__)
  1495. for timelapse_path in ["/timelapse", "/timelapse/video", "/record", "/recording"]:
  1496. try:
  1497. found_files = await list_files_async(
  1498. printer.ip_address, printer.access_code, timelapse_path, printer_model=printer.model
  1499. )
  1500. if found_files:
  1501. mp4_files = [f for f in found_files if not f.get("is_directory") and f.get("name", "").endswith(".mp4")]
  1502. if mp4_files:
  1503. return mp4_files, timelapse_path
  1504. except Exception as e:
  1505. logger.debug("[TIMELAPSE] Path %s failed: %s", timelapse_path, e)
  1506. continue
  1507. return [], None
  1508. async def _scan_for_timelapse_with_retries(archive_id: int, baseline_names: set[str] | None = None):
  1509. """
  1510. Scan for timelapse with retries using a snapshot-diff approach.
  1511. Instead of picking the "most recent by mtime" (unreliable when the printer
  1512. clock is wrong in LAN-only mode), we snapshot existing MP4 filenames BEFORE
  1513. waiting, then look for any NEW filename that appears after each delay.
  1514. If baseline_names is provided (captured at print start), it is used directly.
  1515. Otherwise falls back to taking a baseline at completion time (best-effort
  1516. for prints started before app restart).
  1517. Falls back to name-matching (print name contained in MP4 filename) if no
  1518. new file appears after all retries.
  1519. """
  1520. from pathlib import Path
  1521. logger = logging.getLogger(__name__)
  1522. # --- Phase 1: Take baseline snapshot of existing timelapse files ---
  1523. try:
  1524. async with async_session() as db:
  1525. from backend.app.models.printer import Printer
  1526. service = ArchiveService(db)
  1527. archive = await service.get_archive(archive_id)
  1528. if not archive:
  1529. logger.warning("[TIMELAPSE] Archive %s not found, aborting", archive_id)
  1530. return
  1531. if archive.timelapse_path:
  1532. logger.info("[TIMELAPSE] Archive %s already has timelapse attached", archive_id)
  1533. return
  1534. if not archive.printer_id:
  1535. logger.warning("[TIMELAPSE] Archive %s has no printer, aborting", archive_id)
  1536. return
  1537. if baseline_names is not None:
  1538. # Use pre-captured baseline from print start (no race condition)
  1539. logger.info(
  1540. "[TIMELAPSE] Using print-start baseline: %s existing MP4 files for archive %s",
  1541. len(baseline_names),
  1542. archive_id,
  1543. )
  1544. else:
  1545. # Fallback: take baseline now (e.g. app restarted mid-print)
  1546. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  1547. printer = result.scalar_one_or_none()
  1548. if not printer:
  1549. logger.warning("[TIMELAPSE] Printer not found for archive %s, aborting", archive_id)
  1550. return
  1551. baseline_files, _ = await _list_timelapse_mp4s(printer)
  1552. baseline_names = {f.get("name", "") for f in baseline_files}
  1553. logger.info(
  1554. "[TIMELAPSE] Baseline snapshot (fallback): %s existing MP4 files for archive %s",
  1555. len(baseline_names),
  1556. archive_id,
  1557. )
  1558. # Derive base_name for name-matching fallback
  1559. base_name = Path(archive.filename).stem if archive.filename else ""
  1560. if base_name.endswith(".gcode"):
  1561. base_name = base_name[:-6]
  1562. except Exception as e:
  1563. logger.warning("[TIMELAPSE] Failed to take baseline snapshot for archive %s: %s", archive_id, e)
  1564. return
  1565. # --- Phase 2: Retry loop — look for NEW files that weren't in baseline ---
  1566. retry_delays = [5, 10, 20, 30]
  1567. for attempt, delay in enumerate(retry_delays, 1):
  1568. logger.info(
  1569. "[TIMELAPSE] Attempt %s/%s: waiting %ss before scanning for archive %s",
  1570. attempt,
  1571. len(retry_delays),
  1572. delay,
  1573. archive_id,
  1574. )
  1575. await asyncio.sleep(delay)
  1576. try:
  1577. async with async_session() as db:
  1578. from backend.app.models.printer import Printer
  1579. from backend.app.services.bambu_ftp import download_file_bytes_async
  1580. service = ArchiveService(db)
  1581. archive = await service.get_archive(archive_id)
  1582. if not archive:
  1583. logger.warning("[TIMELAPSE] Archive %s not found, stopping retries", archive_id)
  1584. return
  1585. if archive.timelapse_path:
  1586. logger.info("[TIMELAPSE] Archive %s already has timelapse attached, stopping retries", archive_id)
  1587. return
  1588. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  1589. printer = result.scalar_one_or_none()
  1590. if not printer:
  1591. logger.warning("[TIMELAPSE] Printer not found for archive %s, stopping retries", archive_id)
  1592. return
  1593. mp4_files, found_path = await _list_timelapse_mp4s(printer)
  1594. if not mp4_files:
  1595. logger.info("[TIMELAPSE] Attempt %s: No MP4 files found, will retry", attempt)
  1596. continue
  1597. logger.info("[TIMELAPSE] Attempt %s: Found %s MP4 files in %s", attempt, len(mp4_files), found_path)
  1598. for f in mp4_files[:5]:
  1599. logger.info("[TIMELAPSE] - %s", f.get("name"))
  1600. # Find files that are NEW (not in baseline snapshot)
  1601. new_files = [f for f in mp4_files if f.get("name", "") not in baseline_names]
  1602. if new_files:
  1603. # Pick the first new file (there should typically be exactly one)
  1604. target = new_files[0]
  1605. file_name = target.get("name")
  1606. remote_path = target.get("path") or f"/timelapse/{file_name}"
  1607. logger.info(
  1608. "[TIMELAPSE] Attempt %s: New file detected: %s (downloading for archive %s)",
  1609. attempt,
  1610. file_name,
  1611. archive_id,
  1612. )
  1613. timelapse_data = await download_file_bytes_async(
  1614. printer.ip_address, printer.access_code, remote_path, printer_model=printer.model
  1615. )
  1616. if timelapse_data:
  1617. success = await service.attach_timelapse(archive_id, timelapse_data, file_name)
  1618. if success:
  1619. logger.info("[TIMELAPSE] Successfully attached timelapse to archive %s", archive_id)
  1620. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  1621. return
  1622. else:
  1623. logger.warning("[TIMELAPSE] Failed to attach timelapse to archive %s", archive_id)
  1624. else:
  1625. logger.warning("[TIMELAPSE] Attempt %s: Failed to download new file, will retry", attempt)
  1626. else:
  1627. logger.info("[TIMELAPSE] Attempt %s: No new files since baseline, will retry", attempt)
  1628. except Exception as e:
  1629. logger.warning("[TIMELAPSE] Attempt %s failed with error: %s", attempt, e)
  1630. # --- Phase 3: Fallback — try name matching against all files ---
  1631. if base_name:
  1632. logger.info("[TIMELAPSE] Retries exhausted, trying name-match fallback for '%s'", base_name)
  1633. try:
  1634. async with async_session() as db:
  1635. from backend.app.models.printer import Printer
  1636. from backend.app.services.bambu_ftp import download_file_bytes_async
  1637. service = ArchiveService(db)
  1638. archive = await service.get_archive(archive_id)
  1639. if not archive or archive.timelapse_path:
  1640. return
  1641. result = await db.execute(select(Printer).where(Printer.id == archive.printer_id))
  1642. printer = result.scalar_one_or_none()
  1643. if not printer:
  1644. return
  1645. mp4_files, found_path = await _list_timelapse_mp4s(printer)
  1646. for f in mp4_files:
  1647. fname = f.get("name", "")
  1648. if base_name.lower() in fname.lower():
  1649. remote_path = f.get("path") or f"/timelapse/{fname}"
  1650. logger.info("[TIMELAPSE] Name-match fallback: '%s' matches '%s'", base_name, fname)
  1651. timelapse_data = await download_file_bytes_async(
  1652. printer.ip_address, printer.access_code, remote_path, printer_model=printer.model
  1653. )
  1654. if timelapse_data:
  1655. success = await service.attach_timelapse(archive_id, timelapse_data, fname)
  1656. if success:
  1657. logger.info(
  1658. "[TIMELAPSE] Name-match fallback attached timelapse to archive %s", archive_id
  1659. )
  1660. await ws_manager.send_archive_updated({"id": archive_id, "timelapse_attached": True})
  1661. return
  1662. break # Only try the first name match
  1663. except Exception as e:
  1664. logger.warning("[TIMELAPSE] Name-match fallback failed: %s", e)
  1665. logger.warning("[TIMELAPSE] All attempts exhausted for archive %s, giving up", archive_id)
  1666. async def on_print_complete(printer_id: int, data: dict):
  1667. """Handle print completion - update the archive status."""
  1668. import time
  1669. logger = logging.getLogger(__name__)
  1670. start_time = time.time()
  1671. def log_timing(section: str):
  1672. elapsed = time.time() - start_time
  1673. logger.info("[TIMING] %s: %.3fs elapsed", section, elapsed)
  1674. logger.info("[CALLBACK] on_print_complete started for printer %s", printer_id)
  1675. try:
  1676. ws_data = {
  1677. "status": data.get("status"),
  1678. "filename": data.get("filename"),
  1679. "subtask_name": data.get("subtask_name"),
  1680. "timelapse_was_active": data.get("timelapse_was_active"),
  1681. }
  1682. await ws_manager.send_print_complete(printer_id, ws_data)
  1683. log_timing("WebSocket send_print_complete")
  1684. except Exception as e:
  1685. logger.warning("[CALLBACK] WebSocket send_print_complete failed: %s", e)
  1686. # Clear current print user tracking (Issue #206)
  1687. printer_manager.clear_current_print_user(printer_id)
  1688. # MQTT relay - publish print complete
  1689. try:
  1690. printer_info = printer_manager.get_printer(printer_id)
  1691. if printer_info:
  1692. await mqtt_relay.on_print_complete(
  1693. printer_id,
  1694. printer_info.name,
  1695. printer_info.serial_number,
  1696. data.get("filename", ""),
  1697. data.get("subtask_name", ""),
  1698. data.get("status", "completed"),
  1699. )
  1700. except Exception:
  1701. pass # Don't fail print complete callback if MQTT fails
  1702. filename = data.get("filename", "")
  1703. subtask_name = data.get("subtask_name", "")
  1704. if not filename and not subtask_name:
  1705. logger.warning("Print complete without filename or subtask_name")
  1706. return
  1707. logger.info("Print complete - filename: %s, subtask: %s, status: %s", filename, subtask_name, data.get("status"))
  1708. # Build list of possible keys to try (matching how they were registered in on_print_start)
  1709. possible_keys = []
  1710. # Try subtask_name variations first (most reliable for matching)
  1711. if subtask_name:
  1712. possible_keys.append((printer_id, f"{subtask_name}.3mf"))
  1713. possible_keys.append((printer_id, f"{subtask_name}.gcode.3mf"))
  1714. possible_keys.append((printer_id, subtask_name))
  1715. # Try filename variations
  1716. if filename:
  1717. # Extract just the filename if it's a path
  1718. fname = filename.split("/")[-1] if "/" in filename else filename
  1719. if fname.endswith(".3mf"):
  1720. possible_keys.append((printer_id, fname))
  1721. elif fname.endswith(".gcode"):
  1722. base_name = fname.rsplit(".", 1)[0]
  1723. possible_keys.append((printer_id, f"{base_name}.gcode.3mf"))
  1724. possible_keys.append((printer_id, f"{base_name}.3mf"))
  1725. possible_keys.append((printer_id, fname))
  1726. else:
  1727. possible_keys.append((printer_id, f"{fname}.gcode.3mf"))
  1728. possible_keys.append((printer_id, f"{fname}.3mf"))
  1729. possible_keys.append((printer_id, fname))
  1730. # Also try full path versions
  1731. if filename.endswith(".3mf"):
  1732. possible_keys.append((printer_id, filename))
  1733. elif filename.endswith(".gcode"):
  1734. base_name = filename.rsplit(".", 1)[0]
  1735. possible_keys.append((printer_id, f"{base_name}.3mf"))
  1736. possible_keys.append((printer_id, filename))
  1737. else:
  1738. possible_keys.append((printer_id, f"{filename}.3mf"))
  1739. possible_keys.append((printer_id, filename))
  1740. # Find the archive for this print
  1741. logger.info("Looking for archive in _active_prints, keys to try: %s...", possible_keys[:5])
  1742. logger.info("Current _active_prints: %s", list(_active_prints.keys()))
  1743. archive_id = None
  1744. for key in possible_keys:
  1745. archive_id = _active_prints.pop(key, None)
  1746. if archive_id:
  1747. logger.info("Found archive %s with key %s", archive_id, key)
  1748. # Also clean up any other keys pointing to this archive
  1749. keys_to_remove = [k for k, v in _active_prints.items() if v == archive_id]
  1750. for k in keys_to_remove:
  1751. _active_prints.pop(k, None)
  1752. break
  1753. if not archive_id:
  1754. # Try to find by filename or subtask_name if not tracked (for prints started before app)
  1755. async with async_session() as db:
  1756. from backend.app.models.archive import PrintArchive
  1757. # Try matching by subtask_name (stored as print_name) first
  1758. if subtask_name:
  1759. result = await db.execute(
  1760. select(PrintArchive)
  1761. .where(PrintArchive.printer_id == printer_id)
  1762. .where(PrintArchive.status == "printing")
  1763. .where(
  1764. or_(
  1765. PrintArchive.print_name.ilike(f"%{subtask_name}%"),
  1766. PrintArchive.filename.ilike(f"%{subtask_name}%"),
  1767. )
  1768. )
  1769. .order_by(PrintArchive.created_at.desc())
  1770. .limit(1)
  1771. )
  1772. archive = result.scalar_one_or_none()
  1773. if archive:
  1774. archive_id = archive.id
  1775. logger.info("Found archive %s by subtask_name match: %s", archive_id, subtask_name)
  1776. # Also try by filename
  1777. if not archive_id and filename:
  1778. result = await db.execute(
  1779. select(PrintArchive)
  1780. .where(PrintArchive.printer_id == printer_id)
  1781. .where(PrintArchive.filename == filename)
  1782. .where(PrintArchive.status == "printing")
  1783. .order_by(PrintArchive.created_at.desc())
  1784. .limit(1)
  1785. )
  1786. archive = result.scalar_one_or_none()
  1787. if archive:
  1788. archive_id = archive.id
  1789. if not archive_id:
  1790. logger.warning("Could not find archive for print complete: filename=%s, subtask=%s", filename, subtask_name)
  1791. return
  1792. log_timing("Archive lookup")
  1793. # Update archive status
  1794. logger.info("[ARCHIVE] Updating archive %s status...", archive_id)
  1795. try:
  1796. async with async_session() as db:
  1797. service = ArchiveService(db)
  1798. status = data.get("status", "completed")
  1799. # Auto-detect failure reason
  1800. failure_reason = None
  1801. if status == "aborted":
  1802. failure_reason = "User cancelled"
  1803. logger.info("[ARCHIVE] Print was aborted by user, setting failure_reason='User cancelled'")
  1804. elif status == "failed":
  1805. # Try to determine failure reason from HMS errors
  1806. hms_errors = data.get("hms_errors", [])
  1807. if hms_errors:
  1808. logger.info("[ARCHIVE] HMS errors at failure: %s", hms_errors)
  1809. # Map known HMS error modules to failure reasons
  1810. # Module 0x07 = Filament, 0x0C = MC (Motion Controller), etc.
  1811. for err in hms_errors:
  1812. module = err.get("module", 0)
  1813. if module == 0x07: # Filament module
  1814. failure_reason = "Filament runout"
  1815. break
  1816. elif module == 0x0C: # Motion controller
  1817. failure_reason = "Layer shift"
  1818. break
  1819. elif module == 0x05: # Nozzle/extruder
  1820. failure_reason = "Clogged nozzle"
  1821. break
  1822. if failure_reason:
  1823. logger.info("[ARCHIVE] Detected failure_reason from HMS: %s", failure_reason)
  1824. else:
  1825. logger.info("[ARCHIVE] No HMS errors available to determine failure reason")
  1826. await service.update_archive_status(
  1827. archive_id,
  1828. status=status,
  1829. completed_at=datetime.now() if status in ("completed", "failed", "aborted") else None,
  1830. failure_reason=failure_reason,
  1831. )
  1832. logger.info(
  1833. "[ARCHIVE] Archive %s status updated to %s, failure_reason=%s", archive_id, status, failure_reason
  1834. )
  1835. # Add cost for reprints (first prints have cost set in archive_print())
  1836. if status == "completed" and archive_id in _reprint_archives:
  1837. _reprint_archives.discard(archive_id)
  1838. try:
  1839. await service.add_reprint_cost(archive_id)
  1840. logger.info("[ARCHIVE] Added reprint cost for archive %s", archive_id)
  1841. except Exception as e:
  1842. logger.warning("[ARCHIVE] Failed to add reprint cost for archive %s: %s", archive_id, e)
  1843. await ws_manager.send_archive_updated(
  1844. {
  1845. "id": archive_id,
  1846. "status": status,
  1847. }
  1848. )
  1849. logger.info("[ARCHIVE] WebSocket notification sent for archive %s", archive_id)
  1850. # MQTT relay - publish archive updated
  1851. try:
  1852. await mqtt_relay.on_archive_updated(
  1853. archive_id=archive_id,
  1854. print_name=filename or subtask_name,
  1855. status=status,
  1856. )
  1857. except Exception:
  1858. pass # Don't fail if MQTT fails
  1859. except Exception as e:
  1860. logger.error("[ARCHIVE] Failed to update archive %s status: %s", archive_id, e, exc_info=True)
  1861. # Continue with other operations even if archive update fails
  1862. log_timing("Archive status update")
  1863. # Track filament consumption from AMS remain% deltas (skip if Spoolman handles usage)
  1864. usage_results: list[dict] = []
  1865. try:
  1866. async with async_session() as db:
  1867. from backend.app.api.routes.settings import get_setting
  1868. _spoolman_on = await get_setting(db, "spoolman_enabled")
  1869. if not _spoolman_on or _spoolman_on.lower() != "true":
  1870. from backend.app.services.usage_tracker import on_print_complete as usage_on_print_complete
  1871. async with async_session() as db:
  1872. usage_results = await usage_on_print_complete(
  1873. printer_id, data, printer_manager, db, archive_id=archive_id
  1874. )
  1875. if usage_results:
  1876. await ws_manager.broadcast(
  1877. {
  1878. "type": "spool_usage_logged",
  1879. "printer_id": printer_id,
  1880. "usage": usage_results,
  1881. }
  1882. )
  1883. log_timing("Usage tracker")
  1884. except Exception as e:
  1885. logger.warning("Usage tracker on_print_complete failed: %s", e)
  1886. # Report filament usage to Spoolman if print completed successfully
  1887. if data.get("status") == "completed":
  1888. try:
  1889. await _report_spoolman_usage(printer_id, archive_id)
  1890. log_timing("Spoolman usage report")
  1891. except Exception as e:
  1892. logger.warning("Spoolman usage reporting failed: %s", e)
  1893. else:
  1894. # Report partial usage if tracking data exists (only stored when weight sync is disabled)
  1895. try:
  1896. async with async_session() as db:
  1897. await _cleanup_spoolman_tracking(printer_id, archive_id, db)
  1898. except Exception as e:
  1899. logger.debug("[SPOOLMAN] Cleanup failed: %s", e)
  1900. # Run slow operations as background tasks to avoid blocking the event loop
  1901. # These operations can take 5-10+ seconds and would freeze the UI if awaited
  1902. starting_kwh = _print_energy_start.pop(archive_id, None)
  1903. async def _background_energy_calculation():
  1904. """Calculate and save energy usage in background."""
  1905. try:
  1906. logger.info("[ENERGY-BG] Starting energy calculation for archive %s", archive_id)
  1907. async with async_session() as db:
  1908. plug_result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  1909. plug = plug_result.scalar_one_or_none()
  1910. if plug:
  1911. energy = await _get_plug_energy(plug, db)
  1912. logger.info("[ENERGY-BG] Energy response: %s", energy)
  1913. energy_used = None
  1914. if starting_kwh is not None and energy and energy.get("total") is not None:
  1915. ending_kwh = energy["total"]
  1916. energy_used = round(ending_kwh - starting_kwh, 4)
  1917. logger.info("[ENERGY-BG] Per-print energy: %s kWh", energy_used)
  1918. if energy_used is not None and energy_used >= 0:
  1919. from backend.app.api.routes.settings import get_setting
  1920. energy_cost_per_kwh = await get_setting(db, "energy_cost_per_kwh")
  1921. cost_per_kwh = float(energy_cost_per_kwh) if energy_cost_per_kwh else 0.15
  1922. energy_cost = round(energy_used * cost_per_kwh, 2)
  1923. from backend.app.models.archive import PrintArchive
  1924. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1925. archive = result.scalar_one_or_none()
  1926. if archive:
  1927. archive.energy_kwh = energy_used
  1928. archive.energy_cost = energy_cost
  1929. await db.commit()
  1930. logger.info("[ENERGY-BG] Saved: %s kWh, cost=%s", energy_used, energy_cost)
  1931. else:
  1932. logger.info("[ENERGY-BG] No smart plug for printer %s", printer_id)
  1933. except Exception as e:
  1934. logger.warning("[ENERGY-BG] Failed: %s", e)
  1935. async def _background_finish_photo() -> str | None:
  1936. """Capture finish photo in background. Returns photo filename if captured."""
  1937. try:
  1938. logger.info("[PHOTO-BG] Starting finish photo capture for archive %s", archive_id)
  1939. from backend.app.api.routes.camera import _active_chamber_streams, _active_streams, get_buffered_frame
  1940. async with async_session() as db:
  1941. from backend.app.api.routes.settings import get_setting
  1942. capture_enabled = await get_setting(db, "capture_finish_photo")
  1943. if capture_enabled is None or capture_enabled.lower() == "true":
  1944. from backend.app.models.printer import Printer
  1945. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1946. printer = result.scalar_one_or_none()
  1947. if printer and archive_id:
  1948. from backend.app.models.archive import PrintArchive
  1949. result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  1950. archive = result.scalar_one_or_none()
  1951. if archive:
  1952. import uuid
  1953. from datetime import datetime
  1954. from pathlib import Path
  1955. archive_dir = app_settings.base_dir / Path(archive.file_path).parent
  1956. photo_filename = None
  1957. # Check for external camera first
  1958. if printer.external_camera_enabled and printer.external_camera_url:
  1959. logger.info("[PHOTO-BG] Using external camera")
  1960. from backend.app.services.external_camera import capture_frame
  1961. frame_data = await capture_frame(
  1962. printer.external_camera_url, printer.external_camera_type or "mjpeg"
  1963. )
  1964. if frame_data:
  1965. photos_dir = archive_dir / "photos"
  1966. photos_dir.mkdir(parents=True, exist_ok=True)
  1967. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  1968. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  1969. photo_path = photos_dir / photo_filename
  1970. await asyncio.to_thread(photo_path.write_bytes, frame_data)
  1971. logger.info("[PHOTO-BG] Saved external camera frame: %s", photo_filename)
  1972. else:
  1973. # Check if camera stream is active - use buffered frame to avoid freeze
  1974. # Check both RTSP streams (_active_streams) and chamber image streams (_active_chamber_streams)
  1975. active_for_printer = [k for k in _active_streams if k.startswith(f"{printer_id}-")]
  1976. active_chamber_for_printer = [
  1977. k for k in _active_chamber_streams if k.startswith(f"{printer_id}-")
  1978. ]
  1979. buffered_frame = get_buffered_frame(printer_id)
  1980. if (active_for_printer or active_chamber_for_printer) and buffered_frame:
  1981. # Use frame from active stream
  1982. logger.info("[PHOTO-BG] Using buffered frame from active stream")
  1983. photos_dir = archive_dir / "photos"
  1984. photos_dir.mkdir(parents=True, exist_ok=True)
  1985. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  1986. photo_filename = f"finish_{timestamp}_{uuid.uuid4().hex[:8]}.jpg"
  1987. photo_path = photos_dir / photo_filename
  1988. await asyncio.to_thread(photo_path.write_bytes, buffered_frame)
  1989. logger.info("[PHOTO-BG] Saved buffered frame: %s", photo_filename)
  1990. else:
  1991. # No active stream - capture new frame
  1992. from backend.app.services.camera import capture_finish_photo
  1993. photo_filename = await capture_finish_photo(
  1994. printer_id=printer_id,
  1995. ip_address=printer.ip_address,
  1996. access_code=printer.access_code,
  1997. model=printer.model,
  1998. archive_dir=archive_dir,
  1999. )
  2000. if photo_filename:
  2001. photos = archive.photos or []
  2002. photos.append(photo_filename)
  2003. archive.photos = photos
  2004. await db.commit()
  2005. logger.info("[PHOTO-BG] Saved: %s", photo_filename)
  2006. return photo_filename
  2007. return None
  2008. except Exception as e:
  2009. logger.warning("[PHOTO-BG] Failed: %s", e)
  2010. return None
  2011. asyncio.create_task(_background_energy_calculation())
  2012. # Photo capture task - result will be used by notifications
  2013. photo_task = asyncio.create_task(_background_finish_photo())
  2014. log_timing("Background tasks scheduled (energy, photo)")
  2015. # Also run smart plug, notifications, and maintenance as background tasks
  2016. print_status = data.get("status", "completed")
  2017. async def _background_smart_plug():
  2018. """Handle smart plug automation in background."""
  2019. try:
  2020. logger.info("[AUTO-OFF-BG] Starting smart plug automation for printer %s", printer_id)
  2021. async with async_session() as db:
  2022. await smart_plug_manager.on_print_complete(printer_id, print_status, db)
  2023. logger.info("[AUTO-OFF-BG] Completed")
  2024. except Exception as e:
  2025. logger.warning("[AUTO-OFF-BG] Failed: %s", e)
  2026. async def _background_notifications(finish_photo_filename: str | None = None):
  2027. """Send print complete notifications in background."""
  2028. try:
  2029. logger.info(
  2030. "[NOTIFY-BG] Starting notifications for printer %s, photo=%s", printer_id, finish_photo_filename
  2031. )
  2032. async with async_session() as db:
  2033. from backend.app.models.archive import PrintArchive
  2034. from backend.app.models.printer import Printer
  2035. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2036. printer = result.scalar_one_or_none()
  2037. printer_name = printer.name if printer else f"Printer {printer_id}"
  2038. archive_data = None
  2039. if archive_id:
  2040. archive_result = await db.execute(select(PrintArchive).where(PrintArchive.id == archive_id))
  2041. archive = archive_result.scalar_one_or_none()
  2042. if archive:
  2043. archive_data = {
  2044. "print_time_seconds": archive.print_time_seconds,
  2045. "actual_filament_grams": archive.filament_used_grams,
  2046. "failure_reason": archive.failure_reason,
  2047. }
  2048. # Scale filament usage for partial prints
  2049. if print_status != "completed" and archive.filament_used_grams:
  2050. progress = data.get("progress") or 0
  2051. scale = max(0.0, min(progress / 100.0, 1.0))
  2052. archive_data["actual_filament_grams"] = round(archive.filament_used_grams * scale, 1)
  2053. archive_data["progress"] = progress
  2054. # Pass per-slot data from archive.extra_data
  2055. if archive.extra_data and archive.extra_data.get("filament_slots"):
  2056. slots = archive.extra_data["filament_slots"]
  2057. if print_status != "completed":
  2058. scale = max(0.0, min((data.get("progress") or 0) / 100.0, 1.0))
  2059. slots = [{**s, "used_g": round(s["used_g"] * scale, 1)} for s in slots]
  2060. archive_data["filament_slots"] = slots
  2061. # Pass usage tracker results for AMS slot info in notifications
  2062. if usage_results:
  2063. archive_data["usage_results"] = usage_results
  2064. # Add finish photo URL and image bytes if available
  2065. if finish_photo_filename:
  2066. from backend.app.api.routes.settings import get_setting
  2067. external_url = await get_setting(db, "external_url")
  2068. if external_url:
  2069. external_url = external_url.rstrip("/")
  2070. archive_data["finish_photo_url"] = (
  2071. f"{external_url}/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  2072. )
  2073. else:
  2074. # Fallback to relative URL (won't work for external services)
  2075. archive_data["finish_photo_url"] = (
  2076. f"/api/v1/archives/{archive_id}/photos/{finish_photo_filename}"
  2077. )
  2078. # Read finish photo bytes for image attachment (e.g. Pushover)
  2079. try:
  2080. from pathlib import Path
  2081. photo_path = (
  2082. app_settings.base_dir
  2083. / Path(archive.file_path).parent
  2084. / "photos"
  2085. / finish_photo_filename
  2086. )
  2087. if photo_path.exists():
  2088. photo_bytes = await asyncio.to_thread(photo_path.read_bytes)
  2089. if len(photo_bytes) <= 2_500_000:
  2090. archive_data["image_data"] = photo_bytes
  2091. logger.info("[NOTIFY-BG] Loaded finish photo bytes: %s bytes", len(photo_bytes))
  2092. else:
  2093. logger.warning(
  2094. f"[NOTIFY-BG] Finish photo too large for attachment: "
  2095. f"{len(photo_bytes)} bytes"
  2096. )
  2097. except Exception as e:
  2098. logger.warning("[NOTIFY-BG] Failed to read finish photo bytes: %s", e)
  2099. await notification_service.on_print_complete(
  2100. printer_id, printer_name, print_status, data, db, archive_data=archive_data
  2101. )
  2102. logger.info("[NOTIFY-BG] Completed")
  2103. except Exception as e:
  2104. logger.warning("[NOTIFY-BG] Failed: %s", e)
  2105. async def _background_maintenance_check():
  2106. """Check for maintenance due in background."""
  2107. if print_status != "completed":
  2108. return
  2109. try:
  2110. logger.info("[MAINT-BG] Starting maintenance check for printer %s", printer_id)
  2111. async with async_session() as db:
  2112. from backend.app.models.printer import Printer
  2113. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2114. printer = result.scalar_one_or_none()
  2115. printer_name = printer.name if printer else f"Printer {printer_id}"
  2116. await ensure_default_types(db)
  2117. overview = await _get_printer_maintenance_internal(printer_id, db, commit=True)
  2118. items_needing_attention = [
  2119. {"name": item.maintenance_type_name, "is_due": item.is_due, "is_warning": item.is_warning}
  2120. for item in overview.maintenance_items
  2121. if item.enabled and (item.is_due or item.is_warning)
  2122. ]
  2123. if items_needing_attention:
  2124. await notification_service.on_maintenance_due(printer_id, printer_name, items_needing_attention, db)
  2125. logger.info("[MAINT-BG] Sent notification: %s items need attention", len(items_needing_attention))
  2126. # MQTT relay - publish maintenance alerts
  2127. for item in items_needing_attention:
  2128. try:
  2129. await mqtt_relay.on_maintenance_alert(
  2130. printer_id=printer_id,
  2131. printer_name=printer_name,
  2132. maintenance_type=item["name"],
  2133. current_value=0, # Not easily available here
  2134. threshold=0, # Not easily available here
  2135. )
  2136. except Exception:
  2137. pass # Don't fail if MQTT fails
  2138. else:
  2139. logger.info("[MAINT-BG] Completed (no items need attention)")
  2140. except Exception as e:
  2141. logger.warning("[MAINT-BG] Failed: %s", e)
  2142. asyncio.create_task(_background_smart_plug())
  2143. asyncio.create_task(_background_maintenance_check())
  2144. # Notification task waits for photo capture to complete first
  2145. async def _photo_then_notify():
  2146. """Wait for photo capture, then send notification with photo URL."""
  2147. try:
  2148. finish_photo = await photo_task
  2149. logger.info("[PHOTO-NOTIFY] Photo task returned: %s", finish_photo)
  2150. await _background_notifications(finish_photo)
  2151. except Exception as e:
  2152. logger.warning("[PHOTO-NOTIFY] Failed: %s", e)
  2153. # Still try to send notification without photo
  2154. await _background_notifications(None)
  2155. asyncio.create_task(_photo_then_notify())
  2156. # Stitch external camera layer timelapse if session was active
  2157. print_status = data.get("status", "completed")
  2158. async def _background_layer_timelapse():
  2159. """Stitch layer timelapse and attach to archive."""
  2160. from backend.app.services.layer_timelapse import cancel_session, on_print_complete as tl_complete
  2161. try:
  2162. if print_status == "completed":
  2163. logger.info("[LAYER-TL] Stitching layer timelapse for printer %s", printer_id)
  2164. timelapse_path = await tl_complete(printer_id)
  2165. if timelapse_path and archive_id:
  2166. logger.info("[LAYER-TL] Attaching timelapse %s to archive %s", timelapse_path, archive_id)
  2167. async with async_session() as db:
  2168. service = ArchiveService(db)
  2169. timelapse_data = await asyncio.to_thread(timelapse_path.read_bytes)
  2170. await service.attach_timelapse(archive_id, timelapse_data, "layer_timelapse.mp4")
  2171. # Clean up the temp file
  2172. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  2173. logger.info("[LAYER-TL] Layer timelapse attached successfully")
  2174. elif timelapse_path:
  2175. # Timelapse created but no archive - just clean up
  2176. await asyncio.to_thread(timelapse_path.unlink, missing_ok=True)
  2177. else:
  2178. # Print failed or cancelled - cancel timelapse session
  2179. cancel_session(printer_id)
  2180. logger.info(
  2181. "[LAYER-TL] Cancelled layer timelapse for printer %s (status: %s)", printer_id, print_status
  2182. )
  2183. except Exception as e:
  2184. logger.warning("[LAYER-TL] Failed: %s", e)
  2185. # Try to cancel session on error
  2186. try:
  2187. cancel_session(printer_id)
  2188. except Exception:
  2189. pass # Best-effort timelapse session cancellation on error
  2190. asyncio.create_task(_background_layer_timelapse())
  2191. log_timing("All background tasks scheduled")
  2192. # Auto-scan for timelapse if recording was active during the print
  2193. if archive_id and data.get("timelapse_was_active") and data.get("status") == "completed":
  2194. logger.info("[TIMELAPSE] Timelapse was active during print, scheduling auto-scan for archive %s", archive_id)
  2195. # Schedule timelapse scan as background task with retries
  2196. # The printer needs time to encode the video after print completion
  2197. baseline = _timelapse_baselines.pop(printer_id, None)
  2198. asyncio.create_task(_scan_for_timelapse_with_retries(archive_id, baseline))
  2199. log_timing("Timelapse scan scheduled")
  2200. # Update queue item if this was a scheduled print
  2201. try:
  2202. async with async_session() as db:
  2203. from backend.app.models.print_queue import PrintQueueItem
  2204. # Note: SmartPlug is already imported at module level (line 56)
  2205. # Do NOT import it here as it would shadow the module-level import
  2206. # and cause "cannot access local variable" errors earlier in this function
  2207. result = await db.execute(
  2208. select(PrintQueueItem)
  2209. .where(PrintQueueItem.printer_id == printer_id)
  2210. .where(PrintQueueItem.status == "printing")
  2211. )
  2212. queue_item = result.scalar_one_or_none()
  2213. if queue_item:
  2214. status = data.get("status", "completed")
  2215. queue_item.status = status
  2216. queue_item.completed_at = datetime.now()
  2217. await db.commit()
  2218. logger.info("Updated queue item %s status to %s", queue_item.id, status)
  2219. # MQTT relay - publish queue job completed
  2220. try:
  2221. printer_info = printer_manager.get_printer(printer_id)
  2222. await mqtt_relay.on_queue_job_completed(
  2223. job_id=queue_item.id,
  2224. filename=filename or subtask_name,
  2225. printer_id=printer_id,
  2226. printer_name=printer_info.name if printer_info else "Unknown",
  2227. status=status,
  2228. )
  2229. except Exception:
  2230. pass # Don't fail if MQTT fails
  2231. # Check if queue is now empty and send notification
  2232. try:
  2233. from sqlalchemy import func
  2234. # Count remaining pending items
  2235. count_result = await db.execute(
  2236. select(func.count(PrintQueueItem.id)).where(PrintQueueItem.status == "pending")
  2237. )
  2238. pending_count = count_result.scalar() or 0
  2239. if pending_count == 0:
  2240. # Count how many completed today (rough approximation)
  2241. today_start = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
  2242. completed_result = await db.execute(
  2243. select(func.count(PrintQueueItem.id)).where(
  2244. PrintQueueItem.status.in_(["completed", "failed", "skipped"]),
  2245. PrintQueueItem.completed_at >= today_start,
  2246. )
  2247. )
  2248. completed_count = completed_result.scalar() or 1
  2249. await notification_service.on_queue_completed(
  2250. completed_count=completed_count,
  2251. db=db,
  2252. )
  2253. except Exception:
  2254. pass # Don't fail if notification fails
  2255. # Handle auto_off_after - power off printer if requested (after cooldown)
  2256. if queue_item.auto_off_after:
  2257. result = await db.execute(select(SmartPlug).where(SmartPlug.printer_id == printer_id))
  2258. plug = result.scalar_one_or_none()
  2259. if plug and plug.enabled:
  2260. logger.info("Auto-off requested for printer %s, waiting for cooldown...", printer_id)
  2261. async def cooldown_and_poweroff(pid: int, plug_id: int):
  2262. # Wait for nozzle to cool down
  2263. await printer_manager.wait_for_cooldown(pid, target_temp=50.0, timeout=600)
  2264. # Re-fetch plug in new session
  2265. async with async_session() as new_db:
  2266. result = await new_db.execute(select(SmartPlug).where(SmartPlug.id == plug_id))
  2267. p = result.scalar_one_or_none()
  2268. if p and p.enabled:
  2269. success = await tasmota_service.turn_off(p)
  2270. if success:
  2271. logger.info("Powered off printer %s via smart plug '%s'", pid, p.name)
  2272. else:
  2273. logger.warning("Failed to power off printer %s via smart plug", pid)
  2274. asyncio.create_task(cooldown_and_poweroff(printer_id, plug.id))
  2275. except Exception as e:
  2276. logging.getLogger(__name__).warning(f"Queue item update failed: {e}")
  2277. log_timing("Queue item update")
  2278. logger.info("[CALLBACK] on_print_complete finished for printer %s, archive %s", printer_id, archive_id)
  2279. # AMS sensor history recording
  2280. _ams_history_task: asyncio.Task | None = None
  2281. AMS_HISTORY_INTERVAL = 300 # Record every 5 minutes
  2282. AMS_HISTORY_RETENTION_DAYS = 30 # Keep data for 30 days
  2283. _ams_cleanup_counter = 0 # Track recordings to trigger periodic cleanup
  2284. _ams_alarm_cooldown: dict[str, datetime] = {} # Track alarm cooldowns (printer_id:ams_id:type -> last_alarm_time)
  2285. AMS_ALARM_COOLDOWN_MINUTES = 60 # Don't send same alarm more than once per hour
  2286. async def record_ams_history():
  2287. """Background task to record AMS humidity and temperature data."""
  2288. logger = logging.getLogger(__name__)
  2289. # Wait a short time for MQTT connections to establish on startup
  2290. await asyncio.sleep(10)
  2291. while True:
  2292. try:
  2293. from backend.app.models.ams_history import AMSSensorHistory
  2294. from backend.app.models.printer import Printer
  2295. from backend.app.models.settings import Settings
  2296. async with async_session() as db:
  2297. # Get all active printers
  2298. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  2299. printers = result.scalars().all()
  2300. # Get alarm thresholds from settings
  2301. humidity_threshold = 60.0 # Default: fair threshold
  2302. temp_threshold = 35.0 # Default: fair threshold
  2303. result = await db.execute(select(Settings).where(Settings.key == "ams_humidity_fair"))
  2304. setting = result.scalar_one_or_none()
  2305. if setting:
  2306. try:
  2307. humidity_threshold = float(setting.value)
  2308. except (ValueError, TypeError):
  2309. pass # Keep default threshold if stored value is invalid
  2310. result = await db.execute(select(Settings).where(Settings.key == "ams_temp_fair"))
  2311. setting = result.scalar_one_or_none()
  2312. if setting:
  2313. try:
  2314. temp_threshold = float(setting.value)
  2315. except (ValueError, TypeError):
  2316. pass # Keep default threshold if stored value is invalid
  2317. recorded_count = 0
  2318. for printer in printers:
  2319. # Get current state from printer manager
  2320. state = printer_manager.get_status(printer.id)
  2321. if not state or not state.connected or not state.raw_data:
  2322. continue # Skip disconnected printers - don't use stale data
  2323. raw_data = state.raw_data
  2324. if "ams" not in raw_data or not isinstance(raw_data["ams"], list):
  2325. continue
  2326. # Record data for each AMS unit
  2327. for ams_data in raw_data["ams"]:
  2328. ams_id = int(ams_data.get("id", 0))
  2329. # Get humidity (prefer humidity_raw)
  2330. humidity_raw = ams_data.get("humidity_raw")
  2331. humidity_idx = ams_data.get("humidity")
  2332. humidity = None
  2333. if humidity_raw is not None:
  2334. try:
  2335. humidity = float(humidity_raw)
  2336. except (ValueError, TypeError):
  2337. pass # Skip unparseable humidity; will try fallback
  2338. if humidity is None and humidity_idx is not None:
  2339. try:
  2340. humidity = float(humidity_idx)
  2341. except (ValueError, TypeError):
  2342. pass # Skip unparseable humidity index value
  2343. # Get temperature
  2344. temperature = None
  2345. temp_str = ams_data.get("temp")
  2346. if temp_str is not None:
  2347. try:
  2348. temperature = float(temp_str)
  2349. except (ValueError, TypeError):
  2350. pass # Skip unparseable temperature value
  2351. # Skip if no data
  2352. if humidity is None and temperature is None:
  2353. continue
  2354. # Record the data point
  2355. history = AMSSensorHistory(
  2356. printer_id=printer.id,
  2357. ams_id=ams_id,
  2358. humidity=humidity,
  2359. humidity_raw=float(humidity_raw) if humidity_raw else None,
  2360. temperature=temperature,
  2361. )
  2362. db.add(history)
  2363. recorded_count += 1
  2364. # Generate AMS label and determine if it's AMS-HT (A, B, C, D or HT-A for AMS-Lite/Hub)
  2365. is_ams_ht = ams_id >= 128
  2366. if is_ams_ht:
  2367. ams_label = f"HT-{chr(65 + (ams_id - 128))}"
  2368. else:
  2369. ams_label = f"AMS-{chr(65 + ams_id)}"
  2370. # Check humidity alarm (only if above threshold)
  2371. if humidity is not None and humidity > humidity_threshold:
  2372. cooldown_key = f"{printer.id}:{ams_id}:humidity"
  2373. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  2374. now = datetime.now()
  2375. if (
  2376. last_alarm is None
  2377. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  2378. ):
  2379. _ams_alarm_cooldown[cooldown_key] = now
  2380. logger.info(
  2381. f"Sending humidity alarm for {printer.name} {ams_label}: {humidity}% > {humidity_threshold}%"
  2382. )
  2383. try:
  2384. # Call different notification method based on AMS type
  2385. if is_ams_ht:
  2386. await notification_service.on_ams_ht_humidity_high(
  2387. printer.id, printer.name, ams_label, humidity, humidity_threshold, db
  2388. )
  2389. else:
  2390. await notification_service.on_ams_humidity_high(
  2391. printer.id, printer.name, ams_label, humidity, humidity_threshold, db
  2392. )
  2393. except Exception as e:
  2394. logger.warning("Failed to send humidity alarm: %s", e)
  2395. # Check temperature alarm (only if above threshold)
  2396. if temperature is not None and temperature > temp_threshold:
  2397. cooldown_key = f"{printer.id}:{ams_id}:temperature"
  2398. last_alarm = _ams_alarm_cooldown.get(cooldown_key)
  2399. now = datetime.now()
  2400. if (
  2401. last_alarm is None
  2402. or (now - last_alarm).total_seconds() >= AMS_ALARM_COOLDOWN_MINUTES * 60
  2403. ):
  2404. _ams_alarm_cooldown[cooldown_key] = now
  2405. logger.info(
  2406. f"Sending temperature alarm for {printer.name} {ams_label}: {temperature}°C > {temp_threshold}°C"
  2407. )
  2408. try:
  2409. # Call different notification method based on AMS type
  2410. if is_ams_ht:
  2411. await notification_service.on_ams_ht_temperature_high(
  2412. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  2413. )
  2414. else:
  2415. await notification_service.on_ams_temperature_high(
  2416. printer.id, printer.name, ams_label, temperature, temp_threshold, db
  2417. )
  2418. except Exception as e:
  2419. logger.warning("Failed to send temperature alarm: %s", e)
  2420. await db.commit()
  2421. if recorded_count > 0:
  2422. logger.info("Recorded %s AMS sensor history entries", recorded_count)
  2423. # Periodic cleanup of old data (every ~288 recordings = ~24 hours at 5min interval)
  2424. global _ams_cleanup_counter
  2425. _ams_cleanup_counter += 1
  2426. if _ams_cleanup_counter >= 288:
  2427. _ams_cleanup_counter = 0
  2428. # Get retention days from settings
  2429. from backend.app.models.settings import Settings
  2430. result = await db.execute(select(Settings).where(Settings.key == "ams_history_retention_days"))
  2431. setting = result.scalar_one_or_none()
  2432. retention_days = int(setting.value) if setting else AMS_HISTORY_RETENTION_DAYS
  2433. cutoff = datetime.now() - timedelta(days=retention_days)
  2434. result = await db.execute(delete(AMSSensorHistory).where(AMSSensorHistory.recorded_at < cutoff))
  2435. await db.commit()
  2436. if result.rowcount > 0:
  2437. logger.info(
  2438. f"Cleaned up {result.rowcount} old AMS sensor history entries (older than {retention_days} days)"
  2439. )
  2440. # Wait until next recording interval
  2441. await asyncio.sleep(AMS_HISTORY_INTERVAL)
  2442. except asyncio.CancelledError:
  2443. break
  2444. except Exception as e:
  2445. logger.warning("AMS history recording failed: %s", e)
  2446. await asyncio.sleep(60) # Wait a bit before retrying
  2447. def start_ams_history_recording():
  2448. """Start the AMS history recording background task."""
  2449. global _ams_history_task
  2450. if _ams_history_task is None:
  2451. _ams_history_task = asyncio.create_task(record_ams_history())
  2452. logging.getLogger(__name__).info("AMS history recording started")
  2453. def stop_ams_history_recording():
  2454. """Stop the AMS history recording background task."""
  2455. global _ams_history_task
  2456. if _ams_history_task:
  2457. _ams_history_task.cancel()
  2458. _ams_history_task = None
  2459. logging.getLogger(__name__).info("AMS history recording stopped")
  2460. # Printer runtime tracking
  2461. _runtime_tracking_task: asyncio.Task | None = None
  2462. RUNTIME_TRACKING_INTERVAL = 30 # Update every 30 seconds
  2463. async def track_printer_runtime():
  2464. """Background task to track printer active runtime (RUNNING/PAUSE states)."""
  2465. logger = logging.getLogger(__name__)
  2466. # Wait for MQTT connections to establish on startup
  2467. await asyncio.sleep(15)
  2468. while True:
  2469. try:
  2470. from backend.app.models.printer import Printer
  2471. async with async_session() as db:
  2472. # Get all active printers
  2473. result = await db.execute(select(Printer).where(Printer.is_active.is_(True)))
  2474. printers = result.scalars().all()
  2475. now = datetime.now()
  2476. updated_count = 0
  2477. needs_commit = False
  2478. for printer in printers:
  2479. # Get current state from printer manager
  2480. state = printer_manager.get_status(printer.id)
  2481. if not state:
  2482. logger.debug("[%s] Runtime tracking: no state available", printer.name)
  2483. continue
  2484. if not state.connected:
  2485. logger.debug("[%s] Runtime tracking: not connected", printer.name)
  2486. continue
  2487. # Check if printer is in an active state (RUNNING or PAUSE)
  2488. if state.state in ("RUNNING", "PAUSE"):
  2489. # Calculate time since last update
  2490. if printer.last_runtime_update:
  2491. elapsed = (now - printer.last_runtime_update).total_seconds()
  2492. if elapsed > 0:
  2493. printer.runtime_seconds += int(elapsed)
  2494. updated_count += 1
  2495. needs_commit = True
  2496. logger.debug(
  2497. f"[{printer.name}] Runtime tracking: added {int(elapsed)}s, "
  2498. f"total={printer.runtime_seconds}s ({printer.runtime_seconds / 3600:.2f}h)"
  2499. )
  2500. else:
  2501. # First time seeing printer active - need to commit to save timestamp
  2502. needs_commit = True
  2503. logger.debug("[%s] Runtime tracking: first active detection", printer.name)
  2504. printer.last_runtime_update = now
  2505. else:
  2506. # Printer is idle/offline - clear last_runtime_update
  2507. if printer.last_runtime_update is not None:
  2508. logger.debug(
  2509. f"[{printer.name}] Runtime tracking: state={state.state}, clearing last_runtime_update"
  2510. )
  2511. printer.last_runtime_update = None
  2512. needs_commit = True
  2513. if needs_commit:
  2514. await db.commit()
  2515. if updated_count > 0:
  2516. logger.debug("Updated runtime for %s printer(s)", updated_count)
  2517. except asyncio.CancelledError:
  2518. logger.info("Runtime tracking cancelled")
  2519. break
  2520. except Exception as e:
  2521. logger.warning("Runtime tracking failed: %s", e)
  2522. await asyncio.sleep(RUNTIME_TRACKING_INTERVAL)
  2523. def start_runtime_tracking():
  2524. """Start the printer runtime tracking background task."""
  2525. global _runtime_tracking_task
  2526. if _runtime_tracking_task is None:
  2527. _runtime_tracking_task = asyncio.create_task(track_printer_runtime())
  2528. logging.getLogger(__name__).info("Printer runtime tracking started")
  2529. def stop_runtime_tracking():
  2530. """Stop the printer runtime tracking background task."""
  2531. global _runtime_tracking_task
  2532. if _runtime_tracking_task:
  2533. _runtime_tracking_task.cancel()
  2534. _runtime_tracking_task = None
  2535. logging.getLogger(__name__).info("Printer runtime tracking stopped")
  2536. @asynccontextmanager
  2537. async def lifespan(app: FastAPI):
  2538. # Startup
  2539. await init_db()
  2540. # Restore debug logging state from previous session
  2541. await init_debug_logging()
  2542. # Set up printer manager callbacks
  2543. loop = asyncio.get_event_loop()
  2544. printer_manager.set_event_loop(loop)
  2545. printer_manager.set_status_change_callback(on_printer_status_change)
  2546. printer_manager.set_print_start_callback(on_print_start)
  2547. printer_manager.set_print_complete_callback(on_print_complete)
  2548. printer_manager.set_ams_change_callback(on_ams_change)
  2549. # Layer change callback for external camera timelapse
  2550. async def on_layer_change(printer_id: int, layer_num: int):
  2551. """Capture timelapse frame on layer change."""
  2552. from backend.app.services.layer_timelapse import on_layer_change as tl_layer_change
  2553. await tl_layer_change(printer_id, layer_num)
  2554. printer_manager.set_layer_change_callback(on_layer_change)
  2555. # Initialize MQTT relay from settings
  2556. async with async_session() as db:
  2557. from backend.app.api.routes.settings import get_setting
  2558. mqtt_settings = {
  2559. "mqtt_enabled": (await get_setting(db, "mqtt_enabled") or "false") == "true",
  2560. "mqtt_broker": await get_setting(db, "mqtt_broker") or "",
  2561. "mqtt_port": int(await get_setting(db, "mqtt_port") or "1883"),
  2562. "mqtt_username": await get_setting(db, "mqtt_username") or "",
  2563. "mqtt_password": await get_setting(db, "mqtt_password") or "",
  2564. "mqtt_topic_prefix": await get_setting(db, "mqtt_topic_prefix") or "bambuddy",
  2565. "mqtt_use_tls": (await get_setting(db, "mqtt_use_tls") or "false") == "true",
  2566. }
  2567. await mqtt_relay.configure(mqtt_settings)
  2568. # Restore MQTT smart plug subscriptions
  2569. if mqtt_settings.get("mqtt_enabled"):
  2570. from backend.app.models.smart_plug import SmartPlug
  2571. result = await db.execute(select(SmartPlug).where(SmartPlug.plug_type == "mqtt"))
  2572. mqtt_plugs = result.scalars().all()
  2573. for plug in mqtt_plugs:
  2574. if plug.mqtt_topic:
  2575. mqtt_relay.smart_plug_service.subscribe(
  2576. plug_id=plug.id,
  2577. topic=plug.mqtt_topic,
  2578. power_path=plug.mqtt_power_path,
  2579. energy_path=plug.mqtt_energy_path,
  2580. state_path=plug.mqtt_state_path,
  2581. multiplier=plug.mqtt_multiplier or 1.0,
  2582. )
  2583. if mqtt_plugs:
  2584. logging.info("Restored %s MQTT smart plug subscriptions", len(mqtt_plugs))
  2585. # Connect to all active printers
  2586. async with async_session() as db:
  2587. await init_printer_connections(db)
  2588. # Auto-connect to Spoolman if enabled
  2589. async with async_session() as db:
  2590. from backend.app.api.routes.settings import get_setting
  2591. spoolman_enabled = await get_setting(db, "spoolman_enabled")
  2592. spoolman_url = await get_setting(db, "spoolman_url")
  2593. if spoolman_enabled and spoolman_enabled.lower() == "true" and spoolman_url:
  2594. try:
  2595. client = await init_spoolman_client(spoolman_url)
  2596. if await client.health_check():
  2597. logging.info("Auto-connected to Spoolman at %s", spoolman_url)
  2598. # Ensure the 'tag' extra field exists for RFID/UUID storage
  2599. await client.ensure_tag_extra_field()
  2600. else:
  2601. logging.warning("Spoolman at %s is not reachable", spoolman_url)
  2602. except Exception as e:
  2603. logging.warning("Failed to auto-connect to Spoolman: %s", e)
  2604. # Start the print scheduler
  2605. asyncio.create_task(print_scheduler.run())
  2606. # Start the smart plug scheduler for time-based on/off
  2607. smart_plug_manager.start_scheduler()
  2608. # Resume any pending auto-offs that were interrupted by restart
  2609. await smart_plug_manager.resume_pending_auto_offs()
  2610. # Start the notification digest scheduler
  2611. notification_service.start_digest_scheduler()
  2612. # Start the GitHub backup scheduler
  2613. await github_backup_service.start_scheduler()
  2614. # Start AMS history recording
  2615. start_ams_history_recording()
  2616. # Start printer runtime tracking
  2617. start_runtime_tracking()
  2618. # Initialize virtual printer manager
  2619. from backend.app.services.virtual_printer import virtual_printer_manager
  2620. virtual_printer_manager.set_session_factory(async_session)
  2621. # Auto-start virtual printer if enabled
  2622. async with async_session() as db:
  2623. from backend.app.api.routes.settings import get_setting
  2624. vp_enabled = await get_setting(db, "virtual_printer_enabled")
  2625. if vp_enabled and vp_enabled.lower() == "true":
  2626. vp_access_code = await get_setting(db, "virtual_printer_access_code") or ""
  2627. vp_mode = await get_setting(db, "virtual_printer_mode") or "immediate"
  2628. vp_model = await get_setting(db, "virtual_printer_model") or ""
  2629. vp_target_printer_id = await get_setting(db, "virtual_printer_target_printer_id")
  2630. vp_remote_iface = await get_setting(db, "virtual_printer_remote_interface_ip") or ""
  2631. # Look up printer IP and serial if in proxy mode
  2632. vp_target_ip = ""
  2633. vp_target_serial = ""
  2634. if vp_mode == "proxy" and vp_target_printer_id:
  2635. from backend.app.models.printer import Printer
  2636. result = await db.execute(select(Printer).where(Printer.id == int(vp_target_printer_id)))
  2637. printer = result.scalar_one_or_none()
  2638. if printer:
  2639. vp_target_ip = printer.ip_address
  2640. vp_target_serial = printer.serial_number
  2641. # Proxy mode requires target IP, other modes require access code
  2642. can_start = (vp_mode == "proxy" and vp_target_ip) or (vp_mode != "proxy" and vp_access_code)
  2643. if can_start:
  2644. try:
  2645. await virtual_printer_manager.configure(
  2646. enabled=True,
  2647. access_code=vp_access_code,
  2648. mode=vp_mode,
  2649. model=vp_model,
  2650. target_printer_ip=vp_target_ip,
  2651. target_printer_serial=vp_target_serial,
  2652. remote_interface_ip=vp_remote_iface,
  2653. )
  2654. if vp_mode == "proxy":
  2655. logging.info("Virtual printer proxy started (target=%s)", vp_target_ip)
  2656. else:
  2657. logging.info("Virtual printer started (model=%s)", vp_model or "default")
  2658. except Exception as e:
  2659. logging.warning("Failed to start virtual printer: %s", e)
  2660. yield
  2661. # Shutdown
  2662. print_scheduler.stop()
  2663. smart_plug_manager.stop_scheduler()
  2664. notification_service.stop_digest_scheduler()
  2665. github_backup_service.stop_scheduler()
  2666. stop_ams_history_recording()
  2667. stop_runtime_tracking()
  2668. printer_manager.disconnect_all()
  2669. await close_spoolman_client()
  2670. # Stop virtual printer if running
  2671. if virtual_printer_manager.is_enabled:
  2672. await virtual_printer_manager.configure(enabled=False)
  2673. await mqtt_smart_plug_service.disconnect(timeout=2)
  2674. await mqtt_relay.disconnect(timeout=2)
  2675. app = FastAPI(
  2676. title=app_settings.app_name,
  2677. description="Archive and manage Bambu Lab 3MF files",
  2678. version=APP_VERSION,
  2679. lifespan=lifespan,
  2680. )
  2681. # =============================================================================
  2682. # Authentication Middleware - Secures ALL API routes by default
  2683. # =============================================================================
  2684. # Public routes that don't require authentication even when auth is enabled
  2685. PUBLIC_API_ROUTES = {
  2686. # Auth routes needed before/during login
  2687. "/api/v1/auth/status",
  2688. "/api/v1/auth/login",
  2689. "/api/v1/auth/setup", # Needed for initial setup and recovery
  2690. "/api/v1/auth/advanced-auth/status", # Advanced auth status needed for login page
  2691. "/api/v1/auth/forgot-password", # Password reset for advanced auth
  2692. # Version check for updates (no sensitive data)
  2693. "/api/v1/updates/version",
  2694. # Metrics endpoint handles its own prometheus_token authentication
  2695. "/api/v1/metrics",
  2696. }
  2697. # Route prefixes that are public (for routes with dynamic segments)
  2698. PUBLIC_API_PREFIXES = [
  2699. # WebSocket connections handle their own auth
  2700. "/api/v1/ws",
  2701. ]
  2702. # Route patterns that are public (read-only display data)
  2703. # These are checked with "in path" - needed because browsers load images/videos
  2704. # via <img src> and <video src> which don't include Authorization headers
  2705. PUBLIC_API_PATTERNS = [
  2706. # Thumbnails
  2707. "/thumbnail", # /archives/{id}/thumbnail, /library/files/{id}/thumbnail
  2708. "/plate-thumbnail/", # /archives/{id}/plate-thumbnail/{plate_id}
  2709. # Images and media
  2710. "/photos/", # /archives/{id}/photos/{filename}
  2711. "/project-image/", # /archives/{id}/project-image/{path}
  2712. "/qrcode", # /archives/{id}/qrcode
  2713. "/timelapse", # /archives/{id}/timelapse (video)
  2714. "/cover", # /printers/{id}/cover
  2715. "/icon", # /external-links/{id}/icon
  2716. # Camera (streams loaded via <img> tag)
  2717. "/camera/stream", # /printers/{id}/camera/stream
  2718. "/camera/snapshot", # /printers/{id}/camera/snapshot
  2719. ]
  2720. @app.middleware("http")
  2721. async def auth_middleware(request, call_next):
  2722. """Enforce authentication on all API routes when auth is enabled.
  2723. This middleware provides defense-in-depth by checking auth at the API gateway level,
  2724. regardless of whether individual routes have auth dependencies.
  2725. """
  2726. from starlette.responses import JSONResponse
  2727. path = request.url.path
  2728. # Only apply to API routes
  2729. if not path.startswith("/api/"):
  2730. return await call_next(request)
  2731. # Allow public routes
  2732. if path in PUBLIC_API_ROUTES:
  2733. return await call_next(request)
  2734. # Allow public prefixes
  2735. for prefix in PUBLIC_API_PREFIXES:
  2736. if path.startswith(prefix):
  2737. return await call_next(request)
  2738. # Allow public patterns (read-only display data like thumbnails)
  2739. for pattern in PUBLIC_API_PATTERNS:
  2740. if pattern in path:
  2741. return await call_next(request)
  2742. # Check if auth is enabled
  2743. try:
  2744. async with async_session() as db:
  2745. from backend.app.core.auth import is_auth_enabled
  2746. auth_enabled = await is_auth_enabled(db)
  2747. if not auth_enabled:
  2748. # Auth disabled, allow all requests
  2749. return await call_next(request)
  2750. except Exception:
  2751. # If we can't check auth status, allow request (fail open for DB issues)
  2752. return await call_next(request)
  2753. # Auth is enabled - require valid token
  2754. auth_header = request.headers.get("Authorization")
  2755. x_api_key = request.headers.get("X-API-Key")
  2756. # Check for API key auth first
  2757. if x_api_key or (auth_header and auth_header.startswith("Bearer bb_")):
  2758. # API key authentication - let the request through to be validated by route handler
  2759. # API keys are validated per-route since they have different permission levels
  2760. return await call_next(request)
  2761. # Check for JWT auth
  2762. if not auth_header or not auth_header.startswith("Bearer "):
  2763. return JSONResponse(
  2764. status_code=401,
  2765. content={"detail": "Authentication required"},
  2766. headers={"WWW-Authenticate": "Bearer"},
  2767. )
  2768. # Validate JWT token
  2769. import jwt
  2770. try:
  2771. from backend.app.core.auth import ALGORITHM, SECRET_KEY
  2772. token = auth_header.replace("Bearer ", "")
  2773. payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
  2774. username = payload.get("sub")
  2775. if not username:
  2776. raise ValueError("No username in token")
  2777. # Verify user exists and is active
  2778. async with async_session() as db:
  2779. from backend.app.core.auth import get_user_by_username
  2780. user = await get_user_by_username(db, username)
  2781. if not user or not user.is_active:
  2782. return JSONResponse(
  2783. status_code=401,
  2784. content={"detail": "User not found or inactive"},
  2785. headers={"WWW-Authenticate": "Bearer"},
  2786. )
  2787. except jwt.ExpiredSignatureError:
  2788. return JSONResponse(
  2789. status_code=401,
  2790. content={"detail": "Token has expired"},
  2791. headers={"WWW-Authenticate": "Bearer"},
  2792. )
  2793. except (jwt.InvalidTokenError, ValueError, Exception):
  2794. return JSONResponse(
  2795. status_code=401,
  2796. content={"detail": "Invalid token"},
  2797. headers={"WWW-Authenticate": "Bearer"},
  2798. )
  2799. return await call_next(request)
  2800. # API routes
  2801. app.include_router(auth.router, prefix=app_settings.api_prefix)
  2802. app.include_router(users.router, prefix=app_settings.api_prefix)
  2803. app.include_router(groups.router, prefix=app_settings.api_prefix)
  2804. app.include_router(printers.router, prefix=app_settings.api_prefix)
  2805. app.include_router(archives.router, prefix=app_settings.api_prefix)
  2806. app.include_router(filaments.router, prefix=app_settings.api_prefix)
  2807. app.include_router(inventory.router, prefix=app_settings.api_prefix)
  2808. app.include_router(settings_routes.router, prefix=app_settings.api_prefix)
  2809. app.include_router(cloud.router, prefix=app_settings.api_prefix)
  2810. app.include_router(local_presets.router, prefix=app_settings.api_prefix)
  2811. app.include_router(smart_plugs.router, prefix=app_settings.api_prefix)
  2812. app.include_router(print_queue.router, prefix=app_settings.api_prefix)
  2813. app.include_router(kprofiles.router, prefix=app_settings.api_prefix)
  2814. app.include_router(notifications.router, prefix=app_settings.api_prefix)
  2815. app.include_router(notification_templates.router, prefix=app_settings.api_prefix)
  2816. app.include_router(spoolman.router, prefix=app_settings.api_prefix)
  2817. app.include_router(updates.router, prefix=app_settings.api_prefix)
  2818. app.include_router(maintenance.router, prefix=app_settings.api_prefix)
  2819. app.include_router(camera.router, prefix=app_settings.api_prefix)
  2820. app.include_router(external_links.router, prefix=app_settings.api_prefix)
  2821. app.include_router(projects.router, prefix=app_settings.api_prefix)
  2822. app.include_router(library.router, prefix=app_settings.api_prefix)
  2823. app.include_router(api_keys.router, prefix=app_settings.api_prefix)
  2824. app.include_router(webhook.router, prefix=app_settings.api_prefix)
  2825. app.include_router(ams_history.router, prefix=app_settings.api_prefix)
  2826. app.include_router(system.router, prefix=app_settings.api_prefix)
  2827. app.include_router(support.router, prefix=app_settings.api_prefix)
  2828. app.include_router(websocket.router, prefix=app_settings.api_prefix)
  2829. app.include_router(discovery.router, prefix=app_settings.api_prefix)
  2830. app.include_router(pending_uploads.router, prefix=app_settings.api_prefix)
  2831. app.include_router(firmware.router, prefix=app_settings.api_prefix)
  2832. app.include_router(github_backup.router, prefix=app_settings.api_prefix)
  2833. app.include_router(metrics.router, prefix=app_settings.api_prefix)
  2834. # Serve static files (React build)
  2835. if app_settings.static_dir.exists() and any(app_settings.static_dir.iterdir()):
  2836. app.mount(
  2837. "/assets",
  2838. StaticFiles(directory=app_settings.static_dir / "assets"),
  2839. name="assets",
  2840. )
  2841. if (app_settings.static_dir / "img").exists():
  2842. app.mount(
  2843. "/img",
  2844. StaticFiles(directory=app_settings.static_dir / "img"),
  2845. name="img",
  2846. )
  2847. if (app_settings.static_dir / "icons").exists():
  2848. app.mount(
  2849. "/icons",
  2850. StaticFiles(directory=app_settings.static_dir / "icons"),
  2851. name="icons",
  2852. )
  2853. @app.get("/")
  2854. async def serve_frontend():
  2855. """Serve the React frontend."""
  2856. index_file = app_settings.static_dir / "index.html"
  2857. if index_file.exists():
  2858. return FileResponse(index_file)
  2859. return {
  2860. "message": "Bambuddy API",
  2861. "docs": "/docs",
  2862. "frontend": "Build and place React app in /static directory",
  2863. }
  2864. @app.get("/health")
  2865. async def health_check():
  2866. """Health check endpoint."""
  2867. return {"status": "healthy"}
  2868. @app.get("/manifest.json")
  2869. async def serve_manifest():
  2870. """Serve PWA manifest."""
  2871. manifest_file = app_settings.static_dir / "manifest.json"
  2872. if manifest_file.exists():
  2873. return FileResponse(manifest_file, media_type="application/manifest+json")
  2874. return {"error": "Manifest not found"}
  2875. @app.get("/sw.js")
  2876. async def serve_service_worker():
  2877. """Serve service worker."""
  2878. sw_file = app_settings.static_dir / "sw.js"
  2879. if sw_file.exists():
  2880. return FileResponse(sw_file, media_type="application/javascript")
  2881. return {"error": "Service worker not found"}
  2882. # Catch-all route for React Router (must be last)
  2883. @app.get("/{full_path:path}")
  2884. async def serve_spa(full_path: str):
  2885. """Serve React app for client-side routing."""
  2886. # Don't intercept API routes - raise proper 404 so FastAPI can handle redirects
  2887. if full_path.startswith("api/"):
  2888. from fastapi import HTTPException
  2889. raise HTTPException(status_code=404, detail="Not found")
  2890. index_file = app_settings.static_dir / "index.html"
  2891. if index_file.exists():
  2892. return FileResponse(index_file)
  2893. return {"error": "Frontend not built"}