main.py 197 KB

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