main.py 281 KB

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