main.py 137 KB

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