main.py 204 KB

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