main.py 211 KB

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