main.py 198 KB

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