main.py 191 KB

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