main.py 259 KB

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