main.py 261 KB

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