printers.py 190 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629
  1. import asyncio
  2. import logging
  3. import re
  4. import secrets
  5. import zipfile
  6. from pathlib import Path
  7. from fastapi import APIRouter, Depends, HTTPException, Query
  8. from fastapi.responses import FileResponse, Response
  9. from sqlalchemy import func, select
  10. from sqlalchemy.ext.asyncio import AsyncSession
  11. from starlette.background import BackgroundTask
  12. from backend.app.core import database
  13. from backend.app.core.auth import (
  14. RequireCameraStreamTokenIfAuthEnabled,
  15. RequireOverlayTokenIfAuthEnabled,
  16. RequirePermissionIfAuthEnabled,
  17. RequirePrinterPermissionIfAuthEnabled,
  18. is_auth_enabled,
  19. )
  20. from backend.app.core.config import settings
  21. from backend.app.core.database import get_db
  22. from backend.app.core.permissions import Permission
  23. from backend.app.core.tasks import spawn_background_task
  24. from backend.app.models.ams_label import AmsLabel
  25. from backend.app.models.printer import Printer
  26. from backend.app.models.slot_preset import SlotPresetMapping
  27. from backend.app.models.user import User
  28. from backend.app.schemas.printer import (
  29. AmsLabelBody,
  30. AMSTray,
  31. AMSUnit,
  32. DiagnosticRequest,
  33. ExtruderSlotResponse,
  34. FilaSwitchResponse,
  35. HmsActionBody,
  36. HMSErrorResponse,
  37. NozzleInfoResponse,
  38. NozzleRackSlot,
  39. PrinterCreate,
  40. PrinterDiagnosticResult,
  41. PrinterFilesDownloadRequest,
  42. PrinterFilesJobRequest,
  43. PrinterResponse,
  44. PrinterResponseWithSecret,
  45. PrinterStatus,
  46. PrinterUpdate,
  47. PrintOptionsResponse,
  48. )
  49. from backend.app.services import drying_preflight
  50. from backend.app.services.bambu_ftp import (
  51. cache_3mf_download,
  52. delete_file_async,
  53. download_file_bytes_async,
  54. download_file_try_paths_async,
  55. ftps_handshake_blocked,
  56. get_cached_3mf,
  57. get_storage_info_async,
  58. list_files_result_async,
  59. )
  60. from backend.app.services.print_storage import ftp_probe_paths, print_file_reachable_over_ftp
  61. from backend.app.services.printer_diagnostic import run_connection_diagnostic
  62. from backend.app.services.printer_manager import (
  63. display_temperatures,
  64. drying_screen_only,
  65. get_derived_status_name,
  66. printer_manager,
  67. resolve_expected_tray,
  68. resolve_plate_id,
  69. supports_chamber_heater,
  70. supports_chamber_temp,
  71. supports_drying,
  72. supports_drying_while_printing,
  73. uniform_tray_filament_hint,
  74. )
  75. from backend.app.services.printer_media import (
  76. MAX_PRINTER_ZIP_PREPARE_SECONDS,
  77. PrinterFilesZipInsufficientSpaceError,
  78. PrinterFilesZipTooLargeError,
  79. build_printer_file,
  80. build_printer_files_zip,
  81. cancel_printer_files_job,
  82. get_printer_files_job,
  83. printer_file_path,
  84. printer_files_zip_path,
  85. remove_printer_files_zip,
  86. start_printer_files_job,
  87. )
  88. from backend.app.services.slot_nozzle import resolve_slot_nozzle
  89. from backend.app.utils.filament_ids import filament_id_to_setting_id
  90. from backend.app.utils.filament_types import printer_filament_type
  91. from backend.app.utils.fts_routing import slot_extruder
  92. from backend.app.utils.http import build_content_disposition, download_error_response, safe_download_filename
  93. from backend.app.utils.kprofile_lookup import build_slot_k_resolver
  94. from backend.app.utils.printer_models import MAX_CHAMBER_TEMP_C, uses_exhaust_fan_label
  95. logger = logging.getLogger(__name__)
  96. router = APIRouter(prefix="/printers", tags=["printers"])
  97. # Seconds the /hms/execute-action route waits for a printer status push
  98. # confirming the command landed before reporting 502 to the UI. Module-level
  99. # so tests can monkeypatch a near-zero value instead of mocking asyncio.sleep.
  100. HMS_ACTION_ACK_WAIT_SECONDS = 2.5
  101. async def _caller_can_view_printer_secrets(user: User | None, db: AsyncSession) -> bool:
  102. """Whether the caller is trusted enough to see ``access_code`` on a printer
  103. response. Fail-CLOSED: anything that isn't an authenticated user holding
  104. PRINTERS_UPDATE returns False.
  105. - Auth disabled → True (single trust domain — same as today's local UI).
  106. - JWT user with PRINTERS_UPDATE → True (Admin or Operator; the same roles
  107. that already manage printers and the Virtual Printer card UX that
  108. surfaces a target's code for slicer configuration).
  109. - JWT Viewer → False (the bug fix: Viewers must not be able to read
  110. access_code via PRINTERS_READ and then go around Bambuddy to MQTT).
  111. - API-key principal (``user is None`` because the dep returns None for
  112. API keys) → False. PRINTERS_UPDATE is admin-only and absent from
  113. ``_APIKEY_SCOPE_BY_PERMISSION``, so no API key can hold it.
  114. """
  115. if not await is_auth_enabled(db):
  116. return True
  117. if user is None:
  118. return False
  119. return user.has_permission(Permission.PRINTERS_UPDATE.value)
  120. def _serialize_printer(printer: Printer, *, include_secret: bool):
  121. """Build the response shape that matches the caller's authority."""
  122. if include_secret:
  123. return PrinterResponseWithSecret.model_validate(printer)
  124. return PrinterResponse.model_validate(printer)
  125. @router.get("/")
  126. async def list_printers(
  127. user: User | None = RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  128. db: AsyncSession = Depends(get_db),
  129. ):
  130. """List all configured printers.
  131. ``access_code`` is included in each item only when the caller is trusted
  132. to see it (Admin / Operator JWT, or auth-disabled mode). Viewers and
  133. API keys never receive it.
  134. """
  135. result = await db.execute(select(Printer).order_by(Printer.name))
  136. printers = list(result.scalars().all())
  137. include_secret = await _caller_can_view_printer_secrets(user, db)
  138. return [_serialize_printer(p, include_secret=include_secret) for p in printers]
  139. @router.post("/", response_model=PrinterResponse)
  140. async def create_printer(
  141. printer_data: PrinterCreate,
  142. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CREATE),
  143. db: AsyncSession = Depends(get_db),
  144. ):
  145. """Add a new printer.
  146. Verifies the MQTT connection succeeds before persisting. A wrong access
  147. code or unreachable IP would otherwise create a printer row that shows
  148. as an empty / never-connecting card on the dashboard — those reports
  149. were turning into support tickets that all traced back to a mistyped
  150. access code.
  151. """
  152. # Check if serial number already exists
  153. result = await db.execute(select(Printer).where(Printer.serial_number == printer_data.serial_number))
  154. if result.scalar_one_or_none():
  155. raise HTTPException(400, "Printer with this serial number already exists")
  156. test_result = await printer_manager.test_connection(
  157. ip_address=printer_data.ip_address,
  158. serial_number=printer_data.serial_number,
  159. access_code=printer_data.access_code,
  160. )
  161. if not test_result.get("success"):
  162. # The frontend renders the user-facing message via i18n on `code`;
  163. # `message` is an English fallback for non-UI clients (curl / scripts).
  164. raise HTTPException(
  165. status_code=400,
  166. detail={
  167. "code": "printer_connection_failed",
  168. "message": (
  169. "Could not connect to the printer. Verify IP address, serial number, "
  170. "and access code, and confirm LAN-only mode is enabled. "
  171. "The printer was not added."
  172. ),
  173. },
  174. )
  175. printer = Printer(**printer_data.model_dump())
  176. db.add(printer)
  177. await db.commit()
  178. await db.refresh(printer)
  179. # Connect to the printer
  180. if printer.is_active:
  181. await printer_manager.connect_printer(printer)
  182. return printer
  183. @router.get("/usb-cameras")
  184. async def list_usb_cameras(
  185. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  186. ):
  187. """List available USB cameras connected to the system.
  188. Returns a list of detected V4L2 video devices with their info.
  189. Only works on Linux systems with V4L2 support.
  190. Returns:
  191. List of dicts with {device: str, name: str, capabilities: list, formats?: list}
  192. """
  193. from backend.app.services.external_camera import list_usb_cameras
  194. cameras = list_usb_cameras()
  195. return {"cameras": cameras}
  196. @router.get("/available-filaments")
  197. async def get_available_filaments(
  198. model: str = Query(..., description="Target printer model"),
  199. location: str | None = Query(None, description="Optional location filter"),
  200. _=RequirePermissionIfAuthEnabled(Permission.QUEUE_CREATE),
  201. db: AsyncSession = Depends(get_db),
  202. ):
  203. """Get deduplicated list of filaments loaded across all active printers of a given model.
  204. Used by the frontend to offer filament override options for model-based queue assignment.
  205. """
  206. from backend.app.utils.printer_models import normalize_printer_model, normalize_printer_model_id
  207. # Normalize model name
  208. normalized_model = normalize_printer_model(model) or normalize_printer_model_id(model) or model
  209. query = (
  210. select(Printer).where(func.lower(Printer.model) == normalized_model.lower()).where(Printer.is_active == True) # noqa: E712
  211. )
  212. if location:
  213. query = query.where(Printer.location == location)
  214. result = await db.execute(query)
  215. printers_list = list(result.scalars().all())
  216. if not printers_list:
  217. return []
  218. # Collect filaments from all matching printers
  219. # Dedup key includes extruder_id and tray_sub_brands so "PLA Basic" and "PLA Matte" appear separately
  220. seen: set[tuple[str, str, str, int | None]] = set() # (type_upper, color_normalized, sub_brands_upper, extruder_id)
  221. filaments = []
  222. for printer in printers_list:
  223. status = printer_manager.get_status(printer.id)
  224. if not status:
  225. continue
  226. # Get ams_extruder_map for dual-nozzle printers
  227. ams_extruder_map = status.raw_data.get("ams_extruder_map", {})
  228. # AMS trays
  229. for ams_unit in status.raw_data.get("ams", []):
  230. ams_id = str(ams_unit.get("id", 0))
  231. extruder_id = ams_extruder_map.get(ams_id)
  232. for tray in ams_unit.get("tray", []):
  233. tray_type = tray.get("tray_type")
  234. if not tray_type:
  235. continue
  236. tray_color = tray.get("tray_color", "") or "808080"
  237. # Preserve the full RRGGBBAA so transparent filament (alpha=00)
  238. # reaches the frontend instead of collapsing to #000000 → black
  239. # (#1545). Opaque colours still round-trip as #RRGGBB. The
  240. # dedup key uses the 6-char RGB so two slots that share an RGB
  241. # but differ only in alpha still merge.
  242. stripped = tray_color.replace("#", "")
  243. rgb = stripped[:6].lower() or "808080"
  244. color = f"#{stripped}"
  245. tray_info_idx = tray.get("tray_info_idx", "")
  246. tray_sub_brands = tray.get("tray_sub_brands", "") or ""
  247. key = (tray_type.upper(), rgb, tray_sub_brands.upper(), extruder_id)
  248. if key not in seen:
  249. seen.add(key)
  250. filaments.append(
  251. {
  252. "type": tray_type,
  253. "color": color,
  254. "tray_info_idx": tray_info_idx,
  255. "tray_sub_brands": tray_sub_brands,
  256. "extruder_id": extruder_id,
  257. }
  258. )
  259. # External spools (vt_tray)
  260. for vt in status.raw_data.get("vt_tray") or []:
  261. vt_type = vt.get("tray_type")
  262. if not vt_type:
  263. continue
  264. vt_color = vt.get("tray_color", "") or "808080"
  265. # Same alpha-preserving handling as the AMS branch — see #1545.
  266. stripped = vt_color.replace("#", "")
  267. rgb = stripped[:6].lower() or "808080"
  268. color = f"#{stripped}"
  269. tray_info_idx = vt.get("tray_info_idx", "")
  270. tray_sub_brands = vt.get("tray_sub_brands", "") or ""
  271. vt_id = int(vt.get("id", 254))
  272. extruder_id = (255 - vt_id) if ams_extruder_map else None
  273. key = (vt_type.upper(), rgb, tray_sub_brands.upper(), extruder_id)
  274. if key not in seen:
  275. seen.add(key)
  276. filaments.append(
  277. {
  278. "type": vt_type,
  279. "color": color,
  280. "tray_info_idx": tray_info_idx,
  281. "tray_sub_brands": tray_sub_brands,
  282. "extruder_id": extruder_id,
  283. }
  284. )
  285. return filaments
  286. @router.get("/developer-mode-warnings")
  287. async def get_developer_mode_warnings(
  288. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  289. db: AsyncSession = Depends(get_db),
  290. ):
  291. """Check if any connected printer lacks developer LAN mode."""
  292. result = await db.execute(select(Printer).where(Printer.is_active == True)) # noqa: E712
  293. printers = result.scalars().all()
  294. statuses = printer_manager.get_all_statuses()
  295. warnings = []
  296. for printer in printers:
  297. state = statuses.get(printer.id)
  298. if state and state.connected and state.developer_mode is False:
  299. warnings.append(
  300. {
  301. "printer_id": printer.id,
  302. "name": printer.name,
  303. }
  304. )
  305. return warnings
  306. @router.get("/{printer_id}")
  307. async def get_printer(
  308. printer_id: int,
  309. user: User | None = RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  310. db: AsyncSession = Depends(get_db),
  311. ):
  312. """Get a specific printer.
  313. ``access_code`` is included only when the caller is trusted to see it
  314. (Admin / Operator JWT, or auth-disabled mode). Viewers and API keys
  315. never receive it.
  316. """
  317. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  318. printer = result.scalar_one_or_none()
  319. if not printer:
  320. raise HTTPException(404, "Printer not found")
  321. include_secret = await _caller_can_view_printer_secrets(user, db)
  322. return _serialize_printer(printer, include_secret=include_secret)
  323. @router.patch("/{printer_id}", response_model=PrinterResponse)
  324. async def update_printer(
  325. printer_id: int,
  326. printer_data: PrinterUpdate,
  327. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_UPDATE),
  328. db: AsyncSession = Depends(get_db),
  329. ):
  330. """Update a printer."""
  331. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  332. printer = result.scalar_one_or_none()
  333. if not printer:
  334. raise HTTPException(404, "Printer not found")
  335. update_data = printer_data.model_dump(exclude_unset=True)
  336. # Handle nested ROI object - flatten to individual columns
  337. if "plate_detection_roi" in update_data:
  338. roi = update_data.pop("plate_detection_roi")
  339. if roi:
  340. update_data["plate_detection_roi_x"] = roi.get("x")
  341. update_data["plate_detection_roi_y"] = roi.get("y")
  342. update_data["plate_detection_roi_w"] = roi.get("w")
  343. update_data["plate_detection_roi_h"] = roi.get("h")
  344. else:
  345. # Clear ROI if set to null
  346. update_data["plate_detection_roi_x"] = None
  347. update_data["plate_detection_roi_y"] = None
  348. update_data["plate_detection_roi_w"] = None
  349. update_data["plate_detection_roi_h"] = None
  350. for field, value in update_data.items():
  351. setattr(printer, field, value)
  352. await db.commit()
  353. await db.refresh(printer)
  354. # Reconnect if connection settings changed
  355. if any(k in update_data for k in ["ip_address", "access_code", "is_active"]):
  356. printer_manager.disconnect_printer(printer_id)
  357. if printer.is_active:
  358. await printer_manager.connect_printer(printer)
  359. return printer
  360. @router.delete("/{printer_id}")
  361. async def delete_printer(
  362. printer_id: int,
  363. delete_archives: bool = True,
  364. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_DELETE),
  365. db: AsyncSession = Depends(get_db),
  366. ):
  367. """Delete a printer.
  368. Args:
  369. printer_id: ID of the printer to delete
  370. delete_archives: If True (default), delete all print archives for this printer.
  371. If False, keep archives but remove their printer association.
  372. """
  373. from sqlalchemy import delete as sql_delete
  374. from backend.app.models.archive import PrintArchive
  375. from backend.app.models.maintenance import MaintenanceHistory, PrinterMaintenance
  376. from backend.app.models.scheduled_drying import ScheduledDrying
  377. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  378. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  379. printer = result.scalar_one_or_none()
  380. if not printer:
  381. raise HTTPException(404, "Printer not found")
  382. printer_manager.disconnect_printer(printer_id)
  383. if delete_archives:
  384. # Delete all archives for this printer
  385. await db.execute(sql_delete(PrintArchive).where(PrintArchive.printer_id == printer_id))
  386. else:
  387. # Orphan the archives instead of deleting them
  388. from sqlalchemy import update
  389. await db.execute(update(PrintArchive).where(PrintArchive.printer_id == printer_id).values(printer_id=None))
  390. # Delete slot assignments for this printer (SQLite doesn't enforce FK cascades)
  391. await db.execute(sql_delete(SpoolmanSlotAssignment).where(SpoolmanSlotAssignment.printer_id == printer_id))
  392. # Delete scheduled drying runs for this printer (SQLite doesn't enforce FK cascades)
  393. await db.execute(sql_delete(ScheduledDrying).where(ScheduledDrying.printer_id == printer_id))
  394. # Delete maintenance history and items for this printer
  395. # (SQLite doesn't enforce FK cascades, so do it explicitly)
  396. maintenance_ids = (
  397. (await db.execute(select(PrinterMaintenance.id).where(PrinterMaintenance.printer_id == printer_id)))
  398. .scalars()
  399. .all()
  400. )
  401. if maintenance_ids:
  402. await db.execute(
  403. sql_delete(MaintenanceHistory).where(MaintenanceHistory.printer_maintenance_id.in_(maintenance_ids))
  404. )
  405. await db.execute(sql_delete(PrinterMaintenance).where(PrinterMaintenance.printer_id == printer_id))
  406. await db.delete(printer)
  407. await db.commit()
  408. return {"status": "deleted", "archives_deleted": delete_archives}
  409. @router.get("/{printer_id}/status", response_model=PrinterStatus)
  410. async def get_printer_status(
  411. printer_id: int,
  412. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  413. db: AsyncSession = Depends(get_db),
  414. ):
  415. """Get real-time status of a printer."""
  416. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  417. printer = result.scalar_one_or_none()
  418. if not printer:
  419. raise HTTPException(404, "Printer not found")
  420. state = printer_manager.get_status(printer_id)
  421. if not state:
  422. # No MQTT client state — the printer was never connected this run, or it
  423. # was disconnected manually. The plate-clear gate is Bambuddy-side and
  424. # persisted, so it still has a truthful value here (#2864); reporting the
  425. # schema default instead told clients the plate was clean and hid the
  426. # only control that can release the gate.
  427. return PrinterStatus(
  428. id=printer_id,
  429. name=printer.name,
  430. connected=False,
  431. awaiting_plate_clear=printer_manager.is_awaiting_plate_clear(printer_id),
  432. )
  433. # Determine cover URL if there's an active print (including paused)
  434. cover_url = None
  435. if state.state in ("RUNNING", "PAUSE") and state.gcode_file:
  436. cover_url = f"/api/v1/printers/{printer_id}/cover"
  437. # Convert HMS errors to response format
  438. hms_errors = [
  439. HMSErrorResponse(
  440. code=e.code,
  441. attr=e.attr,
  442. module=e.module,
  443. severity=e.severity,
  444. actions=e.actions,
  445. job_id=e.job_id,
  446. full_code=e.full_code,
  447. description=e.description,
  448. )
  449. for e in (state.hms_errors or [])
  450. ]
  451. # Parse AMS data from raw_data
  452. ams_units = []
  453. vt_tray = []
  454. ams_exists = False
  455. raw_data = state.raw_data or {}
  456. # K value for a slot's bound profile, resolved against its own nozzle.
  457. #
  458. # Keyed on more than cali_idx: the printer numbers its calibration table
  459. # per nozzle, so entry 16 exists on each and means a different profile on
  460. # each. A cali_idx-only map let whichever profile the printer happened to
  461. # list last overwrite the other, and the slot then displayed the wrong
  462. # nozzle's K — on the maintainer's H2C, 0.018 and 0.020 for the same spool.
  463. _kprofile_k = build_slot_k_resolver(state)
  464. # Cached active-cycle drying params (filament + target temp) we sent
  465. # last; Bambu doesn't echo them on the per-tick AMS push, so the badge
  466. # needs the cache to render "<filament> @ <temp>°C".
  467. drying_targets = printer_manager.get_drying_targets(printer_id) or {}
  468. if "ams" in raw_data and isinstance(raw_data["ams"], list):
  469. ams_exists = True
  470. for ams_data in raw_data["ams"]:
  471. # Skip if ams_data is not a dict (defensive check)
  472. if not isinstance(ams_data, dict):
  473. continue
  474. trays = []
  475. for tray_data in ams_data.get("tray", []):
  476. # Filter out empty/invalid tag values
  477. tag_uid = tray_data.get("tag_uid", "")
  478. if tag_uid in ("", "0000000000000000"):
  479. tag_uid = None
  480. tray_uuid = tray_data.get("tray_uuid", "")
  481. if tray_uuid in ("", "00000000000000000000000000000000"):
  482. tray_uuid = None
  483. # Get K value: first try tray's k field, then lookup from K-profiles
  484. k_value = tray_data.get("k")
  485. cali_idx = tray_data.get("cali_idx")
  486. if k_value is None:
  487. k_value = _kprofile_k(cali_idx, int(ams_data.get("id", 0)), int(tray_data.get("id", 0)))
  488. trays.append(
  489. AMSTray(
  490. id=tray_data.get("id", 0),
  491. tray_color=tray_data.get("tray_color"),
  492. tray_type=tray_data.get("tray_type"),
  493. tray_sub_brands=tray_data.get("tray_sub_brands"),
  494. tray_id_name=tray_data.get("tray_id_name"),
  495. tray_info_idx=tray_data.get("tray_info_idx"),
  496. remain=tray_data.get("remain", 0),
  497. k=k_value,
  498. cali_idx=cali_idx,
  499. tag_uid=tag_uid,
  500. tray_uuid=tray_uuid,
  501. nozzle_temp_min=tray_data.get("nozzle_temp_min"),
  502. nozzle_temp_max=tray_data.get("nozzle_temp_max"),
  503. drying_temp=tray_data.get("drying_temp"),
  504. drying_time=tray_data.get("drying_time"),
  505. state=tray_data.get("state"),
  506. exists=tray_data.get("exists"),
  507. )
  508. )
  509. # Prefer humidity_raw (percentage) over humidity (index 1-5)
  510. # humidity_raw is the actual percentage value from the sensor
  511. humidity_raw = ams_data.get("humidity_raw")
  512. humidity_idx = ams_data.get("humidity")
  513. humidity_value = None
  514. if humidity_raw is not None:
  515. try:
  516. humidity_value = int(humidity_raw)
  517. except (ValueError, TypeError):
  518. pass # Skip unparseable humidity; will try index fallback
  519. if humidity_value is None and humidity_idx is not None:
  520. try:
  521. humidity_value = int(humidity_idx)
  522. except (ValueError, TypeError):
  523. pass # Skip unparseable humidity index; humidity remains None
  524. # AMS-HT has 1 tray, regular AMS has 4 trays
  525. is_ams_ht = len(trays) == 1
  526. ams_id_int = int(ams_data.get("id", 0))
  527. target = drying_targets.get(ams_id_int) or {}
  528. dry_target_temp: int | None = None
  529. dry_filament: str | None = None
  530. target_temp_val = target.get("temp")
  531. target_fil_val = target.get("filament") or ""
  532. if target_temp_val is not None:
  533. try:
  534. dry_target_temp = int(target_temp_val)
  535. except (TypeError, ValueError):
  536. dry_target_temp = None
  537. if target_fil_val:
  538. dry_filament = str(target_fil_val)
  539. # Fallback: name the filament from the loaded trays when there is no
  540. # cached target (drying started in a previous backend session, or
  541. # the cache wasn't seeded), and only when they agree. The
  542. # temperature has no fallback — see uniform_tray_filament_hint.
  543. if not dry_filament:
  544. dry_filament = uniform_tray_filament_hint([tray.tray_type or "" for tray in trays])
  545. ams_units.append(
  546. AMSUnit(
  547. id=ams_id_int,
  548. humidity=humidity_value,
  549. temp=ams_data.get("temp"),
  550. is_ams_ht=is_ams_ht,
  551. tray=trays,
  552. # Serial number: Bambu MQTT uses "sn" key on AMS unit objects
  553. serial_number=str(ams_data.get("sn") or ams_data.get("serial_number") or ""),
  554. # Firmware version: populated by _handle_version_info from info.module ams/* entries
  555. sw_ver=str(ams_data.get("sw_ver") or ""),
  556. # Drying: dry_time > 0 means drying is active (minutes remaining)
  557. dry_time=int(ams_data.get("dry_time") or 0),
  558. dry_target_temp=dry_target_temp,
  559. dry_filament=dry_filament,
  560. module_type=str(ams_data.get("module_type") or ""),
  561. )
  562. )
  563. # Virtual tray (external spool holder) - comes from vt_tray in raw_data (list)
  564. if "vt_tray" in raw_data:
  565. for vt_data in raw_data["vt_tray"]:
  566. # Filter out empty/invalid tag values for vt_tray
  567. vt_tag_uid = vt_data.get("tag_uid", "")
  568. if vt_tag_uid in ("", "0000000000000000"):
  569. vt_tag_uid = None
  570. vt_tray_uuid = vt_data.get("tray_uuid", "")
  571. if vt_tray_uuid in ("", "00000000000000000000000000000000"):
  572. vt_tray_uuid = None
  573. # Get K value: first try tray's k field, then lookup from K-profiles
  574. vt_k_value = vt_data.get("k")
  575. vt_cali_idx = vt_data.get("cali_idx")
  576. if vt_k_value is None:
  577. # External holder: id 254 is Ext-L, 255 is Ext-R. slot_extruder
  578. # takes the 0/1 tray index, so normalise before asking.
  579. vt_id = int(vt_data.get("id", 254))
  580. vt_k_value = _kprofile_k(vt_cali_idx, 255, vt_id - 254 if vt_id >= 254 else vt_id)
  581. tray_id = int(vt_data.get("id", 254))
  582. vt_tray.append(
  583. AMSTray(
  584. id=tray_id,
  585. tray_color=vt_data.get("tray_color"),
  586. tray_type=vt_data.get("tray_type"),
  587. tray_sub_brands=vt_data.get("tray_sub_brands"),
  588. tray_id_name=vt_data.get("tray_id_name"),
  589. tray_info_idx=vt_data.get("tray_info_idx"),
  590. remain=vt_data.get("remain", 0),
  591. k=vt_k_value,
  592. cali_idx=vt_cali_idx,
  593. tag_uid=vt_tag_uid,
  594. tray_uuid=vt_tray_uuid,
  595. nozzle_temp_min=vt_data.get("nozzle_temp_min"),
  596. nozzle_temp_max=vt_data.get("nozzle_temp_max"),
  597. )
  598. )
  599. # Convert nozzle info to response format
  600. nozzles = [
  601. NozzleInfoResponse(
  602. nozzle_type=n.nozzle_type,
  603. nozzle_diameter=n.nozzle_diameter,
  604. )
  605. for n in (state.nozzles or [])
  606. ]
  607. # H2C nozzle rack (tool-changer dock positions)
  608. nozzle_rack = [
  609. NozzleRackSlot(
  610. id=n.get("id", 0),
  611. nozzle_type=n.get("type", ""),
  612. nozzle_diameter=n.get("diameter", ""),
  613. wear=n.get("wear"),
  614. stat=n.get("stat"),
  615. max_temp=n.get("max_temp", 0),
  616. serial_number=n.get("serial_number", ""),
  617. filament_color=n.get("filament_color", ""),
  618. filament_id=n.get("filament_id", ""),
  619. filament_type=n.get("filament_type", ""),
  620. )
  621. for n in (state.nozzle_rack or [])
  622. ]
  623. # Convert print options to response format
  624. print_options = PrintOptionsResponse(
  625. spaghetti_detector=state.print_options.spaghetti_detector,
  626. print_halt=state.print_options.print_halt,
  627. halt_print_sensitivity=state.print_options.halt_print_sensitivity,
  628. first_layer_inspector=state.print_options.first_layer_inspector,
  629. printing_monitor=state.print_options.printing_monitor,
  630. buildplate_marker_detector=state.print_options.buildplate_marker_detector,
  631. allow_skip_parts=state.print_options.allow_skip_parts,
  632. nozzle_clumping_detector=state.print_options.nozzle_clumping_detector,
  633. nozzle_clumping_sensitivity=state.print_options.nozzle_clumping_sensitivity,
  634. pileup_detector=state.print_options.pileup_detector,
  635. pileup_sensitivity=state.print_options.pileup_sensitivity,
  636. airprint_detector=state.print_options.airprint_detector,
  637. airprint_sensitivity=state.print_options.airprint_sensitivity,
  638. auto_recovery_step_loss=state.print_options.auto_recovery_step_loss,
  639. filament_tangle_detect=state.print_options.filament_tangle_detect,
  640. )
  641. # Get AMS mapping from raw_data (which AMS is connected to which nozzle)
  642. ams_mapping = raw_data.get("ams_mapping", [])
  643. # Get per-AMS extruder map from state attribute (not raw_data, to avoid race condition
  644. # where raw_data gets replaced during MQTT updates and ams_extruder_map is temporarily missing)
  645. ams_extruder_map = state.ams_extruder_map or {}
  646. logger.debug("API returning ams_mapping: %s, ams_extruder_map: %s", ams_mapping, ams_extruder_map)
  647. # tray_now from MQTT is already a global tray ID: (ams_id * 4) + slot_id
  648. # Per OpenBambuAPI docs: 254 = external spool, 255 = no filament, otherwise global tray ID
  649. # No conversion needed - just use the raw value directly
  650. tray_now = state.tray_now
  651. logger.debug("Using tray_now directly as global ID: %s", tray_now)
  652. # Filter out chamber temp for models that don't have a real sensor
  653. # P1P, P1S, A1, A1Mini report meaningless chamber_temper values
  654. temperatures = state.temperatures
  655. if not supports_chamber_temp(printer.model):
  656. temperatures = {
  657. k: v for k, v in temperatures.items() if k not in ("chamber", "chamber_target", "chamber_heating")
  658. }
  659. # Resolve the active print's archive + plate (#881 follow-up): lets the
  660. # printer card show the actual plate name for multi-plate 3MFs instead of
  661. # just the 3MF filename. Only attempted for active prints, since subtask_id
  662. # is only meaningful then.
  663. current_archive_id: int | None = None
  664. current_plate_id: int | None = None
  665. if state.state in ("RUNNING", "PAUSE"):
  666. current_plate_id = resolve_plate_id(state)
  667. if state.subtask_id:
  668. from backend.app.models.archive import PrintArchive
  669. archive_row = await db.execute(
  670. select(PrintArchive.id)
  671. .where(PrintArchive.subtask_id == state.subtask_id)
  672. .where(PrintArchive.printer_id == printer_id)
  673. .order_by(PrintArchive.created_at.desc())
  674. .limit(1)
  675. )
  676. current_archive_id = archive_row.scalar_one_or_none()
  677. return PrinterStatus(
  678. id=printer_id,
  679. name=printer.name,
  680. connected=state.connected,
  681. state=state.state,
  682. current_print=state.current_print,
  683. subtask_name=state.subtask_name,
  684. gcode_file=state.gcode_file,
  685. progress=state.progress,
  686. remaining_time=state.remaining_time,
  687. layer_num=state.layer_num,
  688. total_layers=state.total_layers,
  689. temperatures=temperatures,
  690. cover_url=cover_url,
  691. hms_errors=hms_errors,
  692. ams=ams_units,
  693. ams_exists=ams_exists,
  694. vt_tray=vt_tray,
  695. sdcard=state.sdcard,
  696. store_to_sdcard=state.store_to_sdcard,
  697. timelapse=state.timelapse,
  698. ipcam=state.ipcam,
  699. wifi_signal=state.wifi_signal,
  700. wired_network=state.wired_network,
  701. door_open=state.door_open,
  702. nozzles=nozzles,
  703. nozzle_rack=nozzle_rack,
  704. print_options=print_options,
  705. stg_cur=state.stg_cur,
  706. stg_cur_name=get_derived_status_name(state, printer.model),
  707. stg=state.stg,
  708. airduct_mode=state.airduct_mode,
  709. speed_level=state.speed_level,
  710. chamber_light=state.chamber_light,
  711. active_extruder=state.active_extruder,
  712. ams_mapping=ams_mapping,
  713. ams_extruder_map=ams_extruder_map,
  714. # Only meaningful alongside an installed switch; without one the map is
  715. # empty anyway, but gating it keeps a stale binding from outliving the
  716. # accessory being unplugged.
  717. ams_switch_inlet=(dict(state.ams_switch_inlet) if state.fila_switch and state.fila_switch.installed else {}),
  718. # Which hotend holds which slot. Same first-load reasoning as
  719. # fila_switch.ready below — the AMS slot menu reads it to decide which
  720. # hotend it may offer, and an empty default would offer both.
  721. extruder_slots={
  722. str(ext_id): ExtruderSlotResponse(
  723. ams_id=slot.ams_id,
  724. slot_id=slot.slot_id,
  725. has_filament=slot.has_filament,
  726. )
  727. for ext_id, slot in state.extruder_slots.items()
  728. },
  729. tray_now=tray_now,
  730. # Runout guidance (#2587): resolve the firmware's target/previous slot to a
  731. # global tray ID, but only while PAUSED — the moment the operator needs it.
  732. expected_tray=(
  733. resolve_expected_tray(
  734. state.tray_tar,
  735. [(u.id, u.is_ams_ht) for u in ams_units],
  736. raw_data.get("mapping"),
  737. )
  738. if state.state == "PAUSE"
  739. else None
  740. ),
  741. previous_tray=(
  742. resolve_expected_tray(
  743. state.tray_pre,
  744. [(u.id, u.is_ams_ht) for u in ams_units],
  745. raw_data.get("mapping"),
  746. )
  747. if state.state == "PAUSE"
  748. else None
  749. ),
  750. ams_status_main=state.ams_status_main,
  751. ams_status_sub=state.ams_status_sub,
  752. mc_print_sub_stage=state.mc_print_sub_stage,
  753. last_ams_update=state.last_ams_update,
  754. printable_objects_count=len(state.printable_objects),
  755. cooling_fan_speed=state.cooling_fan_speed,
  756. big_fan1_speed=state.big_fan1_speed,
  757. big_fan2_speed=state.big_fan2_speed,
  758. heatbreak_fan_speed=state.heatbreak_fan_speed,
  759. left_aux_fan_speed=state.left_aux_fan_speed,
  760. exhaust_fan_present=state.exhaust_fan_present,
  761. firmware_version=state.firmware_version,
  762. developer_mode=state.developer_mode if state else None,
  763. ams_filament_backup=state.ams_filament_backup if state else None,
  764. awaiting_plate_clear=printer_manager.is_awaiting_plate_clear(printer_id),
  765. supports_drying=supports_drying(printer.model, state.firmware_version),
  766. supports_drying_while_printing=supports_drying_while_printing(printer.model, state.firmware_version),
  767. drying_screen_only=drying_screen_only(printer.model),
  768. supports_chamber_heater=supports_chamber_heater(printer.model),
  769. current_archive_id=current_archive_id,
  770. current_plate_id=current_plate_id,
  771. fila_switch=(
  772. FilaSwitchResponse(
  773. installed=state.fila_switch.installed,
  774. in_slots=list(state.fila_switch.in_slots),
  775. out_extruders=list(state.fila_switch.out_extruders),
  776. stat=state.fila_switch.stat,
  777. info=state.fila_switch.info,
  778. # Must be computed here as well as in printer_state_to_dict: this
  779. # is what the page gets on its first load, and the WebSocket only
  780. # corrects it on the next push. Defaulting it to False instead
  781. # would tell every correctly set-up machine that its switch is
  782. # not set up, until a push happened to arrive.
  783. ready=all(str(u.id) in state.ams_switch_inlet for u in ams_units),
  784. )
  785. if state.fila_switch and state.fila_switch.installed
  786. else None
  787. ),
  788. )
  789. @router.get("/{printer_id}/overlay-status")
  790. async def get_overlay_status(
  791. printer_id: int,
  792. _: None = RequireOverlayTokenIfAuthEnabled,
  793. db: AsyncSession = Depends(get_db),
  794. ) -> dict:
  795. """Everything the streaming overlay (#2613) draws for one printer.
  796. A token-authenticated sibling of ``get_printer_status`` for embeds with no
  797. login session — OBS loads ``/overlay/{id}?token=...`` and this feeds it.
  798. Deliberately flat and minimal (name, camera rotation, live print state, and
  799. the one setting the overlay reads) rather than the full ``PrinterStatus``:
  800. a token holder gets exactly the fields the overlay renders, nothing more.
  801. Unlike the Cam Wall feed this *includes the print filename* — the overlay
  802. names the part on screen — which is why it sits behind its own ``overlay``
  803. scope rather than ``camwall``.
  804. """
  805. from backend.app.api.routes.settings import get_setting
  806. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  807. printer = result.scalar_one_or_none()
  808. if not printer:
  809. raise HTTPException(404, "Printer not found")
  810. time_format = await get_setting(db, "time_format") or "system"
  811. state = printer_manager.get_status(printer_id)
  812. if not state:
  813. # Never connected this run — mirror get_printer_status()'s disconnected
  814. # shape so the overlay renders its offline state rather than erroring.
  815. return {
  816. "id": printer_id,
  817. "name": printer.name,
  818. "camera_rotation": printer.camera_rotation or 0,
  819. "connected": False,
  820. "state": None,
  821. "current_print": None,
  822. "gcode_file": None,
  823. "progress": None,
  824. "remaining_time": None,
  825. "layer_num": None,
  826. "total_layers": None,
  827. "stg_cur_name": None,
  828. "temperatures": {},
  829. "time_format": time_format,
  830. }
  831. return {
  832. "id": printer_id,
  833. "name": printer.name,
  834. "camera_rotation": printer.camera_rotation or 0,
  835. "connected": state.connected,
  836. "state": state.state,
  837. "current_print": state.current_print,
  838. "gcode_file": state.gcode_file,
  839. "progress": state.progress,
  840. "remaining_time": state.remaining_time,
  841. "layer_num": state.layer_num,
  842. "total_layers": state.total_layers,
  843. "stg_cur_name": get_derived_status_name(state, printer.model),
  844. # Nozzle / bed / chamber readings for the overlay's temperature fields
  845. # (#1422). Filtered rather than passed through: see display_temperatures.
  846. "temperatures": display_temperatures(state.temperatures, printer.model),
  847. "time_format": time_format,
  848. }
  849. @router.get("/{printer_id}/current-print-user")
  850. async def get_current_print_user(
  851. printer_id: int,
  852. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  853. db: AsyncSession = Depends(get_db),
  854. ):
  855. """Get the user who started the current print (for reprint tracking).
  856. Returns user info if available, empty object otherwise.
  857. This tracks users for reprints (which bypass the queue).
  858. For queue-based prints, use the queue item's created_by field instead.
  859. """
  860. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  861. printer = result.scalar_one_or_none()
  862. if not printer:
  863. raise HTTPException(404, "Printer not found")
  864. user_info = printer_manager.get_current_print_user(printer_id)
  865. return user_info or {}
  866. @router.post("/{printer_id}/refresh-status")
  867. async def refresh_printer_status(
  868. printer_id: int,
  869. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  870. db: AsyncSession = Depends(get_db),
  871. ):
  872. """Request a full status refresh from the printer (sends pushall command)."""
  873. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  874. printer = result.scalar_one_or_none()
  875. if not printer:
  876. raise HTTPException(404, "Printer not found")
  877. success = printer_manager.request_status_update(printer_id)
  878. if not success:
  879. raise HTTPException(400, "Printer not connected")
  880. return {"status": "refresh_requested"}
  881. @router.post("/{printer_id}/connect")
  882. async def connect_printer(
  883. printer_id: int,
  884. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  885. db: AsyncSession = Depends(get_db),
  886. ):
  887. """Manually connect to a printer."""
  888. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  889. printer = result.scalar_one_or_none()
  890. if not printer:
  891. raise HTTPException(404, "Printer not found")
  892. success = await printer_manager.connect_printer(printer)
  893. return {"connected": success}
  894. @router.post("/{printer_id}/disconnect")
  895. async def disconnect_printer(
  896. printer_id: int,
  897. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  898. db: AsyncSession = Depends(get_db),
  899. ):
  900. """Manually disconnect from a printer."""
  901. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  902. printer = result.scalar_one_or_none()
  903. if not printer:
  904. raise HTTPException(404, "Printer not found")
  905. printer_manager.disconnect_printer(printer_id)
  906. return {"connected": False}
  907. @router.post("/test")
  908. async def test_printer_connection(
  909. ip_address: str,
  910. serial_number: str,
  911. access_code: str,
  912. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CREATE),
  913. ):
  914. """Test connection to a printer without saving."""
  915. result = await printer_manager.test_connection(
  916. ip_address=ip_address,
  917. serial_number=serial_number,
  918. access_code=access_code,
  919. )
  920. return result
  921. @router.post("/diagnostic", response_model=PrinterDiagnosticResult)
  922. async def diagnose_connection(
  923. req: DiagnosticRequest,
  924. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CREATE),
  925. ):
  926. """Run connection diagnostics for the Add-Printer flow (printer not yet saved).
  927. When serial_number + access_code are supplied the MQTT credential check
  928. also runs; otherwise only the network-level checks are performed.
  929. """
  930. return await run_connection_diagnostic(
  931. req.ip_address,
  932. serial_number=req.serial_number or None,
  933. access_code=req.access_code or None,
  934. )
  935. @router.get("/{printer_id}/diagnostic", response_model=PrinterDiagnosticResult)
  936. async def diagnose_printer(
  937. printer_id: int,
  938. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  939. db: AsyncSession = Depends(get_db),
  940. ):
  941. """Run connection diagnostics for an existing saved printer.
  942. On-demand run from the UI: wait up to PUBLISH_WAIT_DEFAULT seconds for the
  943. printer to publish a status report so a fresh reconnect (counter reset to
  944. 0) isn't reported as `printer_publishing: fail` prematurely. The support
  945. package code path calls run_connection_diagnostic without the wait so
  946. bundling stays fast.
  947. """
  948. from backend.app.services.printer_diagnostic import PUBLISH_WAIT_DEFAULT
  949. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  950. printer = result.scalar_one_or_none()
  951. if not printer:
  952. raise HTTPException(404, "Printer not found")
  953. return await run_connection_diagnostic(
  954. printer.ip_address,
  955. printer=printer,
  956. wait_for_publish_seconds=PUBLISH_WAIT_DEFAULT,
  957. )
  958. # Cache for cover images (printer_id -> {(subtask_name, view_key) -> image_bytes}).
  959. # Cleared on every print start by main.py::on_print_start, so re-dispatches with
  960. # different plates always fetch a fresh thumbnail without needing plate in the key.
  961. _cover_cache: dict[int, dict[tuple[str, str], bytes]] = {}
  962. # Negative cache (#1420): when a cover lookup exhausts every FTP path with 550
  963. # (file sliced on SD card, not on printer storage), remember the failure so the
  964. # next request short-circuits to 404 instead of re-hammering FTP 8 paths deep.
  965. # Cleared on print start alongside _cover_cache.
  966. _cover_404_cache: dict[int, set[tuple[str, str]]] = {}
  967. # In-flight cover downloads, keyed by (printer_id, subtask_name, view_key) (#2572).
  968. # The farm dashboard mounts a cover tile per printer card, so several browsers
  969. # request the same printer's cover in the same instant, all miss the cache, and
  970. # each runs the full multi-path FTP lookup + 3MF extraction (one observed live
  971. # transfer pulled an 81 MB 3MF while real print uploads were in flight). The
  972. # first request to miss becomes the leader; concurrent requests await its future
  973. # and then serve from the positive/negative cache it filled.
  974. _cover_inflight: dict[tuple[int, str, str], asyncio.Future] = {}
  975. def clear_cover_cache(printer_id: int) -> None:
  976. """Clear cached cover images for a printer. Call on print start to avoid stale thumbnails."""
  977. _cover_cache.pop(printer_id, None)
  978. _cover_404_cache.pop(printer_id, None)
  979. async def _running_print_archive_file(printer_id: int, state) -> Path | None:
  980. """Path to the 3MF of the print this printer is running, if we have it.
  981. Bambuddy archives the sliced file when the print starts, so the copy the
  982. printer is executing is usually already on disk. Anchored on ``subtask_id``,
  983. which the firmware mints per print: a leftover ``status="printing"`` row from
  984. a completion that was never seen must not lend its file to another job.
  985. Opens its own short-lived session, like the caller does, so the pooled
  986. connection is not held across the FTP work that follows.
  987. """
  988. subtask_id = str(getattr(state, "subtask_id", "") or "").strip()
  989. if subtask_id in ("", "0"):
  990. return None
  991. from backend.app.models.archive import PrintArchive
  992. async with database.async_session() as db:
  993. archive = await db.scalar(
  994. select(PrintArchive)
  995. .where(
  996. PrintArchive.printer_id == printer_id,
  997. PrintArchive.status == "printing",
  998. PrintArchive.subtask_id == subtask_id,
  999. )
  1000. .order_by(PrintArchive.created_at.desc())
  1001. .limit(1)
  1002. )
  1003. if archive is None or not archive.file_path:
  1004. return None
  1005. path = settings.base_dir / archive.file_path
  1006. return path if path.is_file() and str(path).endswith(".3mf") else None
  1007. @router.get("/{printer_id}/cover")
  1008. async def get_printer_cover(
  1009. printer_id: int,
  1010. view: str | None = None,
  1011. _: None = RequireCameraStreamTokenIfAuthEnabled,
  1012. ):
  1013. """Get the cover image for the current print job.
  1014. Args:
  1015. view: Optional view type. Use "top" for the top-down build plate view or
  1016. "pick" for the slicer's object-ID mask used by skip objects.
  1017. Default returns angled 3D perspective view.
  1018. """
  1019. # Fetch the printer in a short-lived session and release the pooled DB
  1020. # connection BEFORE the FTP download below. Previously this route took its
  1021. # row via Depends(get_db), whose session stays open for the whole request —
  1022. # so a 3MF cover download (up to 8 paths × 3 retries with backoff, minutes
  1023. # under FTP contention) pinned one pooled connection idle-in-transaction the
  1024. # entire time (issue #2572). db is used only for this one SELECT; everything
  1025. # after reads already-loaded printer.* scalars (expire_on_commit=False keeps
  1026. # them readable), printer_manager, and FTP/zip — no lazy loads.
  1027. #
  1028. # Reference async_session via the module so the maker is looked up at call
  1029. # time — keeps it in sync with reinitialize_database() and lets the test
  1030. # harness's patch of backend.app.core.database.async_session take effect.
  1031. async with database.async_session() as db:
  1032. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1033. printer = result.scalar_one_or_none()
  1034. if not printer:
  1035. raise HTTPException(404, "Printer not found")
  1036. state = printer_manager.get_status(printer_id)
  1037. if not state:
  1038. raise HTTPException(404, "Printer not connected")
  1039. # Use subtask_name as the 3MF filename (gcode_file is the path inside the 3MF)
  1040. subtask_name = state.subtask_name
  1041. if not subtask_name:
  1042. raise HTTPException(404, f"No subtask_name in printer state (state={state.state})")
  1043. # Resolve the active plate. Precedence (#1166):
  1044. # 1. The plate Bambuddy dispatched (authoritative when we sent the print)
  1045. # 2. plate_(\d+)\.gcode regex on state.gcode_file (works on firmware that
  1046. # reflects the full path, e.g. some X1C builds)
  1047. # 3. Scan the downloaded 3MF for a unique Metadata/plate_*.gcode (covers
  1048. # per-plate archives sliced separately in Bambu Studio, where the
  1049. # printer's gcode_file echo is just the .3mf filename)
  1050. # 4. Fall back to plate 1
  1051. # The 3MF-scan fallback runs later — after the file is on disk.
  1052. plate_num = resolve_plate_id(state)
  1053. if plate_num is not None:
  1054. logger.info("Cover: resolved plate %s before download (subtask=%s)", plate_num, subtask_name)
  1055. # Normalize view parameter
  1056. view_key = view or "default"
  1057. # Check cache. Cache by (subtask_name, view_key) only — clear_cover_cache()
  1058. # runs on every print start, so a re-dispatch with a different plate gets
  1059. # a fresh image regardless. Pre-#1166 the key included plate_num, but with
  1060. # late plate resolution the cache check would always miss.
  1061. cache_key = (subtask_name, view_key)
  1062. if printer_id in _cover_cache and cache_key in _cover_cache[printer_id]:
  1063. return Response(content=_cover_cache[printer_id][cache_key], media_type="image/png")
  1064. # Negative-cache short-circuit (#1420): if a prior lookup for this same
  1065. # subtask + view already failed, don't replay 8 FTP retries on every page
  1066. # refresh. _cover_404_cache is cleared on print start.
  1067. if printer_id in _cover_404_cache and cache_key in _cover_404_cache[printer_id]:
  1068. raise HTTPException(404, f"No cover available for '{subtask_name}' (cached)")
  1069. # Coalesce concurrent downloads for the same cover (#2572). The positive and
  1070. # negative caches were just checked above; if another request is already
  1071. # downloading this exact cover, wait for it and serve from the cache it fills
  1072. # instead of launching a duplicate multi-path FTP + 3MF extraction.
  1073. inflight_key = (printer_id, subtask_name, view_key)
  1074. leader = _cover_inflight.get(inflight_key)
  1075. if leader is not None:
  1076. # shield() so our own cancellation can't cancel the shared leader.
  1077. try:
  1078. await asyncio.shield(leader)
  1079. except Exception:
  1080. pass
  1081. if printer_id in _cover_cache and cache_key in _cover_cache[printer_id]:
  1082. return Response(content=_cover_cache[printer_id][cache_key], media_type="image/png")
  1083. if printer_id in _cover_404_cache and cache_key in _cover_404_cache[printer_id]:
  1084. raise HTTPException(404, f"No cover available for '{subtask_name}' (cached)")
  1085. # Leader finished without filling either cache (a transient 503) — fall
  1086. # through and try the download ourselves.
  1087. fut: asyncio.Future = asyncio.get_event_loop().create_future()
  1088. _cover_inflight[inflight_key] = fut
  1089. try:
  1090. image_data = await _produce_cover_image(
  1091. printer,
  1092. printer_id,
  1093. subtask_name,
  1094. view,
  1095. view_key,
  1096. plate_num,
  1097. cache_key,
  1098. archive_path=await _running_print_archive_file(printer_id, state),
  1099. )
  1100. return Response(content=image_data, media_type="image/png")
  1101. finally:
  1102. if not fut.done():
  1103. fut.set_result(None)
  1104. _cover_inflight.pop(inflight_key, None)
  1105. async def _produce_cover_image(
  1106. printer: Printer,
  1107. printer_id: int,
  1108. subtask_name: str,
  1109. view: str | None,
  1110. view_key: str,
  1111. plate_num: int | None,
  1112. cache_key: tuple[str, str],
  1113. archive_path: Path | None = None,
  1114. ) -> bytes:
  1115. """Download the active-print 3MF and extract its cover thumbnail (#2572).
  1116. Split out of ``get_printer_cover`` so concurrent requests for the same cover
  1117. can single-flight through it (see ``_cover_inflight``). Returns the PNG bytes
  1118. on success (also filling ``_cover_cache``) and raises ``HTTPException`` on
  1119. failure (filling ``_cover_404_cache`` for the definitive 404s). Does no DB
  1120. work — the caller already released the pooled connection before this runs,
  1121. which is also why ``archive_path`` arrives resolved rather than looked up
  1122. here.
  1123. """
  1124. # Build possible 3MF filenames from subtask_name
  1125. # Bambu printers may store files as "name.gcode.3mf" (sliced via Bambu Studio)
  1126. # or just "name.3mf" (uploaded directly)
  1127. possible_filenames = []
  1128. if subtask_name.endswith(".3mf"):
  1129. possible_filenames.append(subtask_name)
  1130. else:
  1131. # Try both naming patterns
  1132. possible_filenames.append(f"{subtask_name}.gcode.3mf")
  1133. possible_filenames.append(f"{subtask_name}.3mf")
  1134. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  1135. if " " in subtask_name:
  1136. normalized = subtask_name.replace(" ", "_")
  1137. if normalized.endswith(".3mf"):
  1138. possible_filenames.append(normalized)
  1139. else:
  1140. possible_filenames.append(f"{normalized}.gcode.3mf")
  1141. possible_filenames.append(f"{normalized}.3mf")
  1142. # Build list of all remote paths to try
  1143. remote_paths = []
  1144. for filename in possible_filenames:
  1145. remote_paths.extend(
  1146. [
  1147. f"/{filename}", # Root directory (most common)
  1148. f"/cache/{filename}",
  1149. f"/model/{filename}",
  1150. f"/data/{filename}",
  1151. ]
  1152. )
  1153. # Use first filename for temp path (will be reused)
  1154. temp_filename = possible_filenames[0]
  1155. temp_path = settings.archive_dir / "temp" / f"cover_{printer_id}_{temp_filename}"
  1156. temp_path.parent.mkdir(parents=True, exist_ok=True)
  1157. storage = print_file_reachable_over_ftp(printer_manager.get_status(printer_id))
  1158. # Cache check (#972): the archive-metadata flow in main.py may have already
  1159. # downloaded this 3MF during the print-start handler. Reusing that file
  1160. # avoids a second 36MB transfer competing with the printer's single FTP
  1161. # socket (which produces the 425 errors that feed the retry storm).
  1162. #
  1163. # The dispatch's own filename is a candidate too: it is what the archive
  1164. # flow's probe cached the file under, and it does not always survive the
  1165. # trip through subtask_name (#2856).
  1166. downloaded = False
  1167. using_cached = False
  1168. for candidate_name in (*possible_filenames, storage.probe_filename):
  1169. if not candidate_name:
  1170. continue
  1171. cached = get_cached_3mf(printer_id, candidate_name)
  1172. if cached:
  1173. logger.info("Cover using cached 3MF from %s (avoided duplicate FTP)", cached)
  1174. temp_path = cached
  1175. downloaded = True
  1176. using_cached = True
  1177. break
  1178. if not downloaded:
  1179. # Same idea, one step further back: that in-memory cache dies with the
  1180. # process, but the archive of the print that is still running holds the
  1181. # very 3MF on disk. Without this, reopening a card or the skip-objects
  1182. # plate after a restart pulls the whole file back off a printer that is
  1183. # mid-print — measured at three concurrent fan-outs, thirteen seconds
  1184. # and a 0-byte read on the maintainer's H2C, which is exactly the
  1185. # single-socket contention #972 was about.
  1186. if archive_path is not None:
  1187. logger.info("Cover using the running print's archived 3MF at %s (no FTP)", archive_path)
  1188. temp_path = archive_path
  1189. downloaded = True
  1190. using_cached = True
  1191. if not downloaded:
  1192. # The cover lives inside the 3MF, so it is only reachable if the 3MF is.
  1193. # When the printer kept the print on internal storage there is nothing
  1194. # at any of these paths, and walking all sixteen of them just to end on
  1195. # a 404 that reads as "this print has no cover" helps nobody (#2780).
  1196. #
  1197. # Unless the printer is wrong about that, which an H2D with a card in
  1198. # routinely is (#2856). The dispatch names the file, so when it does,
  1199. # trade the immediate 404 for a five-path probe of that one name — same
  1200. # single connection, and it is the only way this endpoint ever recovers
  1201. # a cover for a print the archive flow did not see start.
  1202. max_retries = 2
  1203. if not storage.reachable:
  1204. if not storage.probe_filename:
  1205. _cover_404_cache.setdefault(printer_id, set()).add(cache_key)
  1206. raise HTTPException(
  1207. 404,
  1208. f"The print file for '{subtask_name}' is not on storage Bambuddy can read over FTPS "
  1209. f"({storage.reason}), so it has no cover to extract.",
  1210. )
  1211. remote_paths = ftp_probe_paths(storage.probe_filename)
  1212. # The dispatch's name is the authoritative one — a print whose
  1213. # subtask_name has been normalized or truncated would otherwise be
  1214. # cached under a key the archive flow never looks up.
  1215. temp_filename = storage.probe_filename
  1216. temp_path = settings.archive_dir / "temp" / f"cover_{printer_id}_{temp_filename}"
  1217. # One look, not three: the printer has already said this file is not
  1218. # here, so a retry storm on top of a hunch is exactly what #2780 was.
  1219. max_retries = 0
  1220. logger.info(
  1221. f"Trying to download cover for '{subtask_name}' from {printer.ip_address} (trying {len(remote_paths)} paths)"
  1222. )
  1223. # Retry logic for transient FTP failures
  1224. last_error = None
  1225. for attempt in range(max_retries + 1):
  1226. if ftps_handshake_blocked(printer.ip_address):
  1227. # Nothing to retry: the printer is not completing a TLS
  1228. # handshake on port 990, so no path and no attempt reaches it
  1229. # (#2780). Report the real cause instead of the 404 below,
  1230. # which would read as "this print has no cover".
  1231. raise HTTPException(
  1232. 503,
  1233. f"Printer {printer.ip_address} is not answering its file service over TLS. "
  1234. "Bambuddy will try again shortly.",
  1235. )
  1236. try:
  1237. downloaded = await download_file_try_paths_async(
  1238. printer.ip_address,
  1239. printer.access_code,
  1240. remote_paths,
  1241. temp_path,
  1242. printer_model=printer.model,
  1243. )
  1244. if downloaded:
  1245. break
  1246. except Exception as e:
  1247. last_error = e
  1248. if attempt < max_retries:
  1249. logger.warning("FTP download attempt %s failed: %s, retrying...", attempt + 1, e)
  1250. await asyncio.sleep(0.5 * (attempt + 1)) # Brief backoff
  1251. else:
  1252. logger.error("FTP download failed after %s attempts: %s", max_retries + 1, e)
  1253. if last_error and not downloaded:
  1254. raise HTTPException(503, f"FTP download temporarily unavailable: {last_error}")
  1255. if not downloaded:
  1256. # Remember this failure so subsequent requests for the same print
  1257. # skip the 8-path FTP fan-out (#1420).
  1258. _cover_404_cache.setdefault(printer_id, set()).add(cache_key)
  1259. if not storage.reachable:
  1260. # The probe looked and found nothing, so the printer's own
  1261. # account of where the file went is the answer after all —
  1262. # keep saying so rather than reporting a generic miss (#2780).
  1263. raise HTTPException(
  1264. 404,
  1265. f"The print file for '{subtask_name}' is not on storage Bambuddy can read over FTPS "
  1266. f"({storage.reason}), so it has no cover to extract.",
  1267. )
  1268. raise HTTPException(
  1269. 404,
  1270. f"Could not download 3MF file for '{subtask_name}' from printer {printer.ip_address}. Tried: {possible_filenames}",
  1271. )
  1272. # Share the fresh download with the archive flow.
  1273. cache_3mf_download(printer_id, temp_filename, temp_path)
  1274. # Verify file actually exists and has content
  1275. if not temp_path.exists():
  1276. raise HTTPException(500, f"Download reported success but file not found: {temp_path}")
  1277. file_size = temp_path.stat().st_size
  1278. logger.info("Downloaded file size: %s bytes", file_size)
  1279. if file_size == 0:
  1280. if not using_cached:
  1281. temp_path.unlink()
  1282. raise HTTPException(500, f"Downloaded file is empty for '{subtask_name}'")
  1283. # Offer the file to the archive flow before extracting the thumbnail. When
  1284. # the print started inside the printer's FTPS cool-off, the archive flow
  1285. # gave up without a single connection and this endpoint holds the very file
  1286. # it wanted — which used to be read for a thumbnail and then deleted at
  1287. # print completion, leaving a permanently empty archive (#2957). Covers the
  1288. # cached branch as well as a fresh download: whoever fetched it, the running
  1289. # print's archive should have it. A no-op unless that archive is a fallback.
  1290. from backend.app.main import try_recover_fallback_archive
  1291. await try_recover_fallback_archive(printer_id, temp_filename, temp_path)
  1292. try:
  1293. # Extract thumbnail from 3MF (which is a ZIP file)
  1294. try:
  1295. zf = zipfile.ZipFile(temp_path, "r")
  1296. except zipfile.BadZipFile:
  1297. raise HTTPException(500, "Downloaded file is not a valid 3MF/ZIP archive")
  1298. except OSError as e:
  1299. logger.error("Failed to open 3MF file: %s", e, exc_info=True)
  1300. raise HTTPException(500, "Failed to open 3MF file. Check server logs for details.")
  1301. try:
  1302. # 3MF-scan fallback for plate detection (#1166). Per-plate archives
  1303. # sliced separately in Bambu Studio contain a single
  1304. # Metadata/plate_N.gcode for the active plate, even though
  1305. # thumbnails for all plates are bundled. Using that gcode's plate
  1306. # number prevents falling back to plate_1.png.
  1307. if plate_num is None:
  1308. plate_gcodes = [name for name in zf.namelist() if re.match(r"^Metadata/plate_\d+\.gcode$", name)]
  1309. if len(plate_gcodes) == 1:
  1310. match = re.search(r"plate_(\d+)\.gcode", plate_gcodes[0])
  1311. if match:
  1312. plate_num = int(match.group(1))
  1313. logger.info("Cover: detected plate %s from 3MF contents", plate_num)
  1314. if plate_num is None:
  1315. plate_num = 1
  1316. # Try common thumbnail paths in 3MF files
  1317. # Use plate_num to get the correct plate's thumbnail for multi-plate projects
  1318. # Use top-down view if requested (better for skip objects modal)
  1319. if view == "pick":
  1320. # Only the active plate's mask, with no fallback: every other view
  1321. # falls back to plate 1 because a slightly wrong picture is better
  1322. # than none, but a mask is coordinates, not decoration. Plate 1's
  1323. # mask over plate 3's layout would resolve clicks to whichever
  1324. # object happened to occupy that pixel on a different plate.
  1325. thumbnail_paths = [f"Metadata/pick_{plate_num}.png"]
  1326. elif view == "top":
  1327. thumbnail_paths = [
  1328. f"Metadata/top_{plate_num}.png",
  1329. # Fall back to plate 1 if specific plate not found
  1330. "Metadata/top_1.png",
  1331. f"Metadata/plate_{plate_num}.png",
  1332. "Metadata/plate_1.png",
  1333. "Metadata/thumbnail.png",
  1334. ]
  1335. else:
  1336. thumbnail_paths = [
  1337. f"Metadata/plate_{plate_num}.png",
  1338. # Fall back to plate 1 if specific plate not found
  1339. "Metadata/plate_1.png",
  1340. "Metadata/thumbnail.png",
  1341. f"Metadata/plate_{plate_num}_small.png",
  1342. "Metadata/plate_1_small.png",
  1343. "Thumbnails/thumbnail.png",
  1344. "thumbnail.png",
  1345. ]
  1346. for thumb_path in thumbnail_paths:
  1347. try:
  1348. image_data = zf.read(thumb_path)
  1349. if printer_id not in _cover_cache:
  1350. _cover_cache[printer_id] = {}
  1351. _cover_cache[printer_id][(subtask_name, view_key)] = image_data
  1352. return image_data
  1353. except KeyError:
  1354. continue
  1355. # If no specific thumbnail found, try any PNG in Metadata. Never for
  1356. # "pick": handing back a rendered thumbnail in place of the object-ID
  1357. # mask is worse than nothing, because the caller can't tell the
  1358. # difference and decodes the render's pixel colours as object IDs —
  1359. # dark pixels yield small integers that collide with real IDs, so a
  1360. # click would select an arbitrary object and skip it irreversibly.
  1361. # A 404 is what tells the UI to fall back to the checklist.
  1362. if view != "pick":
  1363. for name in zf.namelist():
  1364. if name.startswith("Metadata/") and name.endswith(".png"):
  1365. image_data = zf.read(name)
  1366. if printer_id not in _cover_cache:
  1367. _cover_cache[printer_id] = {}
  1368. _cover_cache[printer_id][(subtask_name, view_key)] = image_data
  1369. return image_data
  1370. _cover_404_cache.setdefault(printer_id, set()).add(cache_key)
  1371. raise HTTPException(404, "No thumbnail found in 3MF file")
  1372. finally:
  1373. zf.close()
  1374. finally:
  1375. # Only delete when this invocation owns the file. A cached path is
  1376. # shared with the archive flow — removing it would force a refetch
  1377. # the next time either flow needs the 3MF.
  1378. if not using_cached and temp_path.exists():
  1379. temp_path.unlink()
  1380. # ============================================
  1381. # File Manager Endpoints
  1382. # ============================================
  1383. async def _load_printer_or_404(printer_id: int) -> Printer:
  1384. """Load a printer in a short-lived session, releasing the pooled DB
  1385. connection before the caller starts any FTP/network I/O (#2572).
  1386. The file-manager and storage routes talk FTP to the printer, which can
  1387. block for the full socket timeout — longer when a saturated FTP pool backs
  1388. up. Holding the request's Depends(get_db) session across that FTP pinned one
  1389. pooled connection idle-in-transaction per in-flight request, a top cause of
  1390. pool exhaustion on large farms. The returned row's scalar columns stay
  1391. readable after the session closes (expire_on_commit=False). Raises 404 when
  1392. the printer doesn't exist.
  1393. Reference async_session via the module so the maker is resolved at call time
  1394. — keeps it in sync with reinitialize_database() and lets tests patch it.
  1395. """
  1396. async with database.async_session() as db:
  1397. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1398. printer = result.scalar_one_or_none()
  1399. if not printer:
  1400. raise HTTPException(404, "Printer not found")
  1401. return printer
  1402. @router.get("/{printer_id}/files")
  1403. async def list_printer_files(
  1404. printer_id: int,
  1405. path: str = "/",
  1406. _=RequirePrinterPermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  1407. ):
  1408. """List files on the printer at the specified path."""
  1409. printer = await _load_printer_or_404(printer_id)
  1410. listing = await list_files_result_async(
  1411. printer.ip_address,
  1412. printer.access_code,
  1413. path,
  1414. printer_model=printer.model,
  1415. )
  1416. files = listing.files
  1417. # Add full path to each file
  1418. for f in files:
  1419. f["path"] = f"{path.rstrip('/')}/{f['name']}" if path != "/" else f"/{f['name']}"
  1420. return {
  1421. "path": path,
  1422. "files": files,
  1423. "warnings": [] if listing.available else ["printer_unavailable"],
  1424. }
  1425. @router.get("/{printer_id}/files/download")
  1426. async def download_printer_file(
  1427. printer_id: int,
  1428. path: str,
  1429. _=RequirePrinterPermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  1430. ):
  1431. """Download a file from the printer."""
  1432. printer = await _load_printer_or_404(printer_id)
  1433. try:
  1434. async with asyncio.timeout(MAX_PRINTER_ZIP_PREPARE_SECONDS):
  1435. result = await build_printer_file(
  1436. printer,
  1437. path,
  1438. None,
  1439. bundle_key=f"single-{secrets.token_urlsafe(18)}",
  1440. )
  1441. except PrinterFilesZipTooLargeError as exc:
  1442. raise HTTPException(413, str(exc)) from exc
  1443. except PrinterFilesZipInsufficientSpaceError as exc:
  1444. raise HTTPException(507, str(exc)) from exc
  1445. except FileNotFoundError:
  1446. raise HTTPException(404, f"File not found: {path}")
  1447. except TimeoutError as exc:
  1448. raise HTTPException(504, "Printer download exceeded the 30-minute limit") from exc
  1449. # Determine content type based on extension
  1450. filename = path.split("/")[-1]
  1451. ext = filename.lower().split(".")[-1] if "." in filename else ""
  1452. content_types = {
  1453. "3mf": "application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1454. "gcode": "text/plain",
  1455. "mp4": "video/mp4",
  1456. "avi": "video/x-msvideo",
  1457. "png": "image/png",
  1458. "jpg": "image/jpeg",
  1459. "jpeg": "image/jpeg",
  1460. "json": "application/json",
  1461. "txt": "text/plain",
  1462. }
  1463. content_type = content_types.get(ext, "application/octet-stream")
  1464. return FileResponse(
  1465. path=result.path,
  1466. filename=filename,
  1467. media_type=content_type,
  1468. headers={"Content-Disposition": build_content_disposition(filename)},
  1469. background=BackgroundTask(remove_printer_files_zip, result.path),
  1470. )
  1471. @router.get("/{printer_id}/files/gcode")
  1472. async def get_printer_file_gcode(
  1473. printer_id: int,
  1474. path: str,
  1475. _=RequirePrinterPermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  1476. ):
  1477. """Get gcode for a file stored on a printer (for preview)."""
  1478. import io
  1479. printer = await _load_printer_or_404(printer_id)
  1480. data = await download_file_bytes_async(printer.ip_address, printer.access_code, path, printer_model=printer.model)
  1481. if data is None:
  1482. raise HTTPException(404, f"File not found: {path}")
  1483. filename = path.split("/")[-1]
  1484. lower = filename.lower()
  1485. if lower.endswith(".gcode"):
  1486. return Response(content=data, media_type="text/plain")
  1487. if lower.endswith(".3mf"):
  1488. try:
  1489. with zipfile.ZipFile(io.BytesIO(data), "r") as zf:
  1490. gcode_files = [n for n in zf.namelist() if n.endswith(".gcode")]
  1491. if not gcode_files:
  1492. raise HTTPException(status_code=404, detail="No gcode found in 3MF file")
  1493. gcode_content = zf.read(gcode_files[0])
  1494. return Response(content=gcode_content, media_type="text/plain")
  1495. except zipfile.BadZipFile:
  1496. raise HTTPException(status_code=400, detail="Invalid 3MF file")
  1497. raise HTTPException(status_code=400, detail="Unsupported file type")
  1498. @router.get("/{printer_id}/files/plates")
  1499. async def get_printer_file_plates(
  1500. printer_id: int,
  1501. path: str = Query(..., description="Full path to the 3MF file on the printer"),
  1502. _=RequirePrinterPermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  1503. ):
  1504. """Get available plates from a multi-plate 3MF file stored on a printer."""
  1505. import io
  1506. import json
  1507. import defusedxml.ElementTree as ET
  1508. printer = await _load_printer_or_404(printer_id)
  1509. filename = path.split("/")[-1]
  1510. if not filename.lower().endswith(".3mf"):
  1511. return {
  1512. "printer_id": printer_id,
  1513. "path": path,
  1514. "filename": filename,
  1515. "plates": [],
  1516. "is_multi_plate": False,
  1517. }
  1518. data = await download_file_bytes_async(printer.ip_address, printer.access_code, path, printer_model=printer.model)
  1519. if data is None:
  1520. raise HTTPException(404, f"File not found: {path}")
  1521. plates = []
  1522. try:
  1523. with zipfile.ZipFile(io.BytesIO(data), "r") as zf:
  1524. namelist = zf.namelist()
  1525. # Find all plate gcode files to determine available plates
  1526. gcode_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".gcode")]
  1527. # If no gcode is present (source-only or unsliced), fall back to plate JSON/PNG
  1528. plate_indices: list[int] = []
  1529. if gcode_files:
  1530. for gf in gcode_files:
  1531. try:
  1532. plate_str = gf[15:-6] # Remove "Metadata/plate_" and ".gcode"
  1533. plate_indices.append(int(plate_str))
  1534. except ValueError:
  1535. pass # Skip gcode files with non-numeric plate indices
  1536. else:
  1537. plate_json_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".json")]
  1538. plate_png_files = [
  1539. n
  1540. for n in namelist
  1541. if n.startswith("Metadata/plate_")
  1542. and n.endswith(".png")
  1543. and "_small" not in n
  1544. and "no_light" not in n
  1545. ]
  1546. plate_name_candidates = plate_json_files + plate_png_files
  1547. plate_re = re.compile(r"^Metadata/plate_(\d+)\.(json|png)$")
  1548. seen_indices: set[int] = set()
  1549. for name in plate_name_candidates:
  1550. match = plate_re.match(name)
  1551. if match:
  1552. try:
  1553. index = int(match.group(1))
  1554. except ValueError:
  1555. continue
  1556. if index in seen_indices:
  1557. continue
  1558. seen_indices.add(index)
  1559. plate_indices.append(index)
  1560. if not plate_indices:
  1561. return {
  1562. "printer_id": printer_id,
  1563. "path": path,
  1564. "filename": filename,
  1565. "plates": [],
  1566. "is_multi_plate": False,
  1567. }
  1568. plate_indices.sort()
  1569. # Parse model_settings.config for plate names
  1570. plate_names = {}
  1571. if "Metadata/model_settings.config" in namelist:
  1572. try:
  1573. model_content = zf.read("Metadata/model_settings.config").decode()
  1574. model_root = ET.fromstring(model_content)
  1575. for plate_elem in model_root.findall(".//plate"):
  1576. plater_id = None
  1577. plater_name = None
  1578. for meta in plate_elem.findall("metadata"):
  1579. key = meta.get("key")
  1580. value = meta.get("value")
  1581. if key == "plater_id" and value:
  1582. try:
  1583. plater_id = int(value)
  1584. except ValueError:
  1585. pass # Skip plate with unparseable ID
  1586. elif key == "plater_name" and value:
  1587. plater_name = value.strip()
  1588. if plater_id is not None and plater_name:
  1589. plate_names[plater_id] = plater_name
  1590. except Exception:
  1591. pass # Plate names are optional; continue without them
  1592. # Parse slice_info.config for plate metadata
  1593. plate_metadata = {}
  1594. if "Metadata/slice_info.config" in namelist:
  1595. content = zf.read("Metadata/slice_info.config").decode()
  1596. root = ET.fromstring(content)
  1597. for plate_elem in root.findall(".//plate"):
  1598. plate_info = {"filaments": [], "prediction": None, "weight": None, "name": None, "objects": []}
  1599. plate_index = None
  1600. for meta in plate_elem.findall("metadata"):
  1601. key = meta.get("key")
  1602. value = meta.get("value")
  1603. if key == "index" and value:
  1604. try:
  1605. plate_index = int(value)
  1606. except ValueError:
  1607. pass # Skip plate with unparseable index
  1608. elif key == "prediction" and value:
  1609. try:
  1610. plate_info["prediction"] = int(value)
  1611. except ValueError:
  1612. pass # Skip unparseable prediction; leave as None
  1613. elif key == "weight" and value:
  1614. try:
  1615. plate_info["weight"] = float(value)
  1616. except ValueError:
  1617. pass # Skip unparseable weight; leave as None
  1618. # Get filaments used in this plate
  1619. for filament_elem in plate_elem.findall("filament"):
  1620. filament_id = filament_elem.get("id")
  1621. filament_type = filament_elem.get("type", "")
  1622. filament_color = filament_elem.get("color", "")
  1623. used_g = filament_elem.get("used_g", "0")
  1624. used_m = filament_elem.get("used_m", "0")
  1625. try:
  1626. used_grams = float(used_g)
  1627. except (ValueError, TypeError):
  1628. used_grams = 0
  1629. if used_grams > 0 and filament_id:
  1630. plate_info["filaments"].append(
  1631. {
  1632. "slot_id": int(filament_id),
  1633. "type": filament_type,
  1634. "color": filament_color,
  1635. "used_grams": round(used_grams, 1),
  1636. "used_meters": float(used_m) if used_m else 0,
  1637. }
  1638. )
  1639. plate_info["filaments"].sort(key=lambda x: x["slot_id"])
  1640. # Collect object names
  1641. for obj_elem in plate_elem.findall("object"):
  1642. obj_name = obj_elem.get("name")
  1643. if obj_name and obj_name not in plate_info["objects"]:
  1644. plate_info["objects"].append(obj_name)
  1645. # Set plate name
  1646. if plate_index is not None:
  1647. custom_name = plate_names.get(plate_index)
  1648. if custom_name:
  1649. plate_info["name"] = custom_name
  1650. elif plate_info["objects"]:
  1651. plate_info["name"] = plate_info["objects"][0]
  1652. plate_metadata[plate_index] = plate_info
  1653. # Parse plate_*.json for object lists when slice_info is missing
  1654. plate_json_objects: dict[int, list[str]] = {}
  1655. for name in namelist:
  1656. match = re.match(r"^Metadata/plate_(\d+)\.json$", name)
  1657. if not match:
  1658. continue
  1659. try:
  1660. plate_index = int(match.group(1))
  1661. except ValueError:
  1662. continue
  1663. try:
  1664. payload = json.loads(zf.read(name).decode())
  1665. bbox_objects = payload.get("bbox_objects", [])
  1666. names: list[str] = []
  1667. for obj in bbox_objects:
  1668. obj_name = obj.get("name") if isinstance(obj, dict) else None
  1669. if obj_name and obj_name not in names:
  1670. names.append(obj_name)
  1671. if names:
  1672. plate_json_objects[plate_index] = names
  1673. except Exception:
  1674. continue
  1675. # Build plate list
  1676. for idx in plate_indices:
  1677. meta = plate_metadata.get(idx, {})
  1678. has_thumbnail = f"Metadata/plate_{idx}.png" in namelist
  1679. objects = meta.get("objects", [])
  1680. if not objects:
  1681. objects = plate_json_objects.get(idx, [])
  1682. plate_name = meta.get("name")
  1683. if not plate_name:
  1684. plate_name = plate_names.get(idx)
  1685. if not plate_name and objects:
  1686. plate_name = objects[0]
  1687. plates.append(
  1688. {
  1689. "index": idx,
  1690. "name": plate_name,
  1691. "objects": objects,
  1692. "object_count": len(objects),
  1693. "has_thumbnail": has_thumbnail,
  1694. "thumbnail_url": f"/api/v1/printers/{printer_id}/files/plate-thumbnail/{idx}?path={path}",
  1695. "print_time_seconds": meta.get("prediction"),
  1696. "filament_used_grams": meta.get("weight"),
  1697. "filaments": meta.get("filaments", []),
  1698. }
  1699. )
  1700. except Exception as e:
  1701. logger.warning("Failed to parse plates from printer file %s: %s", path, e)
  1702. return {
  1703. "printer_id": printer_id,
  1704. "path": path,
  1705. "filename": filename,
  1706. "plates": plates,
  1707. "is_multi_plate": len(plates) > 1,
  1708. }
  1709. @router.get("/{printer_id}/files/plate-thumbnail/{plate_index}")
  1710. async def get_printer_file_plate_thumbnail(
  1711. printer_id: int,
  1712. plate_index: int,
  1713. path: str = Query(..., description="Full path to the 3MF file on the printer"),
  1714. _=RequirePrinterPermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  1715. ):
  1716. """Get a plate thumbnail image from a printer-stored 3MF file."""
  1717. import io
  1718. printer = await _load_printer_or_404(printer_id)
  1719. data = await download_file_bytes_async(printer.ip_address, printer.access_code, path, printer_model=printer.model)
  1720. if data is None:
  1721. raise HTTPException(404, f"File not found: {path}")
  1722. try:
  1723. with zipfile.ZipFile(io.BytesIO(data), "r") as zf:
  1724. thumb_path = f"Metadata/plate_{plate_index}.png"
  1725. if thumb_path in zf.namelist():
  1726. image_data = zf.read(thumb_path)
  1727. return Response(content=image_data, media_type="image/png")
  1728. except Exception:
  1729. pass # Corrupt or unreadable 3MF; fall through to 404
  1730. raise HTTPException(status_code=404, detail=f"Thumbnail for plate {plate_index} not found")
  1731. @router.post("/{printer_id}/files/download-zip")
  1732. async def download_printer_files_as_zip(
  1733. printer_id: int,
  1734. request: PrinterFilesDownloadRequest,
  1735. _=RequirePrinterPermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  1736. ):
  1737. """Download multiple files using a disk-backed ZIP.
  1738. Kept backward-compatible for API clients: relative paths are rooted,
  1739. duplicate paths receive collision-safe names, and an all-failed request
  1740. returns an empty ZIP as the historical endpoint did. The browser uses the
  1741. asynchronous preparation endpoints below.
  1742. """
  1743. if not request.paths:
  1744. raise HTTPException(400, "No files specified")
  1745. printer = await _load_printer_or_404(printer_id)
  1746. normalized_paths = [path if path.startswith("/") else f"/{path}" for path in request.paths]
  1747. normalized_sizes = {path if path.startswith("/") else f"/{path}": size for path, size in request.sizes.items()}
  1748. try:
  1749. async with asyncio.timeout(MAX_PRINTER_ZIP_PREPARE_SECONDS):
  1750. result = await build_printer_files_zip(
  1751. printer,
  1752. normalized_paths,
  1753. normalized_sizes,
  1754. preserve_paths=False,
  1755. allow_empty=True,
  1756. )
  1757. except PrinterFilesZipTooLargeError as exc:
  1758. raise HTTPException(413, str(exc)) from exc
  1759. except PrinterFilesZipInsufficientSpaceError as exc:
  1760. raise HTTPException(507, str(exc)) from exc
  1761. except TimeoutError as exc:
  1762. raise HTTPException(504, "Printer ZIP preparation exceeded the 30-minute limit") from exc
  1763. return FileResponse(
  1764. path=result.path,
  1765. filename="printer-files.zip",
  1766. media_type="application/zip",
  1767. headers={
  1768. "X-Bambuddy-Files-Requested": str(result.requested),
  1769. "X-Bambuddy-Files-Downloaded": str(result.successful),
  1770. "X-Bambuddy-Files-Failed": str(len(result.failed_paths)),
  1771. },
  1772. background=BackgroundTask(remove_printer_files_zip, result.path),
  1773. )
  1774. @router.post("/{printer_id}/files/download-job")
  1775. async def create_printer_files_download_job(
  1776. printer_id: int,
  1777. request: PrinterFilesJobRequest,
  1778. _=RequirePrinterPermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  1779. ):
  1780. """Start a cancellable disk-backed preparation without holding the request."""
  1781. if not request.paths:
  1782. raise HTTPException(400, "No files specified")
  1783. if len(set(request.paths)) != len(request.paths):
  1784. raise HTTPException(400, "Selected printer paths must be unique")
  1785. if not request.as_zip and len(request.paths) != 1:
  1786. raise HTTPException(400, "Native downloads require exactly one file")
  1787. printer = await _load_printer_or_404(printer_id)
  1788. try:
  1789. status = await start_printer_files_job(
  1790. printer,
  1791. request.paths,
  1792. request.sizes,
  1793. request.filename,
  1794. as_zip=request.as_zip,
  1795. )
  1796. except PrinterFilesZipTooLargeError as exc:
  1797. raise HTTPException(413, str(exc)) from exc
  1798. except PrinterFilesZipInsufficientSpaceError as exc:
  1799. raise HTTPException(507, str(exc)) from exc
  1800. except ValueError as exc:
  1801. raise HTTPException(400, str(exc)) from exc
  1802. return status.__dict__
  1803. @router.get("/{printer_id}/files/download-jobs/{job_id}")
  1804. async def get_printer_files_download_job(
  1805. printer_id: int,
  1806. job_id: str,
  1807. _=RequirePrinterPermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  1808. ):
  1809. status = await get_printer_files_job(job_id, printer_id)
  1810. if status is None:
  1811. raise HTTPException(404, "Printer download job not found")
  1812. return status.__dict__
  1813. @router.delete("/{printer_id}/files/download-jobs/{job_id}")
  1814. async def cancel_printer_files_download_job(
  1815. printer_id: int,
  1816. job_id: str,
  1817. _=RequirePrinterPermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  1818. ):
  1819. if not await cancel_printer_files_job(job_id, printer_id):
  1820. raise HTTPException(404, "Printer download job not found")
  1821. return {"status": "cancelled"}
  1822. @router.get("/{printer_id}/files/dl/{token}/{filename}")
  1823. async def download_prepared_printer_files(
  1824. printer_id: int,
  1825. token: str,
  1826. filename: str,
  1827. ):
  1828. """Consume a resource-bound token and stream a prepared file natively."""
  1829. from backend.app.core.auth import verify_slicer_download_token
  1830. if not await verify_slicer_download_token(token, "printer-files", printer_id):
  1831. return download_error_response(403, "This download link has already been used or has expired.")
  1832. zip_path = printer_files_zip_path(printer_id, token)
  1833. raw_path = printer_file_path(printer_id, token)
  1834. if zip_path is not None and await asyncio.to_thread(zip_path.is_file):
  1835. prepared_path = zip_path
  1836. media_type = "application/zip"
  1837. elif raw_path is not None and await asyncio.to_thread(raw_path.is_file):
  1838. prepared_path = raw_path
  1839. media_type = "application/octet-stream"
  1840. else:
  1841. return download_error_response(404, "The prepared download is no longer on the server.")
  1842. safe_filename = safe_download_filename(filename, fallback="printer-download")
  1843. return FileResponse(
  1844. path=prepared_path,
  1845. filename=safe_filename,
  1846. media_type=media_type,
  1847. headers={"Content-Disposition": build_content_disposition(safe_filename)},
  1848. background=BackgroundTask(remove_printer_files_zip, prepared_path),
  1849. )
  1850. @router.delete("/{printer_id}/files")
  1851. async def delete_printer_file(
  1852. printer_id: int,
  1853. path: str,
  1854. _=RequirePrinterPermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  1855. ):
  1856. """Delete a file from the printer."""
  1857. printer = await _load_printer_or_404(printer_id)
  1858. from backend.app.services.bambu_ftp import DeleteResult
  1859. result = await delete_file_async(printer.ip_address, printer.access_code, path, printer_model=printer.model)
  1860. if result == DeleteResult.NOT_FOUND:
  1861. raise HTTPException(404, f"File not found on printer: {path}")
  1862. if result == DeleteResult.FAILED:
  1863. raise HTTPException(500, f"Failed to delete file: {path}")
  1864. return {"status": "deleted", "path": path}
  1865. @router.get("/{printer_id}/storage")
  1866. async def get_printer_storage(
  1867. printer_id: int,
  1868. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  1869. ):
  1870. """Get storage information from the printer."""
  1871. printer = await _load_printer_or_404(printer_id)
  1872. storage_info = await get_storage_info_async(printer.ip_address, printer.access_code, printer_model=printer.model)
  1873. return storage_info or {"used_bytes": None, "free_bytes": None}
  1874. # ============================================
  1875. # MQTT Debug Logging Endpoints
  1876. # ============================================
  1877. @router.post("/{printer_id}/logging/enable")
  1878. async def enable_mqtt_logging(
  1879. printer_id: int,
  1880. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1881. db: AsyncSession = Depends(get_db),
  1882. ):
  1883. """Enable MQTT message logging for a printer."""
  1884. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1885. printer = result.scalar_one_or_none()
  1886. if not printer:
  1887. raise HTTPException(404, "Printer not found")
  1888. success = printer_manager.enable_logging(printer_id, True)
  1889. if not success:
  1890. raise HTTPException(400, "Printer not connected")
  1891. return {"logging_enabled": True}
  1892. @router.post("/{printer_id}/logging/disable")
  1893. async def disable_mqtt_logging(
  1894. printer_id: int,
  1895. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1896. db: AsyncSession = Depends(get_db),
  1897. ):
  1898. """Disable MQTT message logging for a printer."""
  1899. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1900. printer = result.scalar_one_or_none()
  1901. if not printer:
  1902. raise HTTPException(404, "Printer not found")
  1903. success = printer_manager.enable_logging(printer_id, False)
  1904. if not success:
  1905. raise HTTPException(400, "Printer not connected")
  1906. return {"logging_enabled": False}
  1907. @router.get("/{printer_id}/logging")
  1908. async def get_mqtt_logs(
  1909. printer_id: int,
  1910. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  1911. db: AsyncSession = Depends(get_db),
  1912. ):
  1913. """Get MQTT message logs for a printer."""
  1914. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1915. printer = result.scalar_one_or_none()
  1916. if not printer:
  1917. raise HTTPException(404, "Printer not found")
  1918. logs = printer_manager.get_logs(printer_id)
  1919. return {
  1920. "logging_enabled": printer_manager.is_logging_enabled(printer_id),
  1921. "logs": [
  1922. {
  1923. "timestamp": log.timestamp,
  1924. "topic": log.topic,
  1925. "direction": log.direction,
  1926. "payload": log.payload,
  1927. }
  1928. for log in logs
  1929. ],
  1930. }
  1931. @router.delete("/{printer_id}/logging")
  1932. async def clear_mqtt_logs(
  1933. printer_id: int,
  1934. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1935. db: AsyncSession = Depends(get_db),
  1936. ):
  1937. """Clear MQTT message logs for a printer."""
  1938. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1939. printer = result.scalar_one_or_none()
  1940. if not printer:
  1941. raise HTTPException(404, "Printer not found")
  1942. printer_manager.clear_logs(printer_id)
  1943. return {"status": "cleared"}
  1944. # ============================================
  1945. # AMS Drying Endpoints
  1946. # ============================================
  1947. # The P1 firmware acks `ams_filament_drying` with result: success and then ignores it
  1948. # — Bambu's own P1 manual says drying "may only be controlled from the P1S screen"
  1949. # (#2533). Refuse the command rather than let the caller believe it landed.
  1950. _DRYING_SCREEN_ONLY_DETAIL = drying_preflight.SCREEN_ONLY_DETAIL
  1951. @router.post("/{printer_id}/drying/start")
  1952. async def start_drying(
  1953. printer_id: int,
  1954. ams_id: int,
  1955. temp: int = 45,
  1956. duration: int = 4,
  1957. filament: str = "",
  1958. rotate_tray: bool = False,
  1959. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1960. db: AsyncSession = Depends(get_db),
  1961. ):
  1962. """Send AMS drying start command. temp=45-85, duration=hours."""
  1963. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1964. printer = result.scalar_one_or_none()
  1965. if not printer:
  1966. raise HTTPException(404, "Printer not found")
  1967. # Server-side guard: reject if this model/firmware doesn't support drying
  1968. live_state = printer_manager.get_status(printer_id)
  1969. firmware = live_state.firmware_version if live_state else None
  1970. unsupported = drying_preflight.check_drying_supported(printer.model, firmware)
  1971. if unsupported:
  1972. raise HTTPException(400, unsupported)
  1973. if temp < 45 or temp > 85:
  1974. raise HTTPException(400, "Temperature must be 45-85°C")
  1975. if duration < 1 or duration > 24:
  1976. raise HTTPException(400, "Duration must be 1-24 hours")
  1977. # Inspect the live AMS unit: surface blocking dry_sf_reasons (otherwise the
  1978. # firmware silently ignores the command — #971) and backfill an empty
  1979. # filament field from the first loaded tray so the printer doesn't reject
  1980. # the payload.
  1981. target_ams = drying_preflight.find_ams_unit(live_state, ams_id)
  1982. blocking = drying_preflight.blocking_reason_codes(target_ams)
  1983. if blocking:
  1984. # Same pick the scheduled path makes, so both describe one blocked AMS
  1985. # the same way rather than differing on which code the firmware listed
  1986. # first.
  1987. raise HTTPException(
  1988. 409, drying_preflight.DRY_SF_REASON_MESSAGES[drying_preflight.primary_reason_code(blocking)]
  1989. )
  1990. filament = drying_preflight.resolve_filament(target_ams, filament)
  1991. success = printer_manager.send_drying_command(
  1992. printer_id, ams_id, temp, duration, mode=1, filament=filament, rotate_tray=rotate_tray
  1993. )
  1994. if not success:
  1995. raise HTTPException(400, "Printer not connected")
  1996. return {"status": "drying_started", "ams_id": ams_id, "temp": temp, "duration": duration}
  1997. @router.post("/{printer_id}/drying/stop")
  1998. async def stop_drying(
  1999. printer_id: int,
  2000. ams_id: int,
  2001. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  2002. db: AsyncSession = Depends(get_db),
  2003. ):
  2004. """Send AMS drying stop command."""
  2005. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2006. printer = result.scalar_one_or_none()
  2007. if not printer:
  2008. raise HTTPException(404, "Printer not found")
  2009. # Screen-only models ignore stop just as they ignore start — a cycle running on a
  2010. # P1S was started at the printer and has to be ended there too (#2533).
  2011. if drying_screen_only(printer.model):
  2012. raise HTTPException(400, _DRYING_SCREEN_ONLY_DETAIL)
  2013. success = printer_manager.send_drying_command(printer_id, ams_id, temp=0, duration=0, mode=0)
  2014. if not success:
  2015. raise HTTPException(400, "Printer not connected")
  2016. # A cycle the user stopped by hand tells us nothing about whether drying can
  2017. # move the humidity reading, so it must not count towards the auto-drying
  2018. # suspension (#2770). Imported here rather than at module scope to keep the
  2019. # existing routes/scheduler import direction.
  2020. from backend.app.services.print_scheduler import scheduler as print_scheduler
  2021. print_scheduler.forget_auto_dry_cycle(printer_id, ams_id)
  2022. return {"status": "drying_stopped", "ams_id": ams_id}
  2023. # ============================================
  2024. # Print Options (AI Detection) Endpoints
  2025. # ============================================
  2026. @router.post("/{printer_id}/print-options")
  2027. async def set_print_option(
  2028. printer_id: int,
  2029. module_name: str,
  2030. enabled: bool,
  2031. print_halt: bool = True,
  2032. sensitivity: str = "medium",
  2033. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  2034. db: AsyncSession = Depends(get_db),
  2035. ):
  2036. """Set an AI detection / print option on the printer.
  2037. Valid module_name values:
  2038. - spaghetti_detector: Spaghetti detection
  2039. - first_layer_inspector: First layer inspection
  2040. - printing_monitor: AI print quality monitoring
  2041. - buildplate_marker_detector: Build plate marker detection
  2042. - allow_skip_parts: Allow skipping failed parts
  2043. """
  2044. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2045. printer = result.scalar_one_or_none()
  2046. if not printer:
  2047. raise HTTPException(404, "Printer not found")
  2048. client = printer_manager.get_client(printer_id)
  2049. if not client or not client.state.connected:
  2050. raise HTTPException(400, "Printer not connected")
  2051. # Validate module_name
  2052. valid_modules = [
  2053. "spaghetti_detector",
  2054. "first_layer_inspector",
  2055. "printing_monitor",
  2056. "buildplate_marker_detector",
  2057. "allow_skip_parts",
  2058. "pileup_detector",
  2059. "clump_detector",
  2060. "airprint_detector",
  2061. "auto_recovery_step_loss",
  2062. ]
  2063. if module_name not in valid_modules:
  2064. raise HTTPException(400, f"Invalid module_name. Must be one of: {valid_modules}")
  2065. # Validate sensitivity
  2066. valid_sensitivities = ["low", "medium", "high", "never_halt"]
  2067. if sensitivity not in valid_sensitivities:
  2068. raise HTTPException(400, f"Invalid sensitivity. Must be one of: {valid_sensitivities}")
  2069. success = client.set_xcam_option(
  2070. module_name=module_name,
  2071. enabled=enabled,
  2072. print_halt=print_halt,
  2073. sensitivity=sensitivity,
  2074. )
  2075. if not success:
  2076. raise HTTPException(500, "Failed to send command to printer")
  2077. return {
  2078. "success": True,
  2079. "module_name": module_name,
  2080. "enabled": enabled,
  2081. "print_halt": print_halt,
  2082. "sensitivity": sensitivity,
  2083. }
  2084. @router.post("/{printer_id}/ams-backup")
  2085. async def set_ams_backup(
  2086. printer_id: int,
  2087. enabled: bool,
  2088. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  2089. db: AsyncSession = Depends(get_db),
  2090. ):
  2091. """Toggle AMS Filament Backup (auto-switch to a backup spool when one runs out)."""
  2092. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2093. printer = result.scalar_one_or_none()
  2094. if not printer:
  2095. raise HTTPException(404, "Printer not found")
  2096. client = printer_manager.get_client(printer_id)
  2097. if not client or not client.state.connected:
  2098. raise HTTPException(400, "Printer not connected")
  2099. success = client.set_ams_filament_backup(enabled)
  2100. if not success:
  2101. raise HTTPException(500, "Failed to send command to printer")
  2102. return {"success": True, "ams_filament_backup": enabled}
  2103. @router.get("/{printer_id}/inventory-remain")
  2104. async def get_inventory_remain(
  2105. printer_id: int,
  2106. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  2107. db: AsyncSession = Depends(get_db),
  2108. ):
  2109. """Per-globalTrayId remaining grams for slots bound to an inventory spool.
  2110. Mirrors `_build_inventory_remain_overrides` server-side so the PrintModal
  2111. client can apply the same two-tier "Prefer Lowest Remaining Filament" sort
  2112. the dispatcher uses (#1766). Works for both internal inventory and
  2113. Spoolman; unbound slots are absent from the map (client falls back to the
  2114. printer's MQTT `remain` for those).
  2115. `slot_materials` carries the same bindings with their material identity and
  2116. extruder side attached, which is what the modal's pre-flight filament check
  2117. needs to pool spools under AMS Filament Backup the way the dispatcher does.
  2118. It is deliberately server-computed: the identity rule lives in
  2119. `filament_deficit`, and a client-side reimplementation of it is exactly how
  2120. the modal came to block prints the dispatcher would have accepted. Unlike
  2121. `inventory_remain_g` it covers every binding, not just currently-loaded
  2122. slots — again matching what the dispatcher pools.
  2123. """
  2124. from backend.app.services.filament_deficit import build_slot_materials
  2125. from backend.app.services.print_scheduler import PrintScheduler
  2126. state = printer_manager.get_status(printer_id)
  2127. if not state:
  2128. return {"inventory_remain_g": {}, "slot_materials": []}
  2129. scheduler = PrintScheduler()
  2130. loaded = scheduler._build_loaded_filaments(state)
  2131. overrides = await scheduler._build_inventory_remain_overrides(db, printer_id, loaded)
  2132. slot_materials = await build_slot_materials(db, printer_id)
  2133. return {
  2134. "inventory_remain_g": {str(k): v for k, v in overrides.items()},
  2135. "slot_materials": [s.to_dict() for s in slot_materials],
  2136. }
  2137. # ============================================
  2138. # Calibration
  2139. # ============================================
  2140. @router.post("/{printer_id}/calibration")
  2141. async def start_calibration(
  2142. printer_id: int,
  2143. bed_leveling: bool = False,
  2144. vibration: bool = False,
  2145. motor_noise: bool = False,
  2146. nozzle_offset: bool = False,
  2147. high_temp_heatbed: bool = False,
  2148. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  2149. db: AsyncSession = Depends(get_db),
  2150. ):
  2151. """Start printer calibration with selected options.
  2152. At least one option must be selected.
  2153. Options:
  2154. - bed_leveling: Run bed leveling calibration
  2155. - vibration: Run vibration compensation calibration
  2156. - motor_noise: Run motor noise cancellation calibration
  2157. - nozzle_offset: Run nozzle offset calibration (dual nozzle printers)
  2158. - high_temp_heatbed: Run high-temperature heatbed calibration
  2159. """
  2160. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2161. printer = result.scalar_one_or_none()
  2162. if not printer:
  2163. raise HTTPException(404, "Printer not found")
  2164. client = printer_manager.get_client(printer_id)
  2165. if not client or not client.state.connected:
  2166. raise HTTPException(400, "Printer not connected")
  2167. # Check that at least one option is selected
  2168. if not any([bed_leveling, vibration, motor_noise, nozzle_offset, high_temp_heatbed]):
  2169. raise HTTPException(400, "At least one calibration option must be selected")
  2170. success = client.start_calibration(
  2171. bed_leveling=bed_leveling,
  2172. vibration=vibration,
  2173. motor_noise=motor_noise,
  2174. nozzle_offset=nozzle_offset,
  2175. high_temp_heatbed=high_temp_heatbed,
  2176. )
  2177. if not success:
  2178. raise HTTPException(500, "Failed to send calibration command to printer")
  2179. return {
  2180. "success": True,
  2181. "bed_leveling": bed_leveling,
  2182. "vibration": vibration,
  2183. "motor_noise": motor_noise,
  2184. "nozzle_offset": nozzle_offset,
  2185. "high_temp_heatbed": high_temp_heatbed,
  2186. }
  2187. # ============================================================================
  2188. # Slot Preset Mapping Endpoints
  2189. # ============================================================================
  2190. def _slot_preset_key(ams_id: int, tray_id: int) -> int:
  2191. # Mirrors frontend getGlobalTrayId (amsHelpers.ts): AMS-HT (128-135) is keyed
  2192. # by ams_id since each unit has a single slot and shares its global ID with
  2193. # the unit itself. Regular AMS and external (255) use ams_id*4+tray_id.
  2194. if 128 <= ams_id <= 135:
  2195. return ams_id
  2196. return ams_id * 4 + tray_id
  2197. @router.get("/{printer_id}/slot-presets")
  2198. async def get_slot_presets(
  2199. printer_id: int,
  2200. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  2201. db: AsyncSession = Depends(get_db),
  2202. ):
  2203. """Get all saved slot-to-preset mappings for a printer."""
  2204. result = await db.execute(select(SlotPresetMapping).where(SlotPresetMapping.printer_id == printer_id))
  2205. mappings = result.scalars().all()
  2206. return {
  2207. _slot_preset_key(mapping.ams_id, mapping.tray_id): {
  2208. "ams_id": mapping.ams_id,
  2209. "tray_id": mapping.tray_id,
  2210. "preset_id": mapping.preset_id,
  2211. "preset_name": mapping.preset_name,
  2212. }
  2213. for mapping in mappings
  2214. }
  2215. @router.get("/{printer_id}/slot-presets/{ams_id}/{tray_id}")
  2216. async def get_slot_preset(
  2217. printer_id: int,
  2218. ams_id: int,
  2219. tray_id: int,
  2220. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  2221. db: AsyncSession = Depends(get_db),
  2222. ):
  2223. """Get the saved preset for a specific slot."""
  2224. result = await db.execute(
  2225. select(SlotPresetMapping).where(
  2226. SlotPresetMapping.printer_id == printer_id,
  2227. SlotPresetMapping.ams_id == ams_id,
  2228. SlotPresetMapping.tray_id == tray_id,
  2229. )
  2230. )
  2231. mapping = result.scalar_one_or_none()
  2232. if not mapping:
  2233. return None
  2234. return {
  2235. "ams_id": mapping.ams_id,
  2236. "tray_id": mapping.tray_id,
  2237. "preset_id": mapping.preset_id,
  2238. "preset_name": mapping.preset_name,
  2239. }
  2240. @router.put("/{printer_id}/slot-presets/{ams_id}/{tray_id}")
  2241. async def save_slot_preset(
  2242. printer_id: int,
  2243. ams_id: int,
  2244. tray_id: int,
  2245. preset_id: str,
  2246. preset_name: str,
  2247. preset_source: str = "cloud",
  2248. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_UPDATE),
  2249. db: AsyncSession = Depends(get_db),
  2250. ):
  2251. """Save a preset mapping for a specific slot."""
  2252. # Check printer exists
  2253. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2254. if not result.scalar_one_or_none():
  2255. raise HTTPException(404, "Printer not found")
  2256. # Check for existing mapping
  2257. result = await db.execute(
  2258. select(SlotPresetMapping).where(
  2259. SlotPresetMapping.printer_id == printer_id,
  2260. SlotPresetMapping.ams_id == ams_id,
  2261. SlotPresetMapping.tray_id == tray_id,
  2262. )
  2263. )
  2264. mapping = result.scalar_one_or_none()
  2265. if mapping:
  2266. # Update existing
  2267. mapping.preset_id = preset_id
  2268. mapping.preset_name = preset_name
  2269. mapping.preset_source = preset_source
  2270. else:
  2271. # Create new
  2272. mapping = SlotPresetMapping(
  2273. printer_id=printer_id,
  2274. ams_id=ams_id,
  2275. tray_id=tray_id,
  2276. preset_id=preset_id,
  2277. preset_name=preset_name,
  2278. preset_source=preset_source,
  2279. )
  2280. db.add(mapping)
  2281. await db.commit()
  2282. await db.refresh(mapping)
  2283. return {
  2284. "ams_id": mapping.ams_id,
  2285. "tray_id": mapping.tray_id,
  2286. "preset_id": mapping.preset_id,
  2287. "preset_name": mapping.preset_name,
  2288. "preset_source": mapping.preset_source,
  2289. }
  2290. @router.delete("/{printer_id}/slot-presets/{ams_id}/{tray_id}")
  2291. async def delete_slot_preset(
  2292. printer_id: int,
  2293. ams_id: int,
  2294. tray_id: int,
  2295. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_UPDATE),
  2296. db: AsyncSession = Depends(get_db),
  2297. ):
  2298. """Delete a saved preset mapping for a slot."""
  2299. result = await db.execute(
  2300. select(SlotPresetMapping).where(
  2301. SlotPresetMapping.printer_id == printer_id,
  2302. SlotPresetMapping.ams_id == ams_id,
  2303. SlotPresetMapping.tray_id == tray_id,
  2304. )
  2305. )
  2306. mapping = result.scalar_one_or_none()
  2307. if mapping:
  2308. await db.delete(mapping)
  2309. await db.commit()
  2310. return {"success": True}
  2311. @router.get("/{printer_id}/slots/{ams_id}/{tray_id}/spool-defaults")
  2312. async def get_slot_spool_defaults(
  2313. printer_id: int,
  2314. ams_id: int,
  2315. tray_id: int,
  2316. db: AsyncSession = Depends(get_db),
  2317. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  2318. ):
  2319. """What the spool assigned to this slot is configured to use here.
  2320. The Configure AMS Slot dialog opens on a slot that usually already holds an
  2321. assigned spool, and that spool carries a filament preset per printer model
  2322. and a K profile per hotend. Without this the dialog offered defaults derived
  2323. from the slot's last manual configuration or from the tray's RFID data --
  2324. ignoring the very values the spool was configured with, on the one screen
  2325. that looks like it exists for them.
  2326. Everything is resolved for the nozzle THIS slot feeds, so a dual-nozzle
  2327. machine gets the answer for the correct hotend. Returns nulls rather than a
  2328. 404 when the slot holds no known spool: "nothing configured" is an ordinary
  2329. answer here and the dialog falls back to what it did before.
  2330. """
  2331. from backend.app.models.spool import Spool
  2332. from backend.app.models.spool_assignment import SpoolAssignment
  2333. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2334. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2335. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  2336. from backend.app.services.slot_nozzle import resolve_slot_nozzle
  2337. from backend.app.services.spool_filament_preset import resolve_spool_preset, resolve_spoolman_preset
  2338. state = printer_manager.get_status(printer_id)
  2339. model = printer_manager.get_model(printer_id)
  2340. slot_nozzle = resolve_slot_nozzle(state, ams_id, tray_id, model)
  2341. profile = await find_slot_kprofile_for_extruder(
  2342. db,
  2343. printer_id,
  2344. ams_id,
  2345. tray_id,
  2346. slot_nozzle.extruder_or_default,
  2347. slot_nozzle.diameter,
  2348. model,
  2349. slot_nozzle.flow,
  2350. )
  2351. slicer_filament: str | None = None
  2352. slicer_filament_name: str | None = None
  2353. spoolman_mode = await spoolman_owns_assignments(db)
  2354. if spoolman_mode:
  2355. sm_assignment = (
  2356. await db.execute(
  2357. select(SpoolmanSlotAssignment).where(
  2358. SpoolmanSlotAssignment.printer_id == printer_id,
  2359. SpoolmanSlotAssignment.ams_id == ams_id,
  2360. SpoolmanSlotAssignment.tray_id == tray_id,
  2361. )
  2362. )
  2363. ).scalar_one_or_none()
  2364. if sm_assignment is not None:
  2365. slicer_filament, slicer_filament_name = await resolve_spoolman_preset(
  2366. db,
  2367. spoolman_spool_id=sm_assignment.spoolman_spool_id,
  2368. printer_model=model,
  2369. nozzle_diameter=slot_nozzle.diameter,
  2370. fallback_filament=None,
  2371. fallback_name=None,
  2372. )
  2373. else:
  2374. assignment = (
  2375. await db.execute(
  2376. select(SpoolAssignment).where(
  2377. SpoolAssignment.printer_id == printer_id,
  2378. SpoolAssignment.ams_id == ams_id,
  2379. SpoolAssignment.tray_id == tray_id,
  2380. )
  2381. )
  2382. ).scalar_one_or_none()
  2383. if assignment is not None:
  2384. spool = (await db.execute(select(Spool).where(Spool.id == assignment.spool_id))).scalar_one_or_none()
  2385. if spool is not None:
  2386. slicer_filament, slicer_filament_name = await resolve_spool_preset(
  2387. db,
  2388. spool_id=spool.id,
  2389. printer_model=model,
  2390. nozzle_diameter=slot_nozzle.diameter,
  2391. fallback_filament=spool.slicer_filament,
  2392. fallback_name=spool.slicer_filament_name,
  2393. )
  2394. return {
  2395. "slicer_filament": slicer_filament,
  2396. "slicer_filament_name": slicer_filament_name,
  2397. "cali_idx": profile.cali_idx if profile else None,
  2398. "k_value": profile.k_value if profile else None,
  2399. "profile_name": profile.name if profile else None,
  2400. "extruder": slot_nozzle.extruder,
  2401. "nozzle_diameter": slot_nozzle.diameter,
  2402. }
  2403. @router.post("/{printer_id}/slots/{ams_id}/{tray_id}/configure")
  2404. async def configure_ams_slot(
  2405. printer_id: int,
  2406. ams_id: int,
  2407. tray_id: int,
  2408. tray_info_idx: str = Query(...),
  2409. tray_type: str = Query(...),
  2410. tray_sub_brands: str = Query(...),
  2411. tray_color: str = Query(...),
  2412. nozzle_temp_min: int = Query(...),
  2413. nozzle_temp_max: int = Query(...),
  2414. cali_idx: int = Query(-1),
  2415. nozzle_diameter: str = Query("0.4"),
  2416. setting_id: str = Query(""),
  2417. kprofile_filament_id: str = Query(""),
  2418. kprofile_setting_id: str = Query(""),
  2419. k_value: float = Query(0.0),
  2420. db: AsyncSession = Depends(get_db),
  2421. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  2422. ):
  2423. """Configure an AMS slot with a specific filament setting and K profile.
  2424. This sends two commands to the printer:
  2425. 1. ams_filament_setting - sets filament type, color, temperature
  2426. 2. extrusion_cali_sel - sets the K profile (pressure advance value)
  2427. Args:
  2428. printer_id: Database ID of the printer
  2429. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  2430. tray_id: Tray ID within the AMS (0-3)
  2431. tray_info_idx: Filament ID short format (e.g., "GFL05") or user preset ID
  2432. tray_type: Filament type (e.g., "PLA", "PETG")
  2433. tray_sub_brands: Sub-brand/profile name (e.g., "PLA Basic", "PETG HF")
  2434. tray_color: Color in RRGGBBAA hex format (e.g., "FFFF00FF")
  2435. nozzle_temp_min: Minimum nozzle temperature
  2436. nozzle_temp_max: Maximum nozzle temperature
  2437. cali_idx: K profile calibration index (-1 for default 0.020)
  2438. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  2439. setting_id: Full setting ID with version (e.g., "GFSL05_07") - optional
  2440. kprofile_filament_id: K profile's filament_id for proper K profile linking
  2441. k_value: Direct K value to set (0.0 to skip direct K value setting)
  2442. """
  2443. logger = logging.getLogger(__name__)
  2444. logger.info("[configure_ams_slot] printer_id=%s, ams_id=%s, tray_id=%s", printer_id, ams_id, tray_id)
  2445. logger.info(
  2446. f"[configure_ams_slot] tray_info_idx={tray_info_idx!r}, tray_type={tray_type!r}, tray_sub_brands={tray_sub_brands!r}"
  2447. )
  2448. logger.info(
  2449. f"[configure_ams_slot] setting_id={setting_id!r}, kprofile_filament_id={kprofile_filament_id!r}, kprofile_setting_id={kprofile_setting_id!r}"
  2450. )
  2451. # The modal derives tray_type from a preset name or a spool's material, so
  2452. # it can be a product line rather than a type ("PLA+", "PolyTerra PLA").
  2453. # A slot carrying one of those satisfies nothing that asks for PLA, so the
  2454. # slot gets the type and tray_sub_brands -- untouched here -- keeps the
  2455. # name (issue #2902). The requested wording is kept for the id lookup
  2456. # below, which knows some product lines the type table does not.
  2457. requested_tray_type = tray_type
  2458. tray_type = printer_filament_type(tray_type)
  2459. if tray_type != requested_tray_type:
  2460. logger.info("[configure_ams_slot] tray_type %r → %r", requested_tray_type, tray_type)
  2461. # Get MQTT client for this printer
  2462. client = printer_manager.get_client(printer_id)
  2463. if not client:
  2464. raise HTTPException(status_code=400, detail="Printer not connected")
  2465. # Resolve tray_info_idx for the MQTT command.
  2466. # Priority:
  2467. # 1. Use the provided tray_info_idx if set (including cloud-synced
  2468. # custom presets like PFUS* / P*).
  2469. # 2. Reuse the slot's existing tray_info_idx if it's a specific
  2470. # (non-generic) preset for the same material.
  2471. # 3. Fall back to a generic Bambu filament ID.
  2472. _GENERIC_FILAMENT_IDS = {
  2473. "PLA": "GFL99",
  2474. "PETG": "GFG99",
  2475. "ABS": "GFB99",
  2476. "ASA": "GFB98",
  2477. "PC": "GFC99",
  2478. "PA": "GFN99",
  2479. "NYLON": "GFN99",
  2480. "TPU": "GFU99",
  2481. "PVA": "GFS99",
  2482. "HIPS": "GFS98",
  2483. "PLA-CF": "GFL98",
  2484. "PETG-CF": "GFG98",
  2485. "PA-CF": "GFN98",
  2486. "PETG HF": "GFG96",
  2487. }
  2488. _GENERIC_ID_VALUES = set(_GENERIC_FILAMENT_IDS.values())
  2489. effective_tray_info_idx = tray_info_idx
  2490. if not tray_info_idx:
  2491. # No preset provided — try slot reuse or generic fallback
  2492. current_tray_info_idx = ""
  2493. current_tray_type = ""
  2494. state = printer_manager.get_status(printer_id)
  2495. if state and state.raw_data:
  2496. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  2497. if ams_id == 255:
  2498. vt_tray = state.raw_data.get("vt_tray") or []
  2499. ext_id = tray_id + 254
  2500. for vt in vt_tray:
  2501. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  2502. current_tray_info_idx = vt.get("tray_info_idx", "")
  2503. current_tray_type = vt.get("tray_type", "")
  2504. break
  2505. else:
  2506. ams_data = state.raw_data.get("ams", {})
  2507. ams_list = (
  2508. ams_data.get("ams", [])
  2509. if isinstance(ams_data, dict)
  2510. else ams_data
  2511. if isinstance(ams_data, list)
  2512. else []
  2513. )
  2514. cur_tray = _find_tray_in_ams_data(ams_list, ams_id, tray_id)
  2515. if cur_tray:
  2516. current_tray_info_idx = cur_tray.get("tray_info_idx", "")
  2517. current_tray_type = cur_tray.get("tray_type", "")
  2518. if (
  2519. current_tray_info_idx
  2520. and current_tray_info_idx not in _GENERIC_ID_VALUES
  2521. and current_tray_type
  2522. and current_tray_type.upper() == tray_type.upper()
  2523. ):
  2524. logger.info(
  2525. "[configure_ams_slot] Reusing slot's existing tray_info_idx=%r (same material %r)",
  2526. current_tray_info_idx,
  2527. tray_type,
  2528. )
  2529. effective_tray_info_idx = current_tray_info_idx
  2530. elif tray_type:
  2531. # Requested wording first, reduced type only as a further fallback,
  2532. # so a material that already resolves keeps resolving to the same
  2533. # id: "PETG HF" has its own generic preset (GFG96) that reducing it
  2534. # to "PETG" would trade away for GFG99.
  2535. material = requested_tray_type.upper().strip()
  2536. generic = (
  2537. _GENERIC_FILAMENT_IDS.get(material)
  2538. or _GENERIC_FILAMENT_IDS.get(material.split("-")[0].split(" ")[0])
  2539. or _GENERIC_FILAMENT_IDS.get(tray_type.upper())
  2540. or ""
  2541. )
  2542. if generic:
  2543. logger.info("[configure_ams_slot] Falling back to generic %r for material %r", generic, tray_type)
  2544. effective_tray_info_idx = generic
  2545. # Send filament setting + K-profile commands
  2546. filament_id_for_kprofile = kprofile_filament_id if kprofile_filament_id else effective_tray_info_idx
  2547. # Realign the slot's filament context to the K-profile's calibration
  2548. # context. The printer's calibration table is keyed by (filament_id,
  2549. # cali_idx) — so for the cali_idx selected via extrusion_cali_sel to
  2550. # actually stick to the slot, ams_filament_setting must declare the
  2551. # slot under the SAME filament_id.
  2552. #
  2553. # Without this, configure_ams_slot would send:
  2554. # ams_filament_setting → tray_info_idx=GFL99 (generic from material)
  2555. # extrusion_cali_sel → filament_id=P4d64437 (kp's preset)
  2556. # ...and the cali_idx would silently be dropped to default because the
  2557. # slot's filament context (GFL99) doesn't match the kp's (P4d64437).
  2558. #
  2559. # This realignment fires only when the kp is targeted at a different
  2560. # preset than the user's filament selection AND the kp's preset is a
  2561. # valid tray_info_idx (GF* official, P* local — not PFUS* cloud-user
  2562. # which the slicer rejects in tray_info_idx).
  2563. effective_setting_id = setting_id
  2564. if (
  2565. kprofile_filament_id
  2566. and kprofile_filament_id != effective_tray_info_idx
  2567. and not kprofile_filament_id.startswith("PFUS")
  2568. ):
  2569. logger.info(
  2570. "[configure_ams_slot] realigning slot filament context to kp: tray_info_idx %r → %r, setting_id %r → %r",
  2571. effective_tray_info_idx,
  2572. kprofile_filament_id,
  2573. setting_id,
  2574. kprofile_setting_id or setting_id,
  2575. )
  2576. effective_tray_info_idx = kprofile_filament_id
  2577. if kprofile_setting_id:
  2578. effective_setting_id = kprofile_setting_id
  2579. # Back-fill setting_id from the resolved filament id when the client sent
  2580. # none. Built-in / local / Orca-generic presets in the Configure AMS Slot
  2581. # modal leave setting_id empty (they carry only a GF* tray_info_idx), and
  2582. # the printer treats a filament-id-without-setting-id slot as half
  2583. # configured: it shows the new material briefly, then reverts to its
  2584. # previously stored profile (#2604). This mirrors the derivation the
  2585. # inventory/assignment path already does (inventory.py). filament_id_to_
  2586. # setting_id leaves P* user presets and already-GFS* values unchanged, so
  2587. # only the empty-setting_id generic paths are affected.
  2588. if effective_tray_info_idx and not effective_setting_id:
  2589. effective_setting_id = filament_id_to_setting_id(effective_tray_info_idx)
  2590. # Always send ams_set_filament_setting — the user explicitly clicked
  2591. # "Configure Slot", so honor that. Previous versions skipped this for
  2592. # RFID-tagged slots to preserve the slicer eye icon, but printers cache
  2593. # stale tag_uid/tray_uuid after a BL spool is removed, causing the check
  2594. # to false-positive on non-RFID slots and silently drop the command.
  2595. success = client.ams_set_filament_setting(
  2596. ams_id=ams_id,
  2597. tray_id=tray_id,
  2598. tray_info_idx=effective_tray_info_idx,
  2599. tray_type=tray_type,
  2600. tray_sub_brands=tray_sub_brands,
  2601. tray_color=tray_color,
  2602. nozzle_temp_min=nozzle_temp_min,
  2603. nozzle_temp_max=nozzle_temp_max,
  2604. setting_id=effective_setting_id,
  2605. )
  2606. if not success:
  2607. raise HTTPException(status_code=500, detail="Failed to send filament configuration command")
  2608. # Method 1: Select existing calibration profile by cali_idx
  2609. # Do NOT include setting_id — BambuStudio never sends it in extrusion_cali_sel,
  2610. # and including it causes the firmware to mislink the profile on X1C/P1S.
  2611. client.extrusion_cali_sel(
  2612. ams_id=ams_id,
  2613. tray_id=tray_id,
  2614. cali_idx=cali_idx,
  2615. filament_id=filament_id_for_kprofile,
  2616. nozzle_diameter=nozzle_diameter,
  2617. )
  2618. # Method 2: Only send extrusion_cali_set when NO existing profile was selected
  2619. # (cali_idx == -1). When cali_idx >= 0, extrusion_cali_sel already selected the
  2620. # correct profile. Sending extrusion_cali_set with the same cali_idx would MODIFY
  2621. # the existing profile's metadata (extruder_id, nozzle_id, name, setting_id),
  2622. # corrupting it — e.g., overwriting a High Flow extruder 1 profile with
  2623. # hardcoded extruder_id=0 and nozzle_id=HS00.
  2624. if k_value > 0 and cali_idx < 0:
  2625. # Calculate global tray ID for extrusion_cali_set
  2626. if ams_id <= 3:
  2627. global_tray_id = ams_id * 4 + tray_id
  2628. elif ams_id >= 128 and ams_id <= 135:
  2629. global_tray_id = (ams_id - 128) * 4 + tray_id
  2630. else:
  2631. global_tray_id = tray_id
  2632. client.extrusion_cali_set(
  2633. tray_id=global_tray_id,
  2634. k_value=k_value,
  2635. nozzle_diameter=nozzle_diameter,
  2636. nozzle_temp=nozzle_temp_max,
  2637. filament_id=filament_id_for_kprofile,
  2638. setting_id=kprofile_setting_id or "",
  2639. name=tray_sub_brands or "",
  2640. cali_idx=cali_idx,
  2641. )
  2642. # Persist the user's K-profile choice so it survives RFID re-reads and
  2643. # session restarts. Pre-Phase-13 this was ephemeral — the MQTT command
  2644. # took effect on the printer but bambuddy never recorded it, so the next
  2645. # `_apply_pa_after_refresh` cycle had no stored profile to re-assert.
  2646. if cali_idx >= 0:
  2647. try:
  2648. from sqlalchemy.orm import selectinload
  2649. from backend.app.models.spool_assignment import SpoolAssignment
  2650. from backend.app.models.spool_k_profile import SpoolKProfile
  2651. from backend.app.models.spoolman_k_profile import SpoolmanKProfile
  2652. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2653. # Resolve the slot's extruder for the K-profile match key. On a
  2654. # Filament Track Switch machine this comes from the AMS's inlet
  2655. # binding, because every unit reports extruder 0xE there — without
  2656. # that, the `else 0` below filed every profile under the right-hand
  2657. # nozzle and a left-nozzle calibration was stored as a right one.
  2658. slot_state = printer_manager.get_status(printer_id)
  2659. resolved_extruder = slot_extruder(
  2660. ams_id,
  2661. tray_id,
  2662. slot_state.ams_extruder_map if slot_state else None,
  2663. slot_state.ams_switch_inlet if slot_state else None,
  2664. )
  2665. # Still 0 when nothing is known, which is right for a single-nozzle
  2666. # printer — the resolver only returns None when it genuinely cannot
  2667. # tell, and on those machines extruder 0 is the only one there is.
  2668. kp_extruder = resolved_extruder if resolved_extruder is not None else 0
  2669. # Only the active mode's assignment table decides where this
  2670. # K-profile is stored. Reading Spoolman first and falling through
  2671. # was safe while the inactive table was emptied on every mode
  2672. # toggle; nothing is emptied since #2812, so a leftover Spoolman
  2673. # row in built-in mode would file the calibration against a spool
  2674. # the printer is not using and never write the local profile —
  2675. # the calibration would appear to succeed and then not apply.
  2676. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2677. spoolman_mode = await spoolman_owns_assignments(db)
  2678. sm_assignment = None
  2679. if spoolman_mode:
  2680. # Spoolman SlotAssignment — has UniqueConstraint, idempotent.
  2681. sm_result = await db.execute(
  2682. select(SpoolmanSlotAssignment).where(
  2683. SpoolmanSlotAssignment.printer_id == printer_id,
  2684. SpoolmanSlotAssignment.ams_id == ams_id,
  2685. SpoolmanSlotAssignment.tray_id == tray_id,
  2686. )
  2687. )
  2688. sm_assignment = sm_result.scalar_one_or_none()
  2689. if sm_assignment:
  2690. existing = await db.execute(
  2691. select(SpoolmanKProfile).where(
  2692. SpoolmanKProfile.spoolman_spool_id == sm_assignment.spoolman_spool_id,
  2693. SpoolmanKProfile.printer_id == printer_id,
  2694. SpoolmanKProfile.extruder == kp_extruder,
  2695. SpoolmanKProfile.nozzle_diameter == nozzle_diameter,
  2696. )
  2697. )
  2698. kp = existing.scalar_one_or_none()
  2699. if kp:
  2700. kp.cali_idx = cali_idx
  2701. kp.k_value = k_value or 0.0
  2702. kp.setting_id = kprofile_setting_id or None
  2703. kp.name = tray_sub_brands or None
  2704. else:
  2705. db.add(
  2706. SpoolmanKProfile(
  2707. spoolman_spool_id=sm_assignment.spoolman_spool_id,
  2708. printer_id=printer_id,
  2709. extruder=kp_extruder,
  2710. nozzle_diameter=nozzle_diameter,
  2711. k_value=k_value or 0.0,
  2712. name=tray_sub_brands or None,
  2713. cali_idx=cali_idx,
  2714. setting_id=kprofile_setting_id or None,
  2715. )
  2716. )
  2717. await db.commit()
  2718. logger.info(
  2719. "[configure_ams_slot] Persisted Spoolman K-profile spool=%d printer=%d ams=%d tray=%d cali_idx=%d",
  2720. sm_assignment.spoolman_spool_id,
  2721. printer_id,
  2722. ams_id,
  2723. tray_id,
  2724. cali_idx,
  2725. )
  2726. elif not spoolman_mode:
  2727. # Local SpoolAssignment + SpoolKProfile (no UNIQUE — use .first()).
  2728. # Skipped in Spoolman mode even when a local row survives: the
  2729. # profile would be filed against a spool this printer is not
  2730. # drawing on, and the mode's own table has nothing to bind to.
  2731. local_result = await db.execute(
  2732. select(SpoolAssignment)
  2733. .options(selectinload(SpoolAssignment.spool))
  2734. .where(
  2735. SpoolAssignment.printer_id == printer_id,
  2736. SpoolAssignment.ams_id == ams_id,
  2737. SpoolAssignment.tray_id == tray_id,
  2738. )
  2739. )
  2740. local_assignment = local_result.scalar_one_or_none()
  2741. if local_assignment and local_assignment.spool:
  2742. existing = await db.execute(
  2743. select(SpoolKProfile).where(
  2744. SpoolKProfile.spool_id == local_assignment.spool.id,
  2745. SpoolKProfile.printer_id == printer_id,
  2746. SpoolKProfile.extruder == kp_extruder,
  2747. SpoolKProfile.nozzle_diameter == nozzle_diameter,
  2748. )
  2749. )
  2750. # SpoolKProfile has no unique constraint on this tuple, so
  2751. # multiple rows could theoretically exist (shouldn't, but
  2752. # don't crash if they do). Update the first match, leave
  2753. # any duplicates alone.
  2754. kp = existing.scalars().first()
  2755. if kp:
  2756. kp.cali_idx = cali_idx
  2757. kp.k_value = k_value or 0.0
  2758. kp.setting_id = kprofile_setting_id or None
  2759. kp.name = tray_sub_brands or None
  2760. else:
  2761. db.add(
  2762. SpoolKProfile(
  2763. spool_id=local_assignment.spool.id,
  2764. printer_id=printer_id,
  2765. extruder=kp_extruder,
  2766. nozzle_diameter=nozzle_diameter,
  2767. k_value=k_value or 0.0,
  2768. name=tray_sub_brands or None,
  2769. cali_idx=cali_idx,
  2770. setting_id=kprofile_setting_id or None,
  2771. )
  2772. )
  2773. await db.commit()
  2774. logger.info(
  2775. "[configure_ams_slot] Persisted local K-profile spool=%d printer=%d ams=%d tray=%d cali_idx=%d",
  2776. local_assignment.spool.id,
  2777. printer_id,
  2778. ams_id,
  2779. tray_id,
  2780. cali_idx,
  2781. )
  2782. except Exception:
  2783. # MQTT command was already sent successfully — DB persist is best-effort.
  2784. logger.exception(
  2785. "[configure_ams_slot] Failed to persist K-profile (printer=%d ams=%d tray=%d cali_idx=%d)",
  2786. printer_id,
  2787. ams_id,
  2788. tray_id,
  2789. cali_idx,
  2790. )
  2791. try:
  2792. await db.rollback()
  2793. except Exception:
  2794. pass
  2795. # Register a read-back verification (#2582) so the tray telemetry that the
  2796. # status push below returns can confirm the printer accepted this manual
  2797. # slot configuration. Mirrors the inventory/assignment path.
  2798. client.register_assignment_verification(
  2799. ams_id=ams_id,
  2800. tray_id=tray_id,
  2801. tray_info_idx=effective_tray_info_idx,
  2802. tray_color=tray_color,
  2803. cali_idx=cali_idx,
  2804. )
  2805. # Request fresh status push from printer so frontend gets updated data via WebSocket
  2806. logger.info("[configure_ams_slot] Requesting status update from printer")
  2807. update_result = client.request_status_update()
  2808. logger.info("[configure_ams_slot] Status update request result: %s", update_result)
  2809. return {
  2810. "success": True,
  2811. "message": f"Configured AMS {ams_id} tray {tray_id} with {tray_sub_brands}",
  2812. }
  2813. @router.post("/{printer_id}/ams/{ams_id}/tray/{tray_id}/reset")
  2814. async def reset_ams_slot(
  2815. printer_id: int,
  2816. ams_id: int,
  2817. tray_id: int,
  2818. db: AsyncSession = Depends(get_db),
  2819. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  2820. ):
  2821. """Reset an AMS slot to empty/unconfigured state.
  2822. This clears the filament configuration from the slot.
  2823. """
  2824. # Get MQTT client for this printer
  2825. client = printer_manager.get_client(printer_id)
  2826. if not client:
  2827. raise HTTPException(status_code=400, detail="Printer not connected")
  2828. # Reset the slot
  2829. success = client.reset_ams_slot(ams_id=ams_id, tray_id=tray_id)
  2830. if not success:
  2831. raise HTTPException(status_code=500, detail="Failed to send reset command")
  2832. # Also delete any saved slot preset mapping
  2833. result = await db.execute(
  2834. select(SlotPresetMapping).where(
  2835. SlotPresetMapping.printer_id == printer_id,
  2836. SlotPresetMapping.ams_id == ams_id,
  2837. SlotPresetMapping.tray_id == tray_id,
  2838. )
  2839. )
  2840. mapping = result.scalar_one_or_none()
  2841. if mapping:
  2842. await db.delete(mapping)
  2843. await db.commit()
  2844. # Request fresh status push from printer so frontend gets updated data via WebSocket
  2845. client.request_status_update()
  2846. return {
  2847. "success": True,
  2848. "message": f"Reset AMS {ams_id} tray {tray_id}",
  2849. }
  2850. @router.get("/{printer_id}/ams-labels")
  2851. async def get_ams_labels(
  2852. printer_id: int,
  2853. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  2854. db: AsyncSession = Depends(get_db),
  2855. ):
  2856. """Get all user-defined AMS labels for a printer, keyed by AMS unit ID.
  2857. Labels are stored by AMS serial number. This endpoint resolves the current
  2858. serial-to-ams_id mapping from the live printer state so the response is still
  2859. keyed by ams_id for UI compatibility.
  2860. """
  2861. # Build serial -> ams_id map from live printer state
  2862. serial_to_ams_id: dict[str, int] = {}
  2863. state = printer_manager.get_status(printer_id)
  2864. if state and state.raw_data:
  2865. for ams_unit in state.raw_data.get("ams", []):
  2866. sn = str(ams_unit.get("sn") or ams_unit.get("serial_number") or "")
  2867. if sn:
  2868. serial_to_ams_id[sn] = int(ams_unit.get("id", 0))
  2869. # Collect all known serials for this printer (live + synthetic fallback keys)
  2870. serials_to_query = set(serial_to_ams_id.keys())
  2871. # Fetch labels for all known serials
  2872. labels: dict[int, str] = {}
  2873. if serials_to_query:
  2874. result = await db.execute(select(AmsLabel).where(AmsLabel.ams_serial_number.in_(serials_to_query)))
  2875. for lbl in result.scalars().all():
  2876. aid = serial_to_ams_id.get(lbl.ams_serial_number)
  2877. if aid is not None:
  2878. labels[aid] = lbl.label
  2879. # Also fetch labels stored under synthetic keys for this printer (backward compat)
  2880. # Collect all synthetic keys first, then query with a single IN clause.
  2881. if state and state.raw_data:
  2882. synthetic_key_to_aid: dict[str, int] = {
  2883. f"p{printer_id}a{int(ams_unit.get('id', 0))}": int(ams_unit.get("id", 0))
  2884. for ams_unit in state.raw_data.get("ams", [])
  2885. if int(ams_unit.get("id", 0)) not in labels
  2886. }
  2887. if synthetic_key_to_aid:
  2888. result = await db.execute(
  2889. select(AmsLabel).where(AmsLabel.ams_serial_number.in_(synthetic_key_to_aid.keys()))
  2890. )
  2891. for lbl in result.scalars().all():
  2892. aid = synthetic_key_to_aid.get(lbl.ams_serial_number)
  2893. if aid is not None:
  2894. labels[aid] = lbl.label
  2895. return labels
  2896. @router.put("/{printer_id}/ams-labels/{ams_id}")
  2897. async def save_ams_label(
  2898. printer_id: int,
  2899. ams_id: int,
  2900. body: AmsLabelBody,
  2901. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_UPDATE),
  2902. db: AsyncSession = Depends(get_db),
  2903. ):
  2904. """Create or update the friendly name for a specific AMS unit.
  2905. When ``ams_serial`` is provided the label is stored under that serial number so
  2906. it survives the AMS being moved to a different printer. When it is absent (e.g.
  2907. older firmware that does not report a serial) a synthetic key based on the
  2908. printer_id and ams_id is used as a fallback.
  2909. """
  2910. # Verify printer exists
  2911. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2912. if not result.scalar_one_or_none():
  2913. raise HTTPException(404, "Printer not found")
  2914. # Determine the serial key to store under
  2915. stripped = body.ams_serial.strip() if body.ams_serial else ""
  2916. serial_key = stripped if stripped else f"p{printer_id}a{ams_id}"
  2917. result = await db.execute(select(AmsLabel).where(AmsLabel.ams_serial_number == serial_key))
  2918. existing = result.scalar_one_or_none()
  2919. if existing:
  2920. existing.label = body.label
  2921. existing.ams_id = ams_id
  2922. else:
  2923. db.add(AmsLabel(ams_serial_number=serial_key, ams_id=ams_id, label=body.label))
  2924. await db.commit()
  2925. return {"ams_id": ams_id, "label": body.label}
  2926. @router.delete("/{printer_id}/ams-labels/{ams_id}")
  2927. async def delete_ams_label(
  2928. printer_id: int,
  2929. ams_id: int,
  2930. ams_serial: str = Query(default="", max_length=50),
  2931. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_UPDATE),
  2932. db: AsyncSession = Depends(get_db),
  2933. ):
  2934. """Delete the friendly name for a specific AMS unit, reverting to the auto label."""
  2935. stripped = ams_serial.strip() if ams_serial else ""
  2936. serial_key = stripped if stripped else f"p{printer_id}a{ams_id}"
  2937. result = await db.execute(select(AmsLabel).where(AmsLabel.ams_serial_number == serial_key))
  2938. existing = result.scalar_one_or_none()
  2939. if existing:
  2940. await db.delete(existing)
  2941. await db.commit()
  2942. return {"success": True}
  2943. @router.post("/{printer_id}/debug/simulate-print-complete")
  2944. async def debug_simulate_print_complete(
  2945. printer_id: int,
  2946. db: AsyncSession = Depends(get_db),
  2947. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  2948. ):
  2949. """DEBUG: Simulate print completion to test freeze behavior.
  2950. This triggers the same code path as a real print completion,
  2951. without needing to wait for an actual print to finish.
  2952. """
  2953. from backend.app.main import _active_prints, on_print_complete
  2954. from backend.app.models.archive import PrintArchive
  2955. # Get the most recent archive for this printer
  2956. result = await db.execute(
  2957. select(PrintArchive)
  2958. .where(PrintArchive.printer_id == printer_id)
  2959. .order_by(PrintArchive.created_at.desc())
  2960. .limit(1)
  2961. )
  2962. archive = result.scalar_one_or_none()
  2963. if not archive:
  2964. raise HTTPException(status_code=404, detail="No archives found for this printer")
  2965. # Register this archive as "active" so on_print_complete can find it
  2966. filename = archive.file_path.split("/")[-1] if archive.file_path else "test.3mf"
  2967. subtask_name = archive.print_name or "Test Print"
  2968. _active_prints[(printer_id, filename)] = archive.id
  2969. _active_prints[(printer_id, subtask_name)] = archive.id
  2970. # Simulate print completion data
  2971. data = {
  2972. "status": "completed",
  2973. "filename": filename,
  2974. "subtask_name": subtask_name,
  2975. "timelapse_was_active": False,
  2976. }
  2977. logger.info("Simulating print complete for printer %s, archive %s", printer_id, archive.id)
  2978. # Call the actual on_print_complete handler
  2979. await on_print_complete(printer_id, data)
  2980. return {"success": True, "archive_id": archive.id, "message": "Print completion simulated"}
  2981. # =============================================================================
  2982. # Print Control Endpoints
  2983. # =============================================================================
  2984. @router.post("/{printer_id}/print/stop")
  2985. async def stop_print(
  2986. printer_id: int,
  2987. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  2988. db: AsyncSession = Depends(get_db),
  2989. ):
  2990. """Stop/cancel the current print job."""
  2991. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2992. printer = result.scalar_one_or_none()
  2993. if not printer:
  2994. raise HTTPException(404, "Printer not found")
  2995. client = printer_manager.get_client(printer_id)
  2996. if not client:
  2997. raise HTTPException(400, "Printer not connected")
  2998. success = client.stop_print()
  2999. if not success:
  3000. raise HTTPException(500, "Failed to stop print")
  3001. # Mark this printer as user-stopped so on_print_complete reclassifies
  3002. # the resulting "failed"/"aborted" MQTT status as "cancelled" — otherwise
  3003. # the HMS heuristic in _dispatch_archive_update mislabels user-cancels
  3004. # (e.g. the H2D's cancel-sequence module-0x0C HMS) as "Layer shift".
  3005. try:
  3006. from backend.app.main import mark_printer_stopped_by_user
  3007. mark_printer_stopped_by_user(printer_id)
  3008. except Exception as _mark_err:
  3009. logger.warning("Failed to mark printer %s as user-stopped: %s", printer_id, _mark_err)
  3010. return {"success": True, "message": "Print stop command sent"}
  3011. @router.post("/{printer_id}/clear-plate")
  3012. async def clear_plate(
  3013. printer_id: int,
  3014. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CLEAR_PLATE),
  3015. db: AsyncSession = Depends(get_db),
  3016. ):
  3017. """Acknowledge that the build plate has been cleared after a finished/failed print.
  3018. Sets a plate-cleared flag so the scheduler can start the next queued print.
  3019. No MQTT command is sent to the printer — the scheduler's start_print command
  3020. will override the FINISH/FAILED state when it sends the next job.
  3021. """
  3022. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3023. printer = result.scalar_one_or_none()
  3024. if not printer:
  3025. raise HTTPException(404, "Printer not found")
  3026. # Deliberately NOT gated on the printer being connected. Acknowledging the plate
  3027. # only mutates Bambuddy-side state — no MQTT command is sent — and with Auto Power
  3028. # Off the normal end-of-print state is exactly this: gate up, printer powered down.
  3029. # The guard this replaces was inherited from the sibling stop/pause/resume handlers,
  3030. # where reaching the printer IS required, and left farms with no way to release the
  3031. # gate short of powering each printer back on by hand (#2864).
  3032. # Accept the acknowledgment whenever the printer is awaiting it — not only when the
  3033. # reported state is FINISH/FAILED. After a power cycle the printer boots into IDLE
  3034. # but the awaiting flag persists, and the user still needs a way to ack it (#961).
  3035. state = printer_manager.get_status(printer_id)
  3036. awaiting = printer_manager.is_awaiting_plate_clear(printer_id)
  3037. if not awaiting and (not state or state.state not in ("FINISH", "FAILED")):
  3038. raise HTTPException(
  3039. 400,
  3040. f"Printer is not awaiting plate-clear acknowledgment (state={state.state if state else 'unknown'})",
  3041. )
  3042. printer_manager.set_awaiting_plate_clear(printer_id, False)
  3043. return {"success": True, "message": "Plate cleared, next print will start shortly"}
  3044. @router.post("/{printer_id}/print/pause")
  3045. async def pause_print(
  3046. printer_id: int,
  3047. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3048. db: AsyncSession = Depends(get_db),
  3049. ):
  3050. """Pause the current print job."""
  3051. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3052. printer = result.scalar_one_or_none()
  3053. if not printer:
  3054. raise HTTPException(404, "Printer not found")
  3055. client = printer_manager.get_client(printer_id)
  3056. if not client:
  3057. raise HTTPException(400, "Printer not connected")
  3058. success = client.pause_print()
  3059. if not success:
  3060. raise HTTPException(500, "Failed to pause print")
  3061. return {"success": True, "message": "Print pause command sent"}
  3062. @router.post("/{printer_id}/print/resume")
  3063. async def resume_print(
  3064. printer_id: int,
  3065. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3066. db: AsyncSession = Depends(get_db),
  3067. ):
  3068. """Resume a paused print job."""
  3069. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3070. printer = result.scalar_one_or_none()
  3071. if not printer:
  3072. raise HTTPException(404, "Printer not found")
  3073. client = printer_manager.get_client(printer_id)
  3074. if not client:
  3075. raise HTTPException(400, "Printer not connected")
  3076. success = client.resume_print()
  3077. if not success:
  3078. raise HTTPException(500, "Failed to resume print")
  3079. return {"success": True, "message": "Print resume command sent"}
  3080. @router.post("/{printer_id}/print-speed")
  3081. async def set_print_speed(
  3082. printer_id: int,
  3083. mode: int = Query(..., description="Speed mode (1=silent, 2=standard, 3=sport, 4=ludicrous)"),
  3084. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3085. db: AsyncSession = Depends(get_db),
  3086. ):
  3087. """Set the print speed mode."""
  3088. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3089. printer = result.scalar_one_or_none()
  3090. if not printer:
  3091. raise HTTPException(404, "Printer not found")
  3092. client = printer_manager.get_client(printer_id)
  3093. if not client:
  3094. raise HTTPException(400, "Printer not connected")
  3095. success = client.set_print_speed(mode)
  3096. if not success:
  3097. raise HTTPException(500, "Failed to set print speed")
  3098. speed_names = {1: "Silent", 2: "Standard", 3: "Sport", 4: "Ludicrous"}
  3099. return {"success": True, "message": f"Print speed set to {speed_names.get(mode, 'Unknown')}"}
  3100. @router.post("/{printer_id}/temperature/nozzle")
  3101. async def set_nozzle_temperature(
  3102. printer_id: int,
  3103. target: int = Query(..., ge=0, le=320, description="Target nozzle temperature in Celsius; 0 turns heating off"),
  3104. nozzle: int = Query(0, ge=0, le=1, description="Nozzle/extruder index (0=right/default, 1=left)"),
  3105. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3106. db: AsyncSession = Depends(get_db),
  3107. ):
  3108. """Set a nozzle target temperature."""
  3109. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3110. printer = result.scalar_one_or_none()
  3111. if not printer:
  3112. raise HTTPException(404, "Printer not found")
  3113. client = printer_manager.get_client(printer_id)
  3114. if not client:
  3115. raise HTTPException(400, "Printer not connected")
  3116. success = client.set_nozzle_temperature(target, nozzle)
  3117. if not success:
  3118. raise HTTPException(500, "Failed to set nozzle temperature")
  3119. return {"success": True, "message": f"Nozzle temperature set to {target}°C"}
  3120. @router.post("/{printer_id}/temperature/bed")
  3121. async def set_bed_temperature(
  3122. printer_id: int,
  3123. target: int = Query(..., ge=0, le=140, description="Target bed temperature in Celsius; 0 turns heating off"),
  3124. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3125. db: AsyncSession = Depends(get_db),
  3126. ):
  3127. """Set the bed target temperature."""
  3128. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3129. printer = result.scalar_one_or_none()
  3130. if not printer:
  3131. raise HTTPException(404, "Printer not found")
  3132. client = printer_manager.get_client(printer_id)
  3133. if not client:
  3134. raise HTTPException(400, "Printer not connected")
  3135. success = client.set_bed_temperature(target)
  3136. if not success:
  3137. raise HTTPException(500, "Failed to set bed temperature")
  3138. return {"success": True, "message": f"Bed temperature set to {target}°C"}
  3139. @router.post("/{printer_id}/temperature/chamber")
  3140. async def set_chamber_temperature(
  3141. printer_id: int,
  3142. target: int = Query(
  3143. ...,
  3144. ge=0,
  3145. le=MAX_CHAMBER_TEMP_C,
  3146. description="Target chamber temperature in Celsius; 0 turns heating off",
  3147. ),
  3148. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3149. db: AsyncSession = Depends(get_db),
  3150. ):
  3151. """Set the chamber target temperature.
  3152. Gated on `supports_chamber_heater(model)`: only H2C, H2D, H2D Pro, H2S,
  3153. and X2D have an active chamber heater. Sensor-only models (X1C, X1E,
  3154. P2S) report chamber temp but silently swallow M141, so we 400 here
  3155. rather than send a no-op.
  3156. """
  3157. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3158. printer = result.scalar_one_or_none()
  3159. if not printer:
  3160. raise HTTPException(404, "Printer not found")
  3161. if not supports_chamber_heater(printer.model):
  3162. raise HTTPException(400, f"Model {printer.model or 'unknown'} does not have an active chamber heater")
  3163. client = printer_manager.get_client(printer_id)
  3164. if not client:
  3165. raise HTTPException(400, "Printer not connected")
  3166. success = client.set_chamber_temperature(target)
  3167. if not success:
  3168. raise HTTPException(500, "Failed to set chamber temperature")
  3169. return {"success": True, "message": f"Chamber temperature set to {target}°C"}
  3170. @router.post("/{printer_id}/fan-speed")
  3171. async def set_fan_speed(
  3172. printer_id: int,
  3173. fan: str = Query(..., description="Fan to control: part, aux, aux2 (left aux), or chamber"),
  3174. speed: int = Query(..., ge=0, le=100, description="Fan speed percentage"),
  3175. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3176. db: AsyncSession = Depends(get_db),
  3177. ):
  3178. """Set a fan speed by percentage.
  3179. Fan index 10 ("aux2") is the optional left auxiliary part cooling fan on
  3180. P2S/X2D — driven with "M106 P10" exactly like Bambu's official machine
  3181. profile gcode does. It only exists when the printer reports airduct part 10,
  3182. so the request is rejected rather than sending M106 P10 into the void on a
  3183. machine that has no such fan.
  3184. That gate also rejects for the short window between connecting and the
  3185. first airduct push, when nothing is known about the fan yet. The card hides
  3186. the badge over the same window, so there is no control to click; a direct
  3187. API caller gets a 400 and should retry once the status reports the fan.
  3188. """
  3189. fan_ids = {"part": 1, "aux": 2, "chamber": 3, "aux2": 10}
  3190. fan_id = fan_ids.get(fan)
  3191. if fan_id is None:
  3192. raise HTTPException(400, "fan must be 'part', 'aux', 'aux2', or 'chamber'")
  3193. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3194. printer = result.scalar_one_or_none()
  3195. if not printer:
  3196. raise HTTPException(404, "Printer not found")
  3197. client = printer_manager.get_client(printer_id)
  3198. if not client:
  3199. raise HTTPException(400, "Printer not connected")
  3200. # Presence gate for the accessory fan. Without this, aux2 is accepted for
  3201. # every model and an A1 would be sent M106 P10 for a fan it does not have.
  3202. # The UI already hides the badge; this closes the same hole on the API.
  3203. if fan == "aux2" and getattr(client.state, "left_aux_fan_speed", None) is None:
  3204. raise HTTPException(
  3205. 400,
  3206. "This printer does not report a left auxiliary fan "
  3207. "(no airduct part 10). The fan is an accessory kit on the P2S "
  3208. "and factory-fitted on the X2D.",
  3209. )
  3210. pwm_speed = round(speed * 255 / 100)
  3211. success = client.set_fan_speed(fan_id, pwm_speed)
  3212. if not success:
  3213. raise HTTPException(500, "Failed to set fan speed")
  3214. # The enclosure fan is called "Exhaust" on P2S/X2D and "Chamber" elsewhere;
  3215. # match whatever the printer card badge shows so the toast agrees with the
  3216. # control the user just clicked.
  3217. fan_names = {
  3218. "part": "Part cooling fan",
  3219. "aux": "Auxiliary fan",
  3220. "aux2": "Left auxiliary fan",
  3221. "chamber": "Exhaust fan" if uses_exhaust_fan_label(printer.model) else "Chamber fan",
  3222. }
  3223. return {"success": True, "message": f"{fan_names[fan]} set to {speed}%"}
  3224. @router.post("/{printer_id}/select-extruder")
  3225. async def select_extruder(
  3226. printer_id: int,
  3227. extruder: int = Query(..., ge=0, le=1, description="Extruder index (0=right, 1=left)"),
  3228. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3229. db: AsyncSession = Depends(get_db),
  3230. ):
  3231. """Select the active extruder/nozzle on dual-nozzle printers."""
  3232. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3233. printer = result.scalar_one_or_none()
  3234. if not printer:
  3235. raise HTTPException(404, "Printer not found")
  3236. client = printer_manager.get_client(printer_id)
  3237. if not client:
  3238. raise HTTPException(400, "Printer not connected")
  3239. success = client.select_extruder(extruder)
  3240. if not success:
  3241. raise HTTPException(500, "Failed to select nozzle")
  3242. return {"success": True, "message": f"{'Left' if extruder == 1 else 'Right'} nozzle selected"}
  3243. @router.post("/{printer_id}/airduct-mode")
  3244. async def set_airduct_mode(
  3245. printer_id: int,
  3246. mode: str = Query(..., description="Airduct mode: 'cooling' or 'heating'"),
  3247. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3248. db: AsyncSession = Depends(get_db),
  3249. ):
  3250. """Set the airduct mode (cooling/heating) on supported printers (P2S/H2*)."""
  3251. if mode not in ("cooling", "heating"):
  3252. raise HTTPException(400, "Mode must be 'cooling' or 'heating'")
  3253. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3254. printer = result.scalar_one_or_none()
  3255. if not printer:
  3256. raise HTTPException(404, "Printer not found")
  3257. client = printer_manager.get_client(printer_id)
  3258. if not client:
  3259. raise HTTPException(400, "Printer not connected")
  3260. success = client.set_airduct_mode(mode)
  3261. if not success:
  3262. raise HTTPException(500, "Failed to set airduct mode")
  3263. return {"success": True, "message": f"Airduct mode set to {mode}"}
  3264. @router.post("/{printer_id}/chamber-light")
  3265. async def set_chamber_light(
  3266. printer_id: int,
  3267. on: bool = Query(..., description="True to turn on, False to turn off"),
  3268. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3269. db: AsyncSession = Depends(get_db),
  3270. ):
  3271. """Turn the chamber light on or off."""
  3272. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3273. printer = result.scalar_one_or_none()
  3274. if not printer:
  3275. raise HTTPException(404, "Printer not found")
  3276. client = printer_manager.get_client(printer_id)
  3277. if not client:
  3278. raise HTTPException(400, "Printer not connected")
  3279. success = client.set_chamber_light(on)
  3280. if not success:
  3281. raise HTTPException(500, "Failed to control chamber light")
  3282. return {"success": True, "message": f"Chamber light {'on' if on else 'off'}"}
  3283. @router.post("/{printer_id}/bed-jog")
  3284. async def bed_jog(
  3285. printer_id: int,
  3286. distance: float = Query(
  3287. ...,
  3288. description=(
  3289. "Signed nozzle-bed gap adjustment in mm. Negative = decrease gap "
  3290. '("up" arrow in the UI: bed up on bed-on-Z models, toolhead down '
  3291. "on A1 bed-slingers). Positive = increase gap. The backend "
  3292. "translates this into the right G-code Z sign per printer model."
  3293. ),
  3294. ),
  3295. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3296. db: AsyncSession = Depends(get_db),
  3297. ):
  3298. """Adjust the nozzle-bed gap by a relative distance.
  3299. Emits a short G-code sequence via MQTT.
  3300. Soft-endstop policy (#2579). The printer's software travel limits are the
  3301. only thing between a jog button and a bed crash — on Bambu machines the
  3302. physical endstops are homing-only (there is no runtime limit switch in the
  3303. travel path), so once they are disabled nothing stops the move. The old
  3304. code disabled them (``M211 S0``) around every forced jog, and the UI sent
  3305. ``force`` on every jog, so the limits were off on every bed move — that is
  3306. what let a jog drive the nozzle into the bed on all models (#2579). This
  3307. endpoint now emits a **bare relative move and never touches ``M211`` at
  3308. all** — byte-for-byte what the printer's own touchscreen jog sends, which
  3309. stops at the travel limit. Bambuddy no longer disables the firmware's soft
  3310. endstops, and it no longer sends ``M211 S1`` either: that was an unverified
  3311. attempt to re-enable a printer left disabled by an older build, and on real
  3312. hardware the jog moved past the limit *with* it. If a printer still jogs
  3313. past its limits, its endstops were disabled at the firmware level by the old
  3314. build — power-cycle it once to restore them; from then on Bambuddy leaves
  3315. them alone.
  3316. Direction handling: on bed-on-Z printers (X1 / P1 / H2 family) the bed
  3317. is the Z-axis, and Bambu's home convention puts Z=0 at the top with
  3318. Z+ moving the bed down — so a frontend "Up" (decrease gap) maps
  3319. naturally to ``G1 Z-``. On bed-slingers (A1 / A1 Mini) the Z-axis is
  3320. the *toolhead*, and ``G1 Z-`` instead drives the nozzle DOWN into the
  3321. bed (#1334 reported exactly that crash). For those models we invert
  3322. the sign before emitting the G-code, so the UI semantics stay the
  3323. same regardless of which part physically moves.
  3324. """
  3325. if distance == 0 or abs(distance) > 200:
  3326. raise HTTPException(400, "Distance must be non-zero and ≤ 200 mm")
  3327. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3328. printer = result.scalar_one_or_none()
  3329. if not printer:
  3330. raise HTTPException(404, "Printer not found")
  3331. client = printer_manager.get_client(printer_id)
  3332. if not client:
  3333. raise HTTPException(400, "Printer not connected")
  3334. from backend.app.services.printer_manager import is_bed_slinger
  3335. gcode_distance = -distance if is_bed_slinger(printer.model) else distance
  3336. # Bare relative move — exactly what the touchscreen sends. Never touch M211
  3337. # (#2579): the firmware keeps its soft endstops on by default and clamps the
  3338. # move at the travel limit.
  3339. lines = ["G91", f"G1 Z{gcode_distance:.2f} F600", "G90"]
  3340. if not client.send_gcode("\n".join(lines)):
  3341. raise HTTPException(500, "Failed to send bed-jog command")
  3342. return {"success": True, "message": f"Bed jog {distance:+.1f} mm sent"}
  3343. @router.post("/{printer_id}/xy-jog")
  3344. async def xy_jog(
  3345. printer_id: int,
  3346. x: float = Query(0, description="Signed relative X movement in mm"),
  3347. y: float = Query(0, description="Signed relative Y movement in mm"),
  3348. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3349. db: AsyncSession = Depends(get_db),
  3350. ):
  3351. """Move the toolhead by a relative X/Y distance."""
  3352. if (x == 0 and y == 0) or abs(x) > 200 or abs(y) > 200:
  3353. raise HTTPException(400, "X/Y movement must be non-zero and ≤ 200 mm per axis")
  3354. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3355. printer = result.scalar_one_or_none()
  3356. if not printer:
  3357. raise HTTPException(404, "Printer not found")
  3358. client = printer_manager.get_client(printer_id)
  3359. if not client:
  3360. raise HTTPException(400, "Printer not connected")
  3361. axes = []
  3362. if x:
  3363. axes.append(f"X{x:.2f}")
  3364. if y:
  3365. axes.append(f"Y{y:.2f}")
  3366. # Bare relative move — never touch M211 (#2579). The firmware keeps its soft
  3367. # endstops on by default and clamps the move at the travel limit; a printer
  3368. # left disabled by an older build is recovered with a power cycle.
  3369. if not client.send_gcode("\n".join(["G91", f"G1 {' '.join(axes)} F6000", "G90"])):
  3370. raise HTTPException(500, "Failed to send XY jog command")
  3371. return {"success": True, "message": f"XY jog X{x:+.1f} Y{y:+.1f} mm sent"}
  3372. @router.post("/{printer_id}/extruder-jog")
  3373. async def extruder_jog(
  3374. printer_id: int,
  3375. distance: float = Query(
  3376. ..., description="Signed relative extrusion distance in mm. Positive extrudes, negative retracts."
  3377. ),
  3378. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3379. db: AsyncSession = Depends(get_db),
  3380. ):
  3381. """Extrude or retract filament by a relative distance.
  3382. No client-side cold-extrude guard: Bambu firmware refuses extrusion
  3383. below its min-extrude temperature, so a cold call is rejected at the
  3384. printer, not silently damaging the extruder gear.
  3385. """
  3386. if distance == 0 or abs(distance) > 100:
  3387. raise HTTPException(400, "Extruder movement must be non-zero and ≤ 100 mm")
  3388. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3389. printer = result.scalar_one_or_none()
  3390. if not printer:
  3391. raise HTTPException(404, "Printer not found")
  3392. client = printer_manager.get_client(printer_id)
  3393. if not client:
  3394. raise HTTPException(400, "Printer not connected")
  3395. if not client.send_gcode("\n".join(["M83", f"G1 E{distance:.2f} F300", "M82"])):
  3396. raise HTTPException(500, "Failed to send extruder jog command")
  3397. return {"success": True, "message": f"Extruder jog {distance:+.1f} mm sent"}
  3398. @router.post("/{printer_id}/home-axes")
  3399. async def home_axes(
  3400. printer_id: int,
  3401. axes: str = Query(
  3402. "all",
  3403. description="Legacy; accepted values are 'z' | 'xy' | 'all'. Always runs the printer's full auto-home sequence — see below.",
  3404. ),
  3405. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3406. db: AsyncSession = Depends(get_db),
  3407. ):
  3408. """Run the printer's full auto-home sequence via bare `G28`.
  3409. Bambu printers (H2C / H2D / H2S / X1 family) home the Z axis by moving
  3410. the BED UP toward an endstop at the top of travel. If the toolhead is
  3411. not already parked out of the way, a bare `G28 Z` will crash the bed
  3412. into the toolhead — #1052 reported exactly that on H2C: the bed rose
  3413. without stopping at a safe height because `G28 Z` skipped the
  3414. toolhead-park step that a full `G28` runs first.
  3415. The endpoint therefore ignores the `axes` argument and always sends a
  3416. bare `G28`, which the firmware expands into a safe multi-step sequence
  3417. (park toolhead → home XY → home Z). The argument is kept only for
  3418. backward-compat with existing clients; sending an invalid value still
  3419. returns 400 so typos surface instead of silently proceeding.
  3420. """
  3421. axes = axes.lower()
  3422. if axes not in ("z", "xy", "all"):
  3423. raise HTTPException(400, "axes must be 'z', 'xy', or 'all'")
  3424. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3425. printer = result.scalar_one_or_none()
  3426. if not printer:
  3427. raise HTTPException(404, "Printer not found")
  3428. client = printer_manager.get_client(printer_id)
  3429. if not client:
  3430. raise HTTPException(400, "Printer not connected")
  3431. if not client.send_gcode("G28"):
  3432. raise HTTPException(500, "Failed to send home command")
  3433. return {"success": True, "message": "Full auto-home sequence sent"}
  3434. @router.post("/{printer_id}/hms/clear")
  3435. async def clear_hms_errors(
  3436. printer_id: int,
  3437. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3438. db: AsyncSession = Depends(get_db),
  3439. ):
  3440. """Clear HMS/print errors on the printer."""
  3441. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3442. printer = result.scalar_one_or_none()
  3443. if not printer:
  3444. raise HTTPException(404, "Printer not found")
  3445. client = printer_manager.get_client(printer_id)
  3446. if not client:
  3447. raise HTTPException(400, "Printer not connected")
  3448. success = client.clear_hms_errors()
  3449. if not success:
  3450. raise HTTPException(500, "Failed to clear HMS errors")
  3451. return {"success": True, "message": "HMS errors cleared"}
  3452. @router.get("/{printer_id}/print/objects")
  3453. async def get_printable_objects(
  3454. printer_id: int,
  3455. reload: bool = False,
  3456. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  3457. db: AsyncSession = Depends(get_db),
  3458. ):
  3459. """Get the list of printable objects for the current print.
  3460. Returns a list of objects with id, name, position (if available), and skip status.
  3461. Objects that have already been skipped are marked in the skipped_objects list.
  3462. Args:
  3463. reload: If True, reload objects from the archive file (useful after restart)
  3464. """
  3465. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3466. printer = result.scalar_one_or_none()
  3467. if not printer:
  3468. raise HTTPException(404, "Printer not found")
  3469. client = printer_manager.get_client(printer_id)
  3470. if not client:
  3471. raise HTTPException(400, "Printer not connected")
  3472. # Reload objects from 3MF if requested or no objects loaded
  3473. if reload or not client.state.printable_objects:
  3474. # The archive of a running print normally holds the very file the
  3475. # printer is executing, so ask the disk before asking the printer:
  3476. # the fan-out below pulls the whole 3MF over FTPS from a machine that
  3477. # is mid-print — 15 MB on the print this was written for — and on a
  3478. # printer that kept the file on internal storage it cannot succeed at
  3479. # all. skipped_objects is deliberately left alone: a reload is
  3480. # not a new print, and the list of what the user already skipped only
  3481. # lives here.
  3482. from backend.app.models.archive import PrintArchive
  3483. from backend.app.services.archive import extract_printable_objects_from_archive
  3484. subtask_id = str(getattr(client.state, "subtask_id", "") or "").strip()
  3485. if subtask_id not in ("", "0"):
  3486. archive = await db.scalar(
  3487. select(PrintArchive)
  3488. .where(
  3489. PrintArchive.printer_id == printer_id,
  3490. PrintArchive.status == "printing",
  3491. PrintArchive.subtask_id == subtask_id,
  3492. )
  3493. .order_by(PrintArchive.created_at.desc())
  3494. .limit(1)
  3495. )
  3496. if archive is not None:
  3497. objects, bbox_all = extract_printable_objects_from_archive(
  3498. settings.base_dir / archive.file_path,
  3499. plate_number=resolve_plate_id(client.state),
  3500. )
  3501. if objects:
  3502. client.state.printable_objects = objects
  3503. client.state.printable_objects_bbox_all = bbox_all
  3504. logger.info(
  3505. "Reloaded %s objects for printer %s from archive %s",
  3506. len(objects),
  3507. printer_id,
  3508. archive.id,
  3509. )
  3510. # Only when the disk could not answer: a `reload=true` that the archive
  3511. # satisfied has already refreshed from the file the printer is running.
  3512. if not client.state.printable_objects:
  3513. subtask_name = client.state.subtask_name
  3514. if subtask_name:
  3515. from backend.app.services.archive import extract_printable_objects_from_3mf
  3516. from backend.app.services.bambu_ftp import download_file_try_paths_async
  3517. # Build possible 3MF filenames (try both .gcode.3mf and .3mf)
  3518. possible_filenames = []
  3519. if subtask_name.endswith(".3mf"):
  3520. possible_filenames.append(subtask_name)
  3521. else:
  3522. possible_filenames.append(f"{subtask_name}.gcode.3mf")
  3523. possible_filenames.append(f"{subtask_name}.3mf")
  3524. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  3525. if " " in subtask_name:
  3526. normalized = subtask_name.replace(" ", "_")
  3527. if normalized.endswith(".3mf"):
  3528. possible_filenames.append(normalized)
  3529. else:
  3530. possible_filenames.append(f"{normalized}.gcode.3mf")
  3531. possible_filenames.append(f"{normalized}.3mf")
  3532. # Download 3MF from printer
  3533. temp_path = settings.archive_dir / "temp" / f"objects_{printer_id}_{possible_filenames[0]}"
  3534. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3535. # Build list of all remote paths to try
  3536. remote_paths = []
  3537. for filename in possible_filenames:
  3538. remote_paths.extend([f"/{filename}", f"/cache/{filename}", f"/model/{filename}"])
  3539. try:
  3540. downloaded = await download_file_try_paths_async(
  3541. printer.ip_address,
  3542. printer.access_code,
  3543. remote_paths,
  3544. temp_path,
  3545. printer_model=printer.model,
  3546. )
  3547. if downloaded and temp_path.exists():
  3548. with open(temp_path, "rb") as f:
  3549. data = f.read()
  3550. # Scope to the running plate: an all-plates 3MF lists every
  3551. # plate's objects, and offering plate 1's while the printer
  3552. # runs plate 2 makes every skip a misfire (#2522).
  3553. objects, bbox_all = extract_printable_objects_from_3mf(
  3554. data,
  3555. plate_number=resolve_plate_id(client.state),
  3556. include_positions=True,
  3557. )
  3558. if objects:
  3559. client.state.printable_objects = objects
  3560. client.state.printable_objects_bbox_all = bbox_all
  3561. logger.info("Reloaded %s objects for printer %s", len(objects), printer_id)
  3562. except Exception as e:
  3563. logger.debug("Failed to reload objects from printer: %s", e)
  3564. finally:
  3565. if temp_path.exists():
  3566. temp_path.unlink()
  3567. # Return objects with their skip status and position data
  3568. objects = []
  3569. for obj_id, obj_data in client.state.printable_objects.items():
  3570. # Handle both old format (string name) and new format (dict with name, x, y)
  3571. if isinstance(obj_data, dict):
  3572. obj_entry = {
  3573. "id": obj_id,
  3574. "name": obj_data.get("name", f"Object {obj_id}"),
  3575. "x": obj_data.get("x"),
  3576. "y": obj_data.get("y"),
  3577. "skipped": obj_id in client.state.skipped_objects,
  3578. }
  3579. else:
  3580. # Legacy format: obj_data is just the name string
  3581. obj_entry = {
  3582. "id": obj_id,
  3583. "name": obj_data,
  3584. "x": None,
  3585. "y": None,
  3586. "skipped": obj_id in client.state.skipped_objects,
  3587. }
  3588. objects.append(obj_entry)
  3589. return {
  3590. "objects": objects,
  3591. "total": len(objects),
  3592. "skipped_count": len(client.state.skipped_objects),
  3593. "is_printing": client.state.state in ("RUNNING", "PAUSE"),
  3594. "bbox_all": getattr(client.state, "printable_objects_bbox_all", None),
  3595. }
  3596. @router.post("/{printer_id}/print/skip-objects")
  3597. async def skip_objects(
  3598. printer_id: int,
  3599. object_ids: list[int],
  3600. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3601. db: AsyncSession = Depends(get_db),
  3602. ):
  3603. """Skip specific objects during the current print.
  3604. Args:
  3605. object_ids: List of object identify_id values to skip
  3606. """
  3607. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3608. printer = result.scalar_one_or_none()
  3609. if not printer:
  3610. raise HTTPException(404, "Printer not found")
  3611. client = printer_manager.get_client(printer_id)
  3612. if not client:
  3613. raise HTTPException(400, "Printer not connected")
  3614. if not object_ids:
  3615. raise HTTPException(400, "No object IDs provided")
  3616. # Validate object IDs exist in printable_objects
  3617. invalid_ids = [oid for oid in object_ids if oid not in client.state.printable_objects]
  3618. if invalid_ids:
  3619. raise HTTPException(400, f"Invalid object IDs: {invalid_ids}")
  3620. success = client.skip_objects(object_ids)
  3621. if not success:
  3622. raise HTTPException(500, "Failed to skip objects")
  3623. # Get names of skipped objects for response (handle both old and new format)
  3624. skipped_names = []
  3625. for oid in object_ids:
  3626. obj_data = client.state.printable_objects.get(oid, str(oid))
  3627. if isinstance(obj_data, dict):
  3628. skipped_names.append(obj_data.get("name", str(oid)))
  3629. else:
  3630. skipped_names.append(obj_data)
  3631. return {
  3632. "success": True,
  3633. "message": f"Skipped {len(object_ids)} object(s): {', '.join(skipped_names)}",
  3634. "skipped_objects": object_ids,
  3635. }
  3636. # =============================================================================
  3637. # AMS Control Endpoints
  3638. # =============================================================================
  3639. @router.post("/{printer_id}/ams/{ams_id}/slot/{slot_id}/refresh")
  3640. async def refresh_ams_slot(
  3641. printer_id: int,
  3642. ams_id: int,
  3643. slot_id: int,
  3644. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_AMS_RFID),
  3645. db: AsyncSession = Depends(get_db),
  3646. ):
  3647. """Re-read RFID for an AMS slot (triggers filament info refresh)."""
  3648. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3649. printer = result.scalar_one_or_none()
  3650. if not printer:
  3651. raise HTTPException(404, "Printer not found")
  3652. client = printer_manager.get_client(printer_id)
  3653. if not client:
  3654. raise HTTPException(400, "Printer not connected")
  3655. success, message = client.ams_refresh_tray(ams_id, slot_id)
  3656. if not success:
  3657. raise HTTPException(400, message)
  3658. # Apply PA profile after delay (RFID re-read takes a few seconds)
  3659. spawn_background_task(
  3660. _apply_pa_after_refresh(printer_id, ams_id, slot_id),
  3661. name=f"apply-pa-after-refresh-{printer_id}-{ams_id}-{slot_id}",
  3662. )
  3663. return {"success": True, "message": message}
  3664. async def _apply_pa_after_refresh(printer_id: int, ams_id: int, slot_id: int):
  3665. """Apply PA profile after RFID re-read completes.
  3666. Waits for the printer to finish processing the RFID data, then selects
  3667. the K-profile via extrusion_cali_sel. Does NOT re-send ams_set_filament_setting
  3668. because that would overwrite the RFID-provided filament data.
  3669. """
  3670. await asyncio.sleep(5)
  3671. try:
  3672. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  3673. from backend.app.core.database import async_session
  3674. from backend.app.models.spool import Spool
  3675. from backend.app.models.spool_assignment import SpoolAssignment as SA
  3676. from backend.app.models.spoolman_k_profile import SpoolmanKProfile
  3677. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  3678. from backend.app.services.spool_tag_matcher import (
  3679. ZERO_TAG_UID,
  3680. ZERO_TRAY_UUID,
  3681. is_bambu_tag,
  3682. )
  3683. from backend.app.utils.tag_normalization import (
  3684. normalize_tag_uid,
  3685. normalize_tray_uuid,
  3686. )
  3687. client = printer_manager.get_client(printer_id)
  3688. if not client:
  3689. return
  3690. state = printer_manager.get_status(printer_id)
  3691. if not state or not state.raw_data:
  3692. return
  3693. # Find current tray data (should have RFID data by now)
  3694. ams_data = state.raw_data.get("ams", {})
  3695. ams_list = (
  3696. ams_data.get("ams", []) if isinstance(ams_data, dict) else ams_data if isinstance(ams_data, list) else []
  3697. )
  3698. tray = _find_tray_in_ams_data(ams_list, ams_id, slot_id)
  3699. if not tray or not tray.get("tray_type"):
  3700. logger.debug("PA re-apply: no tray data for AMS%d-T%d", ams_id, slot_id)
  3701. return
  3702. tag_uid = tray.get("tag_uid", "")
  3703. tray_uuid = tray.get("tray_uuid", "")
  3704. tray_info_idx = tray.get("tray_info_idx", "")
  3705. if not is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  3706. return
  3707. # Compute nozzle/extruder once — used by both local and Spoolman lookup.
  3708. # Shared with every other slot-configuring path (services.slot_nozzle),
  3709. # so the diameter this cascade filters on is the one the slot's own
  3710. # hotend actually has.
  3711. slot_nozzle = resolve_slot_nozzle(state, ams_id, slot_id, printer_manager.get_model(printer_id))
  3712. nozzle_diameter = slot_nozzle.diameter
  3713. resolved_extruder = slot_nozzle.extruder
  3714. # 3-stage K-profile cascade: local SpoolKProfile → Spoolman SpoolmanKProfile
  3715. # → live tray.cali_idx fallback. Pre-Phase-13 only handled the local path
  3716. # and exited silently if no SpoolKProfile match; Spoolman-assigned slots
  3717. # were ignored entirely and live cali_idx was never re-asserted.
  3718. matching_cali_idx: int | None = None
  3719. matching_filament_id: str = tray_info_idx
  3720. async with async_session() as db:
  3721. from sqlalchemy import or_, select as sa_select
  3722. from sqlalchemy.orm import selectinload
  3723. # Stage 1: local SpoolAssignment + SpoolKProfile match
  3724. result = await db.execute(
  3725. sa_select(SA)
  3726. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  3727. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == slot_id)
  3728. )
  3729. assignment = result.scalar_one_or_none()
  3730. spool: Spool | None = assignment.spool if assignment else None
  3731. # Stage 1b: tag-based fallback. The slot may have just been reset
  3732. # (SpoolAssignment row deleted) before the user triggered a re-read.
  3733. # The live tray already carries the spool's tray_uuid/tag_uid from
  3734. # the RFID re-read, but the SA row hasn't been re-created yet.
  3735. # Without this fallback we miss the stored SpoolKProfile and Stage 3
  3736. # ends up re-asserting whatever cali_idx the firmware reset to
  3737. # (typically the default profile).
  3738. if spool is None:
  3739. norm_uuid = normalize_tray_uuid(tray_uuid) if tray_uuid else ""
  3740. norm_tag = normalize_tag_uid(tag_uid) if tag_uid else ""
  3741. tag_filters = []
  3742. if norm_uuid and norm_uuid != ZERO_TRAY_UUID:
  3743. tag_filters.append(Spool.tray_uuid == norm_uuid)
  3744. if norm_tag and norm_tag != ZERO_TAG_UID:
  3745. tag_filters.append(Spool.tag_uid == norm_tag)
  3746. if tag_filters:
  3747. tag_lookup = await db.execute(
  3748. select(Spool).options(selectinload(Spool.k_profiles)).where(or_(*tag_filters)).limit(1)
  3749. )
  3750. spool = tag_lookup.scalar_one_or_none()
  3751. if spool is not None:
  3752. logger.info(
  3753. "PA re-apply AMS%d-T%d: matched spool %d via tag fallback "
  3754. "(SpoolAssignment row missing, likely after slot reset)",
  3755. ams_id,
  3756. slot_id,
  3757. spool.id,
  3758. )
  3759. if spool is not None and spool.k_profiles:
  3760. # Prefer exact extruder match, fall back to extruder-agnostic kp
  3761. # for the same printer + nozzle. Hard-skipping on extruder
  3762. # mismatch made the cascade refuse perfectly valid stored
  3763. # profiles whenever the AMS-extruder mapping had shifted since
  3764. # calibration time, falling all the way through to Stage 3 and
  3765. # re-asserting the firmware default.
  3766. exact_kp = None
  3767. fallback_kp = None
  3768. for kp in spool.k_profiles:
  3769. if not slot_nozzle.flow_matches(kp.nozzle_type):
  3770. continue
  3771. if kp.printer_id != printer_id or kp.nozzle_diameter != nozzle_diameter or kp.cali_idx is None:
  3772. continue
  3773. if resolved_extruder is not None and kp.extruder is not None and kp.extruder == resolved_extruder:
  3774. exact_kp = kp
  3775. break
  3776. if fallback_kp is None:
  3777. fallback_kp = kp
  3778. chosen_kp = exact_kp or fallback_kp
  3779. if chosen_kp is not None:
  3780. matching_cali_idx = chosen_kp.cali_idx
  3781. # The filament_id in extrusion_cali_sel must match the preset
  3782. # under which the K-profile was calibrated. Prefer the spool's
  3783. # slicer_filament setting, falling back to the tray's RFID value.
  3784. matching_filament_id = spool.slicer_filament or tray_info_idx
  3785. # Stage 2: Spoolman SpoolmanSlotAssignment + SpoolmanKProfile match
  3786. # (only when no local spool was matched — local takes priority,
  3787. # including the tag-based fallback above)
  3788. if matching_cali_idx is None and spool is None:
  3789. sm_result = await db.execute(
  3790. select(SpoolmanSlotAssignment).where(
  3791. SpoolmanSlotAssignment.printer_id == printer_id,
  3792. SpoolmanSlotAssignment.ams_id == ams_id,
  3793. SpoolmanSlotAssignment.tray_id == slot_id,
  3794. )
  3795. )
  3796. sm_assignment = sm_result.scalar_one_or_none()
  3797. if sm_assignment:
  3798. kp_result = await db.execute(
  3799. sa_select(SpoolmanKProfile).where(
  3800. SpoolmanKProfile.spoolman_spool_id == sm_assignment.spoolman_spool_id,
  3801. SpoolmanKProfile.printer_id == printer_id,
  3802. )
  3803. )
  3804. for kp in kp_result.scalars().all():
  3805. if kp.nozzle_diameter == nozzle_diameter:
  3806. if (
  3807. resolved_extruder is not None
  3808. and kp.extruder is not None
  3809. and kp.extruder != resolved_extruder
  3810. ):
  3811. continue
  3812. if kp.cali_idx is not None:
  3813. matching_cali_idx = kp.cali_idx
  3814. # Spoolman has no slicer_filament — use the tray's RFID value
  3815. matching_filament_id = tray_info_idx
  3816. break
  3817. # Stage 3: live tray.cali_idx fallback. Re-asserts the printer's current
  3818. # selection so the value sticks across the RFID re-read (otherwise some
  3819. # firmwares clear cali_idx back to -1 mid-cycle).
  3820. if matching_cali_idx is None:
  3821. live_cali_idx = tray.get("cali_idx")
  3822. if live_cali_idx is not None and live_cali_idx >= 0:
  3823. matching_cali_idx = live_cali_idx
  3824. if matching_cali_idx is None:
  3825. logger.debug(
  3826. "PA re-apply AMS%d-T%d: no stored or live cali_idx — skipping MQTT",
  3827. ams_id,
  3828. slot_id,
  3829. )
  3830. return
  3831. logger.info(
  3832. "PA re-apply AMS%d-T%d: cali_idx=%d, filament_id=%s",
  3833. ams_id,
  3834. slot_id,
  3835. matching_cali_idx,
  3836. matching_filament_id,
  3837. )
  3838. # NOTE: Do NOT send ams_set_filament_setting here — it tells the firmware
  3839. # "this is a manual config" which destroys the RFID-detected spool state
  3840. # (changes eye icon to pen icon in slicer).
  3841. client.extrusion_cali_sel(
  3842. ams_id=ams_id,
  3843. tray_id=slot_id,
  3844. cali_idx=matching_cali_idx,
  3845. filament_id=matching_filament_id,
  3846. nozzle_diameter=nozzle_diameter,
  3847. )
  3848. # NOTE: Do NOT send extrusion_cali_set here. extrusion_cali_sel already
  3849. # selected the correct profile by cali_idx. Sending extrusion_cali_set with
  3850. # the same cali_idx would MODIFY the existing profile's metadata (extruder_id,
  3851. # nozzle_id, name), corrupting it.
  3852. logger.info(
  3853. "Applied PA profile cali_idx=%d to printer %d AMS%d-T%d",
  3854. matching_cali_idx,
  3855. printer_id,
  3856. ams_id,
  3857. slot_id,
  3858. )
  3859. except Exception as e:
  3860. logger.warning("Failed to apply PA profile after RFID re-read: %s", e)
  3861. # 24-27 are the A2L AMS-Lite slots (normalised unit 6 = 6*4+slot); see
  3862. # a2l-am-unit-16. They are valid global tray ids alongside the regular 0-15.
  3863. _LOAD_TRAY_ID_ERROR = "tray_id must be 0..15 (AMS slot), 24..27 (A2L AMS-Lite), 254 (external / Ext-L), or 255 (Ext-R)"
  3864. def _is_valid_load_tray_id(tray_id: int) -> bool:
  3865. """Whether ``tray_id`` names a slot the load/unload commands can address."""
  3866. return tray_id in range(16) or tray_id in range(24, 28) or tray_id in (254, 255)
  3867. @router.post("/{printer_id}/ams/load")
  3868. async def ams_load(
  3869. printer_id: int,
  3870. tray_id: int = Query(..., description="Tray ID: 0-15 for AMS slots (ams_id*4+slot_id), 254 for external spool"),
  3871. extruder_id: int | None = Query(
  3872. None,
  3873. ge=0,
  3874. le=1,
  3875. description=(
  3876. "Hotend to feed: 0 = right/main, 1 = left/deputy. Only meaningful "
  3877. "on a printer with a Filament Track Switch fitted, where the AMS is "
  3878. "bound to a switch inlet rather than a hotend and the firmware "
  3879. "cannot work the target out for itself. Omit on every other printer "
  3880. "— the field is absent from BambuStudio's own command there too."
  3881. ),
  3882. ),
  3883. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3884. db: AsyncSession = Depends(get_db),
  3885. ):
  3886. """Load filament from a specific AMS slot or external spool.
  3887. Tray ID encoding (matches Bambu firmware convention):
  3888. - 0..15: AMS slot, computed as ams_id * 4 + slot_id
  3889. - 254: external spool (single-external printers, or Ext-L on dual-nozzle H2D)
  3890. - 255: Ext-R on dual-nozzle H2D
  3891. """
  3892. if not _is_valid_load_tray_id(tray_id):
  3893. raise HTTPException(400, _LOAD_TRAY_ID_ERROR)
  3894. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3895. printer = result.scalar_one_or_none()
  3896. if not printer:
  3897. raise HTTPException(404, "Printer not found")
  3898. client = printer_manager.get_client(printer_id)
  3899. if not client:
  3900. raise HTTPException(400, "Printer not connected")
  3901. success = client.ams_load_filament(tray_id, extruder_id=extruder_id)
  3902. if not success:
  3903. raise HTTPException(500, "Failed to send load command")
  3904. if tray_id == 254:
  3905. target = "external spool"
  3906. elif tray_id == 255:
  3907. target = "Ext-R"
  3908. else:
  3909. target = f"AMS {tray_id // 4} slot {tray_id % 4 + 1}"
  3910. return {"success": True, "message": f"Loading filament from {target}"}
  3911. @router.post("/{printer_id}/ams/unload")
  3912. async def ams_unload(
  3913. printer_id: int,
  3914. tray_id: int | None = Query(
  3915. None,
  3916. description=(
  3917. "Tray ID of the slot to unload, same encoding as the load endpoint. "
  3918. "Identifies which hotend to unload on a dual-nozzle printer, where "
  3919. "both can hold filament at once and the printer's single tray_now "
  3920. "field names only one of them. Omit to unload whatever tray_now "
  3921. "names, which is the only option a single-nozzle printer has."
  3922. ),
  3923. ),
  3924. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3925. db: AsyncSession = Depends(get_db),
  3926. ):
  3927. """Unload the filament in a given slot, or the currently loaded one."""
  3928. if tray_id is not None and not _is_valid_load_tray_id(tray_id):
  3929. raise HTTPException(400, _LOAD_TRAY_ID_ERROR)
  3930. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3931. printer = result.scalar_one_or_none()
  3932. if not printer:
  3933. raise HTTPException(404, "Printer not found")
  3934. client = printer_manager.get_client(printer_id)
  3935. if not client:
  3936. raise HTTPException(400, "Printer not connected")
  3937. success = client.ams_unload_filament(tray_id)
  3938. if not success:
  3939. # A named slot that no hotend is fed from is a no-op, not a fault: the
  3940. # menu is per-slot and the operator may well have clicked one that is
  3941. # not loaded. Say so instead of returning a 500 they cannot act on.
  3942. if tray_id is not None:
  3943. raise HTTPException(409, "No hotend is loaded from that slot")
  3944. raise HTTPException(500, "Failed to send unload command")
  3945. return {"success": True, "message": "Unloading filament"}
  3946. @router.get("/{printer_id}/runtime-debug")
  3947. async def get_runtime_debug(
  3948. printer_id: int,
  3949. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  3950. db: AsyncSession = Depends(get_db),
  3951. ):
  3952. """Debug endpoint: Get runtime tracking status for a printer."""
  3953. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3954. printer = result.scalar_one_or_none()
  3955. if not printer:
  3956. raise HTTPException(404, "Printer not found")
  3957. state = printer_manager.get_status(printer_id)
  3958. return {
  3959. "printer_name": printer.name,
  3960. "runtime_seconds": printer.runtime_seconds,
  3961. "runtime_hours": printer.runtime_seconds / 3600.0 if printer.runtime_seconds else 0,
  3962. "print_hours_offset": printer.print_hours_offset,
  3963. "total_hours": (printer.runtime_seconds / 3600.0 if printer.runtime_seconds else 0)
  3964. + (printer.print_hours_offset or 0),
  3965. "last_runtime_update": printer.last_runtime_update.isoformat() if printer.last_runtime_update else None,
  3966. "mqtt_state": {
  3967. "connected": state.connected if state else False,
  3968. "state": state.state if state else None,
  3969. "progress": state.progress if state else None,
  3970. "gcode_file": state.gcode_file if state else None,
  3971. }
  3972. if state
  3973. else None,
  3974. "is_active": printer.is_active,
  3975. }
  3976. @router.post("/{printer_id}/hms/execute-action")
  3977. async def execute_hms_action(
  3978. printer_id: int,
  3979. body: HmsActionBody,
  3980. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3981. db: AsyncSession = Depends(get_db),
  3982. ):
  3983. """Execute an HMS action on the printer."""
  3984. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3985. printer = result.scalar_one_or_none()
  3986. if not printer:
  3987. raise HTTPException(404, "Printer not found")
  3988. client = printer_manager.get_client(printer_id)
  3989. if not client:
  3990. raise HTTPException(400, "Printer not connected")
  3991. # Snapshot pre-state so we can verify the printer actually acted on the
  3992. # command. publish() success is NOT the same as printer-ack: Bambu's
  3993. # firmware silently rejects malformed HMS commands at QoS 1 (the broker
  3994. # ACKs the publish, but the printer drops it). Verified end-to-end against
  3995. # a live H2D — see #1830 §(3).
  3996. #
  3997. # We probe `_last_message_time` (bumped on every MQTT push) rather than a
  3998. # (gcode_state, hms_errors-length) diff. The old diff missed the
  3999. # wrong-plate IGNORE_RESUME case where the printer briefly resumes and
  4000. # re-pauses with the same fault inside the 2.5s window: both fields
  4001. # round-trip to their pre-publish values → false 502 even though the
  4002. # firmware fully ack'd the resume. Every accepted command triggers a
  4003. # pushall response within ~100-500ms, so a fresh inbound message after
  4004. # the publish is the robust ack signal.
  4005. pre_last_message = client._last_message_time
  4006. success = client.execute_hms_action(body.print_error, body.action, body.job_id)
  4007. if not success:
  4008. raise HTTPException(400, "Failed to execute HMS action")
  4009. # Give the printer time to push a state update. The dispatch helper already
  4010. # publishes a pushall after every command, so a fresh status should arrive
  4011. # within ~1s; the default 2.5s covers slower firmware variants without
  4012. # making the UI feel hung. Plain sleep is fine — paho's MQTT callback
  4013. # runs in its own thread and updates state regardless of whether this
  4014. # coroutine is awaiting.
  4015. await asyncio.sleep(HMS_ACTION_ACK_WAIT_SECONDS)
  4016. acked = client._last_message_time > pre_last_message
  4017. if not acked:
  4018. # Publish succeeded but the printer sent nothing back. Almost always
  4019. # firmware-side silent rejection (err mismatch, command/state mismatch)
  4020. # or a dropped MQTT route. 502 makes it visible at the UI instead of
  4021. # the 200-but-broken loop #1830 reported.
  4022. raise HTTPException(502, "Printer did not acknowledge HMS action within 2.5s")
  4023. return {"success": True, "message": "HMS action executed"}