main.py 261 KB

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