main.py 260 KB

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