main.py 218 KB

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