main.py 215 KB

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