main.py 164 KB

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