main.py 267 KB

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