printers.py 191 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659
  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. def _cached_source() -> Path | None:
  1169. """The 3MF another flow has already published for this print, if any."""
  1170. for candidate_name in (*possible_filenames, storage.probe_filename):
  1171. if not candidate_name:
  1172. continue
  1173. cached = get_cached_3mf(printer_id, candidate_name)
  1174. if cached:
  1175. return cached
  1176. return None
  1177. cached = _cached_source()
  1178. if cached:
  1179. logger.info("Cover using cached 3MF from %s (avoided duplicate FTP)", cached)
  1180. temp_path = cached
  1181. downloaded = True
  1182. using_cached = True
  1183. if not downloaded:
  1184. # Same idea, one step further back: that in-memory cache dies with the
  1185. # process, but the archive of the print that is still running holds the
  1186. # very 3MF on disk. Without this, reopening a card or the skip-objects
  1187. # plate after a restart pulls the whole file back off a printer that is
  1188. # mid-print — measured at three concurrent fan-outs, thirteen seconds
  1189. # and a 0-byte read on the maintainer's H2C, which is exactly the
  1190. # single-socket contention #972 was about.
  1191. if archive_path is not None:
  1192. logger.info("Cover using the running print's archived 3MF at %s (no FTP)", archive_path)
  1193. temp_path = archive_path
  1194. downloaded = True
  1195. using_cached = True
  1196. if not downloaded:
  1197. # The cover lives inside the 3MF, so it is only reachable if the 3MF is.
  1198. # When the printer kept the print on internal storage there is nothing
  1199. # at any of these paths, and walking all sixteen of them just to end on
  1200. # a 404 that reads as "this print has no cover" helps nobody (#2780).
  1201. #
  1202. # Unless the printer is wrong about that, which an H2D with a card in
  1203. # routinely is (#2856). The dispatch names the file, so when it does,
  1204. # trade the immediate 404 for a five-path probe of that one name — same
  1205. # single connection, and it is the only way this endpoint ever recovers
  1206. # a cover for a print the archive flow did not see start.
  1207. max_retries = 2
  1208. if not storage.reachable:
  1209. if not storage.probe_filename:
  1210. _cover_404_cache.setdefault(printer_id, set()).add(cache_key)
  1211. raise HTTPException(
  1212. 404,
  1213. f"The print file for '{subtask_name}' is not on storage Bambuddy can read over FTPS "
  1214. f"({storage.reason}), so it has no cover to extract.",
  1215. )
  1216. remote_paths = ftp_probe_paths(storage.probe_filename)
  1217. # The dispatch's name is the authoritative one — a print whose
  1218. # subtask_name has been normalized or truncated would otherwise be
  1219. # cached under a key the archive flow never looks up.
  1220. temp_filename = storage.probe_filename
  1221. temp_path = settings.archive_dir / "temp" / f"cover_{printer_id}_{temp_filename}"
  1222. # One look, not three: the printer has already said this file is not
  1223. # here, so a retry storm on top of a hunch is exactly what #2780 was.
  1224. max_retries = 0
  1225. logger.info(
  1226. f"Trying to download cover for '{subtask_name}' from {printer.ip_address} (trying {len(remote_paths)} paths)"
  1227. )
  1228. # Retry logic for transient FTP failures
  1229. last_error = None
  1230. for attempt in range(max_retries + 1):
  1231. if attempt:
  1232. # Look again before spending another transfer. The entry check
  1233. # above only settles the race when the two flows do not
  1234. # overlap, and on a P1S at print start they overlap for
  1235. # minutes: a reported run had the archive flow publish the file
  1236. # 42 seconds into this endpoint's 2.5-minute retry sequence,
  1237. # and the third attempt still pulled its own 5 MB copy of it
  1238. # over the same socket the printer was serving the print from
  1239. # (#2957).
  1240. cached = _cached_source()
  1241. if cached:
  1242. logger.info(
  1243. "Cover picked up the 3MF another flow finished downloading (%s) — skipping retry %s",
  1244. cached,
  1245. attempt + 1,
  1246. )
  1247. temp_path = cached
  1248. downloaded = True
  1249. using_cached = True
  1250. break
  1251. if ftps_handshake_blocked(printer.ip_address):
  1252. # Nothing to retry: the printer is not completing a TLS
  1253. # handshake on port 990, so no path and no attempt reaches it
  1254. # (#2780). Report the real cause instead of the 404 below,
  1255. # which would read as "this print has no cover".
  1256. raise HTTPException(
  1257. 503,
  1258. f"Printer {printer.ip_address} is not answering its file service over TLS. "
  1259. "Bambuddy will try again shortly.",
  1260. )
  1261. try:
  1262. downloaded = await download_file_try_paths_async(
  1263. printer.ip_address,
  1264. printer.access_code,
  1265. remote_paths,
  1266. temp_path,
  1267. printer_model=printer.model,
  1268. )
  1269. if downloaded:
  1270. break
  1271. except Exception as e:
  1272. last_error = e
  1273. if attempt < max_retries:
  1274. logger.warning("FTP download attempt %s failed: %s, retrying...", attempt + 1, e)
  1275. await asyncio.sleep(0.5 * (attempt + 1)) # Brief backoff
  1276. else:
  1277. logger.error("FTP download failed after %s attempts: %s", max_retries + 1, e)
  1278. if last_error and not downloaded:
  1279. raise HTTPException(503, f"FTP download temporarily unavailable: {last_error}")
  1280. if not downloaded:
  1281. # Remember this failure so subsequent requests for the same print
  1282. # skip the 8-path FTP fan-out (#1420).
  1283. _cover_404_cache.setdefault(printer_id, set()).add(cache_key)
  1284. if not storage.reachable:
  1285. # The probe looked and found nothing, so the printer's own
  1286. # account of where the file went is the answer after all —
  1287. # keep saying so rather than reporting a generic miss (#2780).
  1288. raise HTTPException(
  1289. 404,
  1290. f"The print file for '{subtask_name}' is not on storage Bambuddy can read over FTPS "
  1291. f"({storage.reason}), so it has no cover to extract.",
  1292. )
  1293. raise HTTPException(
  1294. 404,
  1295. f"Could not download 3MF file for '{subtask_name}' from printer {printer.ip_address}. Tried: {possible_filenames}",
  1296. )
  1297. # Share the fresh download with the archive flow — unless the file is
  1298. # already theirs, in which case re-registering it under this endpoint's
  1299. # own name would only add a second key pointing at the same bytes.
  1300. if not using_cached:
  1301. cache_3mf_download(printer_id, temp_filename, temp_path)
  1302. # Verify file actually exists and has content
  1303. if not temp_path.exists():
  1304. raise HTTPException(500, f"Download reported success but file not found: {temp_path}")
  1305. file_size = temp_path.stat().st_size
  1306. logger.info("Downloaded file size: %s bytes", file_size)
  1307. if file_size == 0:
  1308. if not using_cached:
  1309. temp_path.unlink()
  1310. raise HTTPException(500, f"Downloaded file is empty for '{subtask_name}'")
  1311. # Offer the file to the archive flow before extracting the thumbnail. When
  1312. # the print started inside the printer's FTPS cool-off, the archive flow
  1313. # gave up without a single connection and this endpoint holds the very file
  1314. # it wanted — which used to be read for a thumbnail and then deleted at
  1315. # print completion, leaving a permanently empty archive (#2957). Covers the
  1316. # cached branch as well as a fresh download: whoever fetched it, the running
  1317. # print's archive should have it. A no-op unless that archive is a fallback.
  1318. from backend.app.main import try_recover_fallback_archive
  1319. await try_recover_fallback_archive(printer_id, temp_filename, temp_path)
  1320. try:
  1321. # Extract thumbnail from 3MF (which is a ZIP file)
  1322. try:
  1323. zf = zipfile.ZipFile(temp_path, "r")
  1324. except zipfile.BadZipFile:
  1325. raise HTTPException(500, "Downloaded file is not a valid 3MF/ZIP archive")
  1326. except OSError as e:
  1327. logger.error("Failed to open 3MF file: %s", e, exc_info=True)
  1328. raise HTTPException(500, "Failed to open 3MF file. Check server logs for details.")
  1329. try:
  1330. # 3MF-scan fallback for plate detection (#1166). Per-plate archives
  1331. # sliced separately in Bambu Studio contain a single
  1332. # Metadata/plate_N.gcode for the active plate, even though
  1333. # thumbnails for all plates are bundled. Using that gcode's plate
  1334. # number prevents falling back to plate_1.png.
  1335. if plate_num is None:
  1336. plate_gcodes = [name for name in zf.namelist() if re.match(r"^Metadata/plate_\d+\.gcode$", name)]
  1337. if len(plate_gcodes) == 1:
  1338. match = re.search(r"plate_(\d+)\.gcode", plate_gcodes[0])
  1339. if match:
  1340. plate_num = int(match.group(1))
  1341. logger.info("Cover: detected plate %s from 3MF contents", plate_num)
  1342. if plate_num is None:
  1343. plate_num = 1
  1344. # Try common thumbnail paths in 3MF files
  1345. # Use plate_num to get the correct plate's thumbnail for multi-plate projects
  1346. # Use top-down view if requested (better for skip objects modal)
  1347. if view == "pick":
  1348. # Only the active plate's mask, with no fallback: every other view
  1349. # falls back to plate 1 because a slightly wrong picture is better
  1350. # than none, but a mask is coordinates, not decoration. Plate 1's
  1351. # mask over plate 3's layout would resolve clicks to whichever
  1352. # object happened to occupy that pixel on a different plate.
  1353. thumbnail_paths = [f"Metadata/pick_{plate_num}.png"]
  1354. elif view == "top":
  1355. thumbnail_paths = [
  1356. f"Metadata/top_{plate_num}.png",
  1357. # Fall back to plate 1 if specific plate not found
  1358. "Metadata/top_1.png",
  1359. f"Metadata/plate_{plate_num}.png",
  1360. "Metadata/plate_1.png",
  1361. "Metadata/thumbnail.png",
  1362. ]
  1363. else:
  1364. thumbnail_paths = [
  1365. f"Metadata/plate_{plate_num}.png",
  1366. # Fall back to plate 1 if specific plate not found
  1367. "Metadata/plate_1.png",
  1368. "Metadata/thumbnail.png",
  1369. f"Metadata/plate_{plate_num}_small.png",
  1370. "Metadata/plate_1_small.png",
  1371. "Thumbnails/thumbnail.png",
  1372. "thumbnail.png",
  1373. ]
  1374. for thumb_path in thumbnail_paths:
  1375. try:
  1376. image_data = zf.read(thumb_path)
  1377. if printer_id not in _cover_cache:
  1378. _cover_cache[printer_id] = {}
  1379. _cover_cache[printer_id][(subtask_name, view_key)] = image_data
  1380. return image_data
  1381. except KeyError:
  1382. continue
  1383. # If no specific thumbnail found, try any PNG in Metadata. Never for
  1384. # "pick": handing back a rendered thumbnail in place of the object-ID
  1385. # mask is worse than nothing, because the caller can't tell the
  1386. # difference and decodes the render's pixel colours as object IDs —
  1387. # dark pixels yield small integers that collide with real IDs, so a
  1388. # click would select an arbitrary object and skip it irreversibly.
  1389. # A 404 is what tells the UI to fall back to the checklist.
  1390. if view != "pick":
  1391. for name in zf.namelist():
  1392. if name.startswith("Metadata/") and name.endswith(".png"):
  1393. image_data = zf.read(name)
  1394. if printer_id not in _cover_cache:
  1395. _cover_cache[printer_id] = {}
  1396. _cover_cache[printer_id][(subtask_name, view_key)] = image_data
  1397. return image_data
  1398. _cover_404_cache.setdefault(printer_id, set()).add(cache_key)
  1399. raise HTTPException(404, "No thumbnail found in 3MF file")
  1400. finally:
  1401. zf.close()
  1402. finally:
  1403. # Only delete when this invocation owns the file. A cached path is
  1404. # shared with the archive flow — removing it would force a refetch
  1405. # the next time either flow needs the 3MF.
  1406. if not using_cached and temp_path.exists():
  1407. temp_path.unlink()
  1408. # ============================================
  1409. # File Manager Endpoints
  1410. # ============================================
  1411. async def _load_printer_or_404(printer_id: int) -> Printer:
  1412. """Load a printer in a short-lived session, releasing the pooled DB
  1413. connection before the caller starts any FTP/network I/O (#2572).
  1414. The file-manager and storage routes talk FTP to the printer, which can
  1415. block for the full socket timeout — longer when a saturated FTP pool backs
  1416. up. Holding the request's Depends(get_db) session across that FTP pinned one
  1417. pooled connection idle-in-transaction per in-flight request, a top cause of
  1418. pool exhaustion on large farms. The returned row's scalar columns stay
  1419. readable after the session closes (expire_on_commit=False). Raises 404 when
  1420. the printer doesn't exist.
  1421. Reference async_session via the module so the maker is resolved at call time
  1422. — keeps it in sync with reinitialize_database() and lets tests patch it.
  1423. """
  1424. async with database.async_session() as db:
  1425. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1426. printer = result.scalar_one_or_none()
  1427. if not printer:
  1428. raise HTTPException(404, "Printer not found")
  1429. return printer
  1430. @router.get("/{printer_id}/files")
  1431. async def list_printer_files(
  1432. printer_id: int,
  1433. path: str = "/",
  1434. _=RequirePrinterPermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  1435. ):
  1436. """List files on the printer at the specified path."""
  1437. printer = await _load_printer_or_404(printer_id)
  1438. listing = await list_files_result_async(
  1439. printer.ip_address,
  1440. printer.access_code,
  1441. path,
  1442. printer_model=printer.model,
  1443. )
  1444. files = listing.files
  1445. # Add full path to each file
  1446. for f in files:
  1447. f["path"] = f"{path.rstrip('/')}/{f['name']}" if path != "/" else f"/{f['name']}"
  1448. return {
  1449. "path": path,
  1450. "files": files,
  1451. "warnings": [] if listing.available else ["printer_unavailable"],
  1452. }
  1453. @router.get("/{printer_id}/files/download")
  1454. async def download_printer_file(
  1455. printer_id: int,
  1456. path: str,
  1457. _=RequirePrinterPermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  1458. ):
  1459. """Download a file from the printer."""
  1460. printer = await _load_printer_or_404(printer_id)
  1461. try:
  1462. async with asyncio.timeout(MAX_PRINTER_ZIP_PREPARE_SECONDS):
  1463. result = await build_printer_file(
  1464. printer,
  1465. path,
  1466. None,
  1467. bundle_key=f"single-{secrets.token_urlsafe(18)}",
  1468. )
  1469. except PrinterFilesZipTooLargeError as exc:
  1470. raise HTTPException(413, str(exc)) from exc
  1471. except PrinterFilesZipInsufficientSpaceError as exc:
  1472. raise HTTPException(507, str(exc)) from exc
  1473. except FileNotFoundError:
  1474. raise HTTPException(404, f"File not found: {path}")
  1475. except TimeoutError as exc:
  1476. raise HTTPException(504, "Printer download exceeded the 30-minute limit") from exc
  1477. # Determine content type based on extension
  1478. filename = path.split("/")[-1]
  1479. ext = filename.lower().split(".")[-1] if "." in filename else ""
  1480. content_types = {
  1481. "3mf": "application/vnd.ms-package.3dmanufacturing-3dmodel+xml",
  1482. "gcode": "text/plain",
  1483. "mp4": "video/mp4",
  1484. "avi": "video/x-msvideo",
  1485. "png": "image/png",
  1486. "jpg": "image/jpeg",
  1487. "jpeg": "image/jpeg",
  1488. "json": "application/json",
  1489. "txt": "text/plain",
  1490. }
  1491. content_type = content_types.get(ext, "application/octet-stream")
  1492. return FileResponse(
  1493. path=result.path,
  1494. filename=filename,
  1495. media_type=content_type,
  1496. headers={"Content-Disposition": build_content_disposition(filename)},
  1497. background=BackgroundTask(remove_printer_files_zip, result.path),
  1498. )
  1499. @router.get("/{printer_id}/files/gcode")
  1500. async def get_printer_file_gcode(
  1501. printer_id: int,
  1502. path: str,
  1503. _=RequirePrinterPermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  1504. ):
  1505. """Get gcode for a file stored on a printer (for preview)."""
  1506. import io
  1507. printer = await _load_printer_or_404(printer_id)
  1508. data = await download_file_bytes_async(printer.ip_address, printer.access_code, path, printer_model=printer.model)
  1509. if data is None:
  1510. raise HTTPException(404, f"File not found: {path}")
  1511. filename = path.split("/")[-1]
  1512. lower = filename.lower()
  1513. if lower.endswith(".gcode"):
  1514. return Response(content=data, media_type="text/plain")
  1515. if lower.endswith(".3mf"):
  1516. try:
  1517. with zipfile.ZipFile(io.BytesIO(data), "r") as zf:
  1518. gcode_files = [n for n in zf.namelist() if n.endswith(".gcode")]
  1519. if not gcode_files:
  1520. raise HTTPException(status_code=404, detail="No gcode found in 3MF file")
  1521. gcode_content = zf.read(gcode_files[0])
  1522. return Response(content=gcode_content, media_type="text/plain")
  1523. except zipfile.BadZipFile:
  1524. raise HTTPException(status_code=400, detail="Invalid 3MF file")
  1525. raise HTTPException(status_code=400, detail="Unsupported file type")
  1526. @router.get("/{printer_id}/files/plates")
  1527. async def get_printer_file_plates(
  1528. printer_id: int,
  1529. path: str = Query(..., description="Full path to the 3MF file on the printer"),
  1530. _=RequirePrinterPermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  1531. ):
  1532. """Get available plates from a multi-plate 3MF file stored on a printer."""
  1533. import io
  1534. import json
  1535. import defusedxml.ElementTree as ET
  1536. printer = await _load_printer_or_404(printer_id)
  1537. filename = path.split("/")[-1]
  1538. if not filename.lower().endswith(".3mf"):
  1539. return {
  1540. "printer_id": printer_id,
  1541. "path": path,
  1542. "filename": filename,
  1543. "plates": [],
  1544. "is_multi_plate": False,
  1545. }
  1546. data = await download_file_bytes_async(printer.ip_address, printer.access_code, path, printer_model=printer.model)
  1547. if data is None:
  1548. raise HTTPException(404, f"File not found: {path}")
  1549. plates = []
  1550. try:
  1551. with zipfile.ZipFile(io.BytesIO(data), "r") as zf:
  1552. namelist = zf.namelist()
  1553. # Find all plate gcode files to determine available plates
  1554. gcode_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".gcode")]
  1555. # If no gcode is present (source-only or unsliced), fall back to plate JSON/PNG
  1556. plate_indices: list[int] = []
  1557. if gcode_files:
  1558. for gf in gcode_files:
  1559. try:
  1560. plate_str = gf[15:-6] # Remove "Metadata/plate_" and ".gcode"
  1561. plate_indices.append(int(plate_str))
  1562. except ValueError:
  1563. pass # Skip gcode files with non-numeric plate indices
  1564. else:
  1565. plate_json_files = [n for n in namelist if n.startswith("Metadata/plate_") and n.endswith(".json")]
  1566. plate_png_files = [
  1567. n
  1568. for n in namelist
  1569. if n.startswith("Metadata/plate_")
  1570. and n.endswith(".png")
  1571. and "_small" not in n
  1572. and "no_light" not in n
  1573. ]
  1574. plate_name_candidates = plate_json_files + plate_png_files
  1575. plate_re = re.compile(r"^Metadata/plate_(\d+)\.(json|png)$")
  1576. seen_indices: set[int] = set()
  1577. for name in plate_name_candidates:
  1578. match = plate_re.match(name)
  1579. if match:
  1580. try:
  1581. index = int(match.group(1))
  1582. except ValueError:
  1583. continue
  1584. if index in seen_indices:
  1585. continue
  1586. seen_indices.add(index)
  1587. plate_indices.append(index)
  1588. if not plate_indices:
  1589. return {
  1590. "printer_id": printer_id,
  1591. "path": path,
  1592. "filename": filename,
  1593. "plates": [],
  1594. "is_multi_plate": False,
  1595. }
  1596. plate_indices.sort()
  1597. # Parse model_settings.config for plate names
  1598. plate_names = {}
  1599. if "Metadata/model_settings.config" in namelist:
  1600. try:
  1601. model_content = zf.read("Metadata/model_settings.config").decode()
  1602. model_root = ET.fromstring(model_content)
  1603. for plate_elem in model_root.findall(".//plate"):
  1604. plater_id = None
  1605. plater_name = None
  1606. for meta in plate_elem.findall("metadata"):
  1607. key = meta.get("key")
  1608. value = meta.get("value")
  1609. if key == "plater_id" and value:
  1610. try:
  1611. plater_id = int(value)
  1612. except ValueError:
  1613. pass # Skip plate with unparseable ID
  1614. elif key == "plater_name" and value:
  1615. plater_name = value.strip()
  1616. if plater_id is not None and plater_name:
  1617. plate_names[plater_id] = plater_name
  1618. except Exception:
  1619. pass # Plate names are optional; continue without them
  1620. # Parse slice_info.config for plate metadata
  1621. plate_metadata = {}
  1622. if "Metadata/slice_info.config" in namelist:
  1623. content = zf.read("Metadata/slice_info.config").decode()
  1624. root = ET.fromstring(content)
  1625. for plate_elem in root.findall(".//plate"):
  1626. plate_info = {"filaments": [], "prediction": None, "weight": None, "name": None, "objects": []}
  1627. plate_index = None
  1628. for meta in plate_elem.findall("metadata"):
  1629. key = meta.get("key")
  1630. value = meta.get("value")
  1631. if key == "index" and value:
  1632. try:
  1633. plate_index = int(value)
  1634. except ValueError:
  1635. pass # Skip plate with unparseable index
  1636. elif key == "prediction" and value:
  1637. try:
  1638. plate_info["prediction"] = int(value)
  1639. except ValueError:
  1640. pass # Skip unparseable prediction; leave as None
  1641. elif key == "weight" and value:
  1642. try:
  1643. plate_info["weight"] = float(value)
  1644. except ValueError:
  1645. pass # Skip unparseable weight; leave as None
  1646. # Get filaments used in this plate
  1647. for filament_elem in plate_elem.findall("filament"):
  1648. filament_id = filament_elem.get("id")
  1649. filament_type = filament_elem.get("type", "")
  1650. filament_color = filament_elem.get("color", "")
  1651. used_g = filament_elem.get("used_g", "0")
  1652. used_m = filament_elem.get("used_m", "0")
  1653. try:
  1654. used_grams = float(used_g)
  1655. except (ValueError, TypeError):
  1656. used_grams = 0
  1657. if used_grams > 0 and filament_id:
  1658. plate_info["filaments"].append(
  1659. {
  1660. "slot_id": int(filament_id),
  1661. "type": filament_type,
  1662. "color": filament_color,
  1663. "used_grams": round(used_grams, 1),
  1664. "used_meters": float(used_m) if used_m else 0,
  1665. }
  1666. )
  1667. plate_info["filaments"].sort(key=lambda x: x["slot_id"])
  1668. # Collect object names
  1669. for obj_elem in plate_elem.findall("object"):
  1670. obj_name = obj_elem.get("name")
  1671. if obj_name and obj_name not in plate_info["objects"]:
  1672. plate_info["objects"].append(obj_name)
  1673. # Set plate name
  1674. if plate_index is not None:
  1675. custom_name = plate_names.get(plate_index)
  1676. if custom_name:
  1677. plate_info["name"] = custom_name
  1678. elif plate_info["objects"]:
  1679. plate_info["name"] = plate_info["objects"][0]
  1680. plate_metadata[plate_index] = plate_info
  1681. # Parse plate_*.json for object lists when slice_info is missing
  1682. plate_json_objects: dict[int, list[str]] = {}
  1683. for name in namelist:
  1684. match = re.match(r"^Metadata/plate_(\d+)\.json$", name)
  1685. if not match:
  1686. continue
  1687. try:
  1688. plate_index = int(match.group(1))
  1689. except ValueError:
  1690. continue
  1691. try:
  1692. payload = json.loads(zf.read(name).decode())
  1693. bbox_objects = payload.get("bbox_objects", [])
  1694. names: list[str] = []
  1695. for obj in bbox_objects:
  1696. obj_name = obj.get("name") if isinstance(obj, dict) else None
  1697. if obj_name and obj_name not in names:
  1698. names.append(obj_name)
  1699. if names:
  1700. plate_json_objects[plate_index] = names
  1701. except Exception:
  1702. continue
  1703. # Build plate list
  1704. for idx in plate_indices:
  1705. meta = plate_metadata.get(idx, {})
  1706. has_thumbnail = f"Metadata/plate_{idx}.png" in namelist
  1707. objects = meta.get("objects", [])
  1708. if not objects:
  1709. objects = plate_json_objects.get(idx, [])
  1710. plate_name = meta.get("name")
  1711. if not plate_name:
  1712. plate_name = plate_names.get(idx)
  1713. if not plate_name and objects:
  1714. plate_name = objects[0]
  1715. plates.append(
  1716. {
  1717. "index": idx,
  1718. "name": plate_name,
  1719. "objects": objects,
  1720. "object_count": len(objects),
  1721. "has_thumbnail": has_thumbnail,
  1722. "thumbnail_url": f"/api/v1/printers/{printer_id}/files/plate-thumbnail/{idx}?path={path}",
  1723. "print_time_seconds": meta.get("prediction"),
  1724. "filament_used_grams": meta.get("weight"),
  1725. "filaments": meta.get("filaments", []),
  1726. }
  1727. )
  1728. except Exception as e:
  1729. logger.warning("Failed to parse plates from printer file %s: %s", path, e)
  1730. return {
  1731. "printer_id": printer_id,
  1732. "path": path,
  1733. "filename": filename,
  1734. "plates": plates,
  1735. "is_multi_plate": len(plates) > 1,
  1736. }
  1737. @router.get("/{printer_id}/files/plate-thumbnail/{plate_index}")
  1738. async def get_printer_file_plate_thumbnail(
  1739. printer_id: int,
  1740. plate_index: int,
  1741. path: str = Query(..., description="Full path to the 3MF file on the printer"),
  1742. _=RequirePrinterPermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  1743. ):
  1744. """Get a plate thumbnail image from a printer-stored 3MF file."""
  1745. import io
  1746. printer = await _load_printer_or_404(printer_id)
  1747. data = await download_file_bytes_async(printer.ip_address, printer.access_code, path, printer_model=printer.model)
  1748. if data is None:
  1749. raise HTTPException(404, f"File not found: {path}")
  1750. try:
  1751. with zipfile.ZipFile(io.BytesIO(data), "r") as zf:
  1752. thumb_path = f"Metadata/plate_{plate_index}.png"
  1753. if thumb_path in zf.namelist():
  1754. image_data = zf.read(thumb_path)
  1755. return Response(content=image_data, media_type="image/png")
  1756. except Exception:
  1757. pass # Corrupt or unreadable 3MF; fall through to 404
  1758. raise HTTPException(status_code=404, detail=f"Thumbnail for plate {plate_index} not found")
  1759. @router.post("/{printer_id}/files/download-zip")
  1760. async def download_printer_files_as_zip(
  1761. printer_id: int,
  1762. request: PrinterFilesDownloadRequest,
  1763. _=RequirePrinterPermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  1764. ):
  1765. """Download multiple files using a disk-backed ZIP.
  1766. Kept backward-compatible for API clients: relative paths are rooted,
  1767. duplicate paths receive collision-safe names, and an all-failed request
  1768. returns an empty ZIP as the historical endpoint did. The browser uses the
  1769. asynchronous preparation endpoints below.
  1770. """
  1771. if not request.paths:
  1772. raise HTTPException(400, "No files specified")
  1773. printer = await _load_printer_or_404(printer_id)
  1774. normalized_paths = [path if path.startswith("/") else f"/{path}" for path in request.paths]
  1775. normalized_sizes = {path if path.startswith("/") else f"/{path}": size for path, size in request.sizes.items()}
  1776. try:
  1777. async with asyncio.timeout(MAX_PRINTER_ZIP_PREPARE_SECONDS):
  1778. result = await build_printer_files_zip(
  1779. printer,
  1780. normalized_paths,
  1781. normalized_sizes,
  1782. preserve_paths=False,
  1783. allow_empty=True,
  1784. )
  1785. except PrinterFilesZipTooLargeError as exc:
  1786. raise HTTPException(413, str(exc)) from exc
  1787. except PrinterFilesZipInsufficientSpaceError as exc:
  1788. raise HTTPException(507, str(exc)) from exc
  1789. except TimeoutError as exc:
  1790. raise HTTPException(504, "Printer ZIP preparation exceeded the 30-minute limit") from exc
  1791. return FileResponse(
  1792. path=result.path,
  1793. filename="printer-files.zip",
  1794. media_type="application/zip",
  1795. headers={
  1796. "X-Bambuddy-Files-Requested": str(result.requested),
  1797. "X-Bambuddy-Files-Downloaded": str(result.successful),
  1798. "X-Bambuddy-Files-Failed": str(len(result.failed_paths)),
  1799. },
  1800. background=BackgroundTask(remove_printer_files_zip, result.path),
  1801. )
  1802. @router.post("/{printer_id}/files/download-job")
  1803. async def create_printer_files_download_job(
  1804. printer_id: int,
  1805. request: PrinterFilesJobRequest,
  1806. _=RequirePrinterPermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  1807. ):
  1808. """Start a cancellable disk-backed preparation without holding the request."""
  1809. if not request.paths:
  1810. raise HTTPException(400, "No files specified")
  1811. if len(set(request.paths)) != len(request.paths):
  1812. raise HTTPException(400, "Selected printer paths must be unique")
  1813. if not request.as_zip and len(request.paths) != 1:
  1814. raise HTTPException(400, "Native downloads require exactly one file")
  1815. printer = await _load_printer_or_404(printer_id)
  1816. try:
  1817. status = await start_printer_files_job(
  1818. printer,
  1819. request.paths,
  1820. request.sizes,
  1821. request.filename,
  1822. as_zip=request.as_zip,
  1823. )
  1824. except PrinterFilesZipTooLargeError as exc:
  1825. raise HTTPException(413, str(exc)) from exc
  1826. except PrinterFilesZipInsufficientSpaceError as exc:
  1827. raise HTTPException(507, str(exc)) from exc
  1828. except ValueError as exc:
  1829. raise HTTPException(400, str(exc)) from exc
  1830. return status.__dict__
  1831. @router.get("/{printer_id}/files/download-jobs/{job_id}")
  1832. async def get_printer_files_download_job(
  1833. printer_id: int,
  1834. job_id: str,
  1835. _=RequirePrinterPermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  1836. ):
  1837. status = await get_printer_files_job(job_id, printer_id)
  1838. if status is None:
  1839. raise HTTPException(404, "Printer download job not found")
  1840. return status.__dict__
  1841. @router.delete("/{printer_id}/files/download-jobs/{job_id}")
  1842. async def cancel_printer_files_download_job(
  1843. printer_id: int,
  1844. job_id: str,
  1845. _=RequirePrinterPermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  1846. ):
  1847. if not await cancel_printer_files_job(job_id, printer_id):
  1848. raise HTTPException(404, "Printer download job not found")
  1849. return {"status": "cancelled"}
  1850. @router.get("/{printer_id}/files/dl/{token}/{filename}")
  1851. async def download_prepared_printer_files(
  1852. printer_id: int,
  1853. token: str,
  1854. filename: str,
  1855. ):
  1856. """Consume a resource-bound token and stream a prepared file natively."""
  1857. from backend.app.core.auth import verify_slicer_download_token
  1858. if not await verify_slicer_download_token(token, "printer-files", printer_id):
  1859. return download_error_response(403, "This download link has already been used or has expired.")
  1860. zip_path = printer_files_zip_path(printer_id, token)
  1861. raw_path = printer_file_path(printer_id, token)
  1862. if zip_path is not None and await asyncio.to_thread(zip_path.is_file):
  1863. prepared_path = zip_path
  1864. media_type = "application/zip"
  1865. elif raw_path is not None and await asyncio.to_thread(raw_path.is_file):
  1866. prepared_path = raw_path
  1867. media_type = "application/octet-stream"
  1868. else:
  1869. return download_error_response(404, "The prepared download is no longer on the server.")
  1870. safe_filename = safe_download_filename(filename, fallback="printer-download")
  1871. return FileResponse(
  1872. path=prepared_path,
  1873. filename=safe_filename,
  1874. media_type=media_type,
  1875. headers={"Content-Disposition": build_content_disposition(safe_filename)},
  1876. background=BackgroundTask(remove_printer_files_zip, prepared_path),
  1877. )
  1878. @router.delete("/{printer_id}/files")
  1879. async def delete_printer_file(
  1880. printer_id: int,
  1881. path: str,
  1882. _=RequirePrinterPermissionIfAuthEnabled(Permission.PRINTERS_FILES),
  1883. ):
  1884. """Delete a file from the printer."""
  1885. printer = await _load_printer_or_404(printer_id)
  1886. from backend.app.services.bambu_ftp import DeleteResult
  1887. result = await delete_file_async(printer.ip_address, printer.access_code, path, printer_model=printer.model)
  1888. if result == DeleteResult.NOT_FOUND:
  1889. raise HTTPException(404, f"File not found on printer: {path}")
  1890. if result == DeleteResult.FAILED:
  1891. raise HTTPException(500, f"Failed to delete file: {path}")
  1892. return {"status": "deleted", "path": path}
  1893. @router.get("/{printer_id}/storage")
  1894. async def get_printer_storage(
  1895. printer_id: int,
  1896. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  1897. ):
  1898. """Get storage information from the printer."""
  1899. printer = await _load_printer_or_404(printer_id)
  1900. storage_info = await get_storage_info_async(printer.ip_address, printer.access_code, printer_model=printer.model)
  1901. return storage_info or {"used_bytes": None, "free_bytes": None}
  1902. # ============================================
  1903. # MQTT Debug Logging Endpoints
  1904. # ============================================
  1905. @router.post("/{printer_id}/logging/enable")
  1906. async def enable_mqtt_logging(
  1907. printer_id: int,
  1908. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1909. db: AsyncSession = Depends(get_db),
  1910. ):
  1911. """Enable MQTT message logging for a printer."""
  1912. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1913. printer = result.scalar_one_or_none()
  1914. if not printer:
  1915. raise HTTPException(404, "Printer not found")
  1916. success = printer_manager.enable_logging(printer_id, True)
  1917. if not success:
  1918. raise HTTPException(400, "Printer not connected")
  1919. return {"logging_enabled": True}
  1920. @router.post("/{printer_id}/logging/disable")
  1921. async def disable_mqtt_logging(
  1922. printer_id: int,
  1923. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1924. db: AsyncSession = Depends(get_db),
  1925. ):
  1926. """Disable MQTT message logging for a printer."""
  1927. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1928. printer = result.scalar_one_or_none()
  1929. if not printer:
  1930. raise HTTPException(404, "Printer not found")
  1931. success = printer_manager.enable_logging(printer_id, False)
  1932. if not success:
  1933. raise HTTPException(400, "Printer not connected")
  1934. return {"logging_enabled": False}
  1935. @router.get("/{printer_id}/logging")
  1936. async def get_mqtt_logs(
  1937. printer_id: int,
  1938. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  1939. db: AsyncSession = Depends(get_db),
  1940. ):
  1941. """Get MQTT message logs for a printer."""
  1942. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1943. printer = result.scalar_one_or_none()
  1944. if not printer:
  1945. raise HTTPException(404, "Printer not found")
  1946. logs = printer_manager.get_logs(printer_id)
  1947. return {
  1948. "logging_enabled": printer_manager.is_logging_enabled(printer_id),
  1949. "logs": [
  1950. {
  1951. "timestamp": log.timestamp,
  1952. "topic": log.topic,
  1953. "direction": log.direction,
  1954. "payload": log.payload,
  1955. }
  1956. for log in logs
  1957. ],
  1958. }
  1959. @router.delete("/{printer_id}/logging")
  1960. async def clear_mqtt_logs(
  1961. printer_id: int,
  1962. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1963. db: AsyncSession = Depends(get_db),
  1964. ):
  1965. """Clear MQTT message logs for a printer."""
  1966. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1967. printer = result.scalar_one_or_none()
  1968. if not printer:
  1969. raise HTTPException(404, "Printer not found")
  1970. printer_manager.clear_logs(printer_id)
  1971. return {"status": "cleared"}
  1972. # ============================================
  1973. # AMS Drying Endpoints
  1974. # ============================================
  1975. # The P1 firmware acks `ams_filament_drying` with result: success and then ignores it
  1976. # — Bambu's own P1 manual says drying "may only be controlled from the P1S screen"
  1977. # (#2533). Refuse the command rather than let the caller believe it landed.
  1978. _DRYING_SCREEN_ONLY_DETAIL = drying_preflight.SCREEN_ONLY_DETAIL
  1979. @router.post("/{printer_id}/drying/start")
  1980. async def start_drying(
  1981. printer_id: int,
  1982. ams_id: int,
  1983. temp: int = 45,
  1984. duration: int = 4,
  1985. filament: str = "",
  1986. rotate_tray: bool = False,
  1987. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  1988. db: AsyncSession = Depends(get_db),
  1989. ):
  1990. """Send AMS drying start command. temp=45-85, duration=hours."""
  1991. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  1992. printer = result.scalar_one_or_none()
  1993. if not printer:
  1994. raise HTTPException(404, "Printer not found")
  1995. # Server-side guard: reject if this model/firmware doesn't support drying
  1996. live_state = printer_manager.get_status(printer_id)
  1997. firmware = live_state.firmware_version if live_state else None
  1998. unsupported = drying_preflight.check_drying_supported(printer.model, firmware)
  1999. if unsupported:
  2000. raise HTTPException(400, unsupported)
  2001. if temp < 45 or temp > 85:
  2002. raise HTTPException(400, "Temperature must be 45-85°C")
  2003. if duration < 1 or duration > 24:
  2004. raise HTTPException(400, "Duration must be 1-24 hours")
  2005. # Inspect the live AMS unit: surface blocking dry_sf_reasons (otherwise the
  2006. # firmware silently ignores the command — #971) and backfill an empty
  2007. # filament field from the first loaded tray so the printer doesn't reject
  2008. # the payload.
  2009. target_ams = drying_preflight.find_ams_unit(live_state, ams_id)
  2010. blocking = drying_preflight.blocking_reason_codes(target_ams)
  2011. if blocking:
  2012. # Same pick the scheduled path makes, so both describe one blocked AMS
  2013. # the same way rather than differing on which code the firmware listed
  2014. # first.
  2015. raise HTTPException(
  2016. 409, drying_preflight.DRY_SF_REASON_MESSAGES[drying_preflight.primary_reason_code(blocking)]
  2017. )
  2018. filament = drying_preflight.resolve_filament(target_ams, filament)
  2019. success = printer_manager.send_drying_command(
  2020. printer_id, ams_id, temp, duration, mode=1, filament=filament, rotate_tray=rotate_tray
  2021. )
  2022. if not success:
  2023. raise HTTPException(400, "Printer not connected")
  2024. return {"status": "drying_started", "ams_id": ams_id, "temp": temp, "duration": duration}
  2025. @router.post("/{printer_id}/drying/stop")
  2026. async def stop_drying(
  2027. printer_id: int,
  2028. ams_id: int,
  2029. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  2030. db: AsyncSession = Depends(get_db),
  2031. ):
  2032. """Send AMS drying stop command."""
  2033. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2034. printer = result.scalar_one_or_none()
  2035. if not printer:
  2036. raise HTTPException(404, "Printer not found")
  2037. # Screen-only models ignore stop just as they ignore start — a cycle running on a
  2038. # P1S was started at the printer and has to be ended there too (#2533).
  2039. if drying_screen_only(printer.model):
  2040. raise HTTPException(400, _DRYING_SCREEN_ONLY_DETAIL)
  2041. success = printer_manager.send_drying_command(printer_id, ams_id, temp=0, duration=0, mode=0)
  2042. if not success:
  2043. raise HTTPException(400, "Printer not connected")
  2044. # A cycle the user stopped by hand tells us nothing about whether drying can
  2045. # move the humidity reading, so it must not count towards the auto-drying
  2046. # suspension (#2770). Imported here rather than at module scope to keep the
  2047. # existing routes/scheduler import direction.
  2048. from backend.app.services.print_scheduler import scheduler as print_scheduler
  2049. print_scheduler.forget_auto_dry_cycle(printer_id, ams_id)
  2050. return {"status": "drying_stopped", "ams_id": ams_id}
  2051. # ============================================
  2052. # Print Options (AI Detection) Endpoints
  2053. # ============================================
  2054. @router.post("/{printer_id}/print-options")
  2055. async def set_print_option(
  2056. printer_id: int,
  2057. module_name: str,
  2058. enabled: bool,
  2059. print_halt: bool = True,
  2060. sensitivity: str = "medium",
  2061. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  2062. db: AsyncSession = Depends(get_db),
  2063. ):
  2064. """Set an AI detection / print option on the printer.
  2065. Valid module_name values:
  2066. - spaghetti_detector: Spaghetti detection
  2067. - first_layer_inspector: First layer inspection
  2068. - printing_monitor: AI print quality monitoring
  2069. - buildplate_marker_detector: Build plate marker detection
  2070. - allow_skip_parts: Allow skipping failed parts
  2071. """
  2072. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2073. printer = result.scalar_one_or_none()
  2074. if not printer:
  2075. raise HTTPException(404, "Printer not found")
  2076. client = printer_manager.get_client(printer_id)
  2077. if not client or not client.state.connected:
  2078. raise HTTPException(400, "Printer not connected")
  2079. # Validate module_name
  2080. valid_modules = [
  2081. "spaghetti_detector",
  2082. "first_layer_inspector",
  2083. "printing_monitor",
  2084. "buildplate_marker_detector",
  2085. "allow_skip_parts",
  2086. "pileup_detector",
  2087. "clump_detector",
  2088. "airprint_detector",
  2089. "auto_recovery_step_loss",
  2090. ]
  2091. if module_name not in valid_modules:
  2092. raise HTTPException(400, f"Invalid module_name. Must be one of: {valid_modules}")
  2093. # Validate sensitivity
  2094. valid_sensitivities = ["low", "medium", "high", "never_halt"]
  2095. if sensitivity not in valid_sensitivities:
  2096. raise HTTPException(400, f"Invalid sensitivity. Must be one of: {valid_sensitivities}")
  2097. success = client.set_xcam_option(
  2098. module_name=module_name,
  2099. enabled=enabled,
  2100. print_halt=print_halt,
  2101. sensitivity=sensitivity,
  2102. )
  2103. if not success:
  2104. raise HTTPException(500, "Failed to send command to printer")
  2105. return {
  2106. "success": True,
  2107. "module_name": module_name,
  2108. "enabled": enabled,
  2109. "print_halt": print_halt,
  2110. "sensitivity": sensitivity,
  2111. }
  2112. @router.post("/{printer_id}/ams-backup")
  2113. async def set_ams_backup(
  2114. printer_id: int,
  2115. enabled: bool,
  2116. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  2117. db: AsyncSession = Depends(get_db),
  2118. ):
  2119. """Toggle AMS Filament Backup (auto-switch to a backup spool when one runs out)."""
  2120. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2121. printer = result.scalar_one_or_none()
  2122. if not printer:
  2123. raise HTTPException(404, "Printer not found")
  2124. client = printer_manager.get_client(printer_id)
  2125. if not client or not client.state.connected:
  2126. raise HTTPException(400, "Printer not connected")
  2127. success = client.set_ams_filament_backup(enabled)
  2128. if not success:
  2129. raise HTTPException(500, "Failed to send command to printer")
  2130. return {"success": True, "ams_filament_backup": enabled}
  2131. @router.get("/{printer_id}/inventory-remain")
  2132. async def get_inventory_remain(
  2133. printer_id: int,
  2134. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  2135. db: AsyncSession = Depends(get_db),
  2136. ):
  2137. """Per-globalTrayId remaining grams for slots bound to an inventory spool.
  2138. Mirrors `_build_inventory_remain_overrides` server-side so the PrintModal
  2139. client can apply the same two-tier "Prefer Lowest Remaining Filament" sort
  2140. the dispatcher uses (#1766). Works for both internal inventory and
  2141. Spoolman; unbound slots are absent from the map (client falls back to the
  2142. printer's MQTT `remain` for those).
  2143. `slot_materials` carries the same bindings with their material identity and
  2144. extruder side attached, which is what the modal's pre-flight filament check
  2145. needs to pool spools under AMS Filament Backup the way the dispatcher does.
  2146. It is deliberately server-computed: the identity rule lives in
  2147. `filament_deficit`, and a client-side reimplementation of it is exactly how
  2148. the modal came to block prints the dispatcher would have accepted. Unlike
  2149. `inventory_remain_g` it covers every binding, not just currently-loaded
  2150. slots — again matching what the dispatcher pools.
  2151. """
  2152. from backend.app.services.filament_deficit import build_slot_materials
  2153. from backend.app.services.print_scheduler import PrintScheduler
  2154. state = printer_manager.get_status(printer_id)
  2155. if not state:
  2156. return {"inventory_remain_g": {}, "slot_materials": []}
  2157. scheduler = PrintScheduler()
  2158. loaded = scheduler._build_loaded_filaments(state)
  2159. overrides = await scheduler._build_inventory_remain_overrides(db, printer_id, loaded)
  2160. slot_materials = await build_slot_materials(db, printer_id)
  2161. return {
  2162. "inventory_remain_g": {str(k): v for k, v in overrides.items()},
  2163. "slot_materials": [s.to_dict() for s in slot_materials],
  2164. }
  2165. # ============================================
  2166. # Calibration
  2167. # ============================================
  2168. @router.post("/{printer_id}/calibration")
  2169. async def start_calibration(
  2170. printer_id: int,
  2171. bed_leveling: bool = False,
  2172. vibration: bool = False,
  2173. motor_noise: bool = False,
  2174. nozzle_offset: bool = False,
  2175. high_temp_heatbed: bool = False,
  2176. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  2177. db: AsyncSession = Depends(get_db),
  2178. ):
  2179. """Start printer calibration with selected options.
  2180. At least one option must be selected.
  2181. Options:
  2182. - bed_leveling: Run bed leveling calibration
  2183. - vibration: Run vibration compensation calibration
  2184. - motor_noise: Run motor noise cancellation calibration
  2185. - nozzle_offset: Run nozzle offset calibration (dual nozzle printers)
  2186. - high_temp_heatbed: Run high-temperature heatbed calibration
  2187. """
  2188. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2189. printer = result.scalar_one_or_none()
  2190. if not printer:
  2191. raise HTTPException(404, "Printer not found")
  2192. client = printer_manager.get_client(printer_id)
  2193. if not client or not client.state.connected:
  2194. raise HTTPException(400, "Printer not connected")
  2195. # Check that at least one option is selected
  2196. if not any([bed_leveling, vibration, motor_noise, nozzle_offset, high_temp_heatbed]):
  2197. raise HTTPException(400, "At least one calibration option must be selected")
  2198. success = client.start_calibration(
  2199. bed_leveling=bed_leveling,
  2200. vibration=vibration,
  2201. motor_noise=motor_noise,
  2202. nozzle_offset=nozzle_offset,
  2203. high_temp_heatbed=high_temp_heatbed,
  2204. )
  2205. if not success:
  2206. raise HTTPException(500, "Failed to send calibration command to printer")
  2207. return {
  2208. "success": True,
  2209. "bed_leveling": bed_leveling,
  2210. "vibration": vibration,
  2211. "motor_noise": motor_noise,
  2212. "nozzle_offset": nozzle_offset,
  2213. "high_temp_heatbed": high_temp_heatbed,
  2214. }
  2215. # ============================================================================
  2216. # Slot Preset Mapping Endpoints
  2217. # ============================================================================
  2218. def _slot_preset_key(ams_id: int, tray_id: int) -> int:
  2219. # Mirrors frontend getGlobalTrayId (amsHelpers.ts): AMS-HT (128-135) is keyed
  2220. # by ams_id since each unit has a single slot and shares its global ID with
  2221. # the unit itself. Regular AMS and external (255) use ams_id*4+tray_id.
  2222. if 128 <= ams_id <= 135:
  2223. return ams_id
  2224. return ams_id * 4 + tray_id
  2225. @router.get("/{printer_id}/slot-presets")
  2226. async def get_slot_presets(
  2227. printer_id: int,
  2228. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  2229. db: AsyncSession = Depends(get_db),
  2230. ):
  2231. """Get all saved slot-to-preset mappings for a printer."""
  2232. result = await db.execute(select(SlotPresetMapping).where(SlotPresetMapping.printer_id == printer_id))
  2233. mappings = result.scalars().all()
  2234. return {
  2235. _slot_preset_key(mapping.ams_id, mapping.tray_id): {
  2236. "ams_id": mapping.ams_id,
  2237. "tray_id": mapping.tray_id,
  2238. "preset_id": mapping.preset_id,
  2239. "preset_name": mapping.preset_name,
  2240. }
  2241. for mapping in mappings
  2242. }
  2243. @router.get("/{printer_id}/slot-presets/{ams_id}/{tray_id}")
  2244. async def get_slot_preset(
  2245. printer_id: int,
  2246. ams_id: int,
  2247. tray_id: int,
  2248. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  2249. db: AsyncSession = Depends(get_db),
  2250. ):
  2251. """Get the saved preset for a specific slot."""
  2252. result = await db.execute(
  2253. select(SlotPresetMapping).where(
  2254. SlotPresetMapping.printer_id == printer_id,
  2255. SlotPresetMapping.ams_id == ams_id,
  2256. SlotPresetMapping.tray_id == tray_id,
  2257. )
  2258. )
  2259. mapping = result.scalar_one_or_none()
  2260. if not mapping:
  2261. return None
  2262. return {
  2263. "ams_id": mapping.ams_id,
  2264. "tray_id": mapping.tray_id,
  2265. "preset_id": mapping.preset_id,
  2266. "preset_name": mapping.preset_name,
  2267. }
  2268. @router.put("/{printer_id}/slot-presets/{ams_id}/{tray_id}")
  2269. async def save_slot_preset(
  2270. printer_id: int,
  2271. ams_id: int,
  2272. tray_id: int,
  2273. preset_id: str,
  2274. preset_name: str,
  2275. preset_source: str = "cloud",
  2276. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_UPDATE),
  2277. db: AsyncSession = Depends(get_db),
  2278. ):
  2279. """Save a preset mapping for a specific slot."""
  2280. # Check printer exists
  2281. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2282. if not result.scalar_one_or_none():
  2283. raise HTTPException(404, "Printer not found")
  2284. # Check for existing mapping
  2285. result = await db.execute(
  2286. select(SlotPresetMapping).where(
  2287. SlotPresetMapping.printer_id == printer_id,
  2288. SlotPresetMapping.ams_id == ams_id,
  2289. SlotPresetMapping.tray_id == tray_id,
  2290. )
  2291. )
  2292. mapping = result.scalar_one_or_none()
  2293. if mapping:
  2294. # Update existing
  2295. mapping.preset_id = preset_id
  2296. mapping.preset_name = preset_name
  2297. mapping.preset_source = preset_source
  2298. else:
  2299. # Create new
  2300. mapping = SlotPresetMapping(
  2301. printer_id=printer_id,
  2302. ams_id=ams_id,
  2303. tray_id=tray_id,
  2304. preset_id=preset_id,
  2305. preset_name=preset_name,
  2306. preset_source=preset_source,
  2307. )
  2308. db.add(mapping)
  2309. await db.commit()
  2310. await db.refresh(mapping)
  2311. return {
  2312. "ams_id": mapping.ams_id,
  2313. "tray_id": mapping.tray_id,
  2314. "preset_id": mapping.preset_id,
  2315. "preset_name": mapping.preset_name,
  2316. "preset_source": mapping.preset_source,
  2317. }
  2318. @router.delete("/{printer_id}/slot-presets/{ams_id}/{tray_id}")
  2319. async def delete_slot_preset(
  2320. printer_id: int,
  2321. ams_id: int,
  2322. tray_id: int,
  2323. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_UPDATE),
  2324. db: AsyncSession = Depends(get_db),
  2325. ):
  2326. """Delete a saved preset mapping for a slot."""
  2327. result = await db.execute(
  2328. select(SlotPresetMapping).where(
  2329. SlotPresetMapping.printer_id == printer_id,
  2330. SlotPresetMapping.ams_id == ams_id,
  2331. SlotPresetMapping.tray_id == tray_id,
  2332. )
  2333. )
  2334. mapping = result.scalar_one_or_none()
  2335. if mapping:
  2336. await db.delete(mapping)
  2337. await db.commit()
  2338. return {"success": True}
  2339. @router.get("/{printer_id}/slots/{ams_id}/{tray_id}/spool-defaults")
  2340. async def get_slot_spool_defaults(
  2341. printer_id: int,
  2342. ams_id: int,
  2343. tray_id: int,
  2344. db: AsyncSession = Depends(get_db),
  2345. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  2346. ):
  2347. """What the spool assigned to this slot is configured to use here.
  2348. The Configure AMS Slot dialog opens on a slot that usually already holds an
  2349. assigned spool, and that spool carries a filament preset per printer model
  2350. and a K profile per hotend. Without this the dialog offered defaults derived
  2351. from the slot's last manual configuration or from the tray's RFID data --
  2352. ignoring the very values the spool was configured with, on the one screen
  2353. that looks like it exists for them.
  2354. Everything is resolved for the nozzle THIS slot feeds, so a dual-nozzle
  2355. machine gets the answer for the correct hotend. Returns nulls rather than a
  2356. 404 when the slot holds no known spool: "nothing configured" is an ordinary
  2357. answer here and the dialog falls back to what it did before.
  2358. """
  2359. from backend.app.models.spool import Spool
  2360. from backend.app.models.spool_assignment import SpoolAssignment
  2361. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2362. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2363. from backend.app.services.slot_kprofile import find_slot_kprofile_for_extruder
  2364. from backend.app.services.slot_nozzle import resolve_slot_nozzle
  2365. from backend.app.services.spool_filament_preset import resolve_spool_preset, resolve_spoolman_preset
  2366. state = printer_manager.get_status(printer_id)
  2367. model = printer_manager.get_model(printer_id)
  2368. slot_nozzle = resolve_slot_nozzle(state, ams_id, tray_id, model)
  2369. profile = await find_slot_kprofile_for_extruder(
  2370. db,
  2371. printer_id,
  2372. ams_id,
  2373. tray_id,
  2374. slot_nozzle.extruder_or_default,
  2375. slot_nozzle.diameter,
  2376. model,
  2377. slot_nozzle.flow,
  2378. )
  2379. slicer_filament: str | None = None
  2380. slicer_filament_name: str | None = None
  2381. spoolman_mode = await spoolman_owns_assignments(db)
  2382. if spoolman_mode:
  2383. sm_assignment = (
  2384. await db.execute(
  2385. select(SpoolmanSlotAssignment).where(
  2386. SpoolmanSlotAssignment.printer_id == printer_id,
  2387. SpoolmanSlotAssignment.ams_id == ams_id,
  2388. SpoolmanSlotAssignment.tray_id == tray_id,
  2389. )
  2390. )
  2391. ).scalar_one_or_none()
  2392. if sm_assignment is not None:
  2393. slicer_filament, slicer_filament_name = await resolve_spoolman_preset(
  2394. db,
  2395. spoolman_spool_id=sm_assignment.spoolman_spool_id,
  2396. printer_model=model,
  2397. nozzle_diameter=slot_nozzle.diameter,
  2398. fallback_filament=None,
  2399. fallback_name=None,
  2400. )
  2401. else:
  2402. assignment = (
  2403. await db.execute(
  2404. select(SpoolAssignment).where(
  2405. SpoolAssignment.printer_id == printer_id,
  2406. SpoolAssignment.ams_id == ams_id,
  2407. SpoolAssignment.tray_id == tray_id,
  2408. )
  2409. )
  2410. ).scalar_one_or_none()
  2411. if assignment is not None:
  2412. spool = (await db.execute(select(Spool).where(Spool.id == assignment.spool_id))).scalar_one_or_none()
  2413. if spool is not None:
  2414. slicer_filament, slicer_filament_name = await resolve_spool_preset(
  2415. db,
  2416. spool_id=spool.id,
  2417. printer_model=model,
  2418. nozzle_diameter=slot_nozzle.diameter,
  2419. fallback_filament=spool.slicer_filament,
  2420. fallback_name=spool.slicer_filament_name,
  2421. )
  2422. return {
  2423. "slicer_filament": slicer_filament,
  2424. "slicer_filament_name": slicer_filament_name,
  2425. "cali_idx": profile.cali_idx if profile else None,
  2426. "k_value": profile.k_value if profile else None,
  2427. "profile_name": profile.name if profile else None,
  2428. "extruder": slot_nozzle.extruder,
  2429. "nozzle_diameter": slot_nozzle.diameter,
  2430. }
  2431. @router.post("/{printer_id}/slots/{ams_id}/{tray_id}/configure")
  2432. async def configure_ams_slot(
  2433. printer_id: int,
  2434. ams_id: int,
  2435. tray_id: int,
  2436. tray_info_idx: str = Query(...),
  2437. tray_type: str = Query(...),
  2438. tray_sub_brands: str = Query(...),
  2439. tray_color: str = Query(...),
  2440. nozzle_temp_min: int = Query(...),
  2441. nozzle_temp_max: int = Query(...),
  2442. cali_idx: int = Query(-1),
  2443. nozzle_diameter: str = Query("0.4"),
  2444. setting_id: str = Query(""),
  2445. kprofile_filament_id: str = Query(""),
  2446. kprofile_setting_id: str = Query(""),
  2447. k_value: float = Query(0.0),
  2448. db: AsyncSession = Depends(get_db),
  2449. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  2450. ):
  2451. """Configure an AMS slot with a specific filament setting and K profile.
  2452. This sends two commands to the printer:
  2453. 1. ams_filament_setting - sets filament type, color, temperature
  2454. 2. extrusion_cali_sel - sets the K profile (pressure advance value)
  2455. Args:
  2456. printer_id: Database ID of the printer
  2457. ams_id: AMS unit ID (0-3 for regular AMS, 128-135 for HT AMS)
  2458. tray_id: Tray ID within the AMS (0-3)
  2459. tray_info_idx: Filament ID short format (e.g., "GFL05") or user preset ID
  2460. tray_type: Filament type (e.g., "PLA", "PETG")
  2461. tray_sub_brands: Sub-brand/profile name (e.g., "PLA Basic", "PETG HF")
  2462. tray_color: Color in RRGGBBAA hex format (e.g., "FFFF00FF")
  2463. nozzle_temp_min: Minimum nozzle temperature
  2464. nozzle_temp_max: Maximum nozzle temperature
  2465. cali_idx: K profile calibration index (-1 for default 0.020)
  2466. nozzle_diameter: Nozzle diameter string (e.g., "0.4")
  2467. setting_id: Full setting ID with version (e.g., "GFSL05_07") - optional
  2468. kprofile_filament_id: K profile's filament_id for proper K profile linking
  2469. k_value: Direct K value to set (0.0 to skip direct K value setting)
  2470. """
  2471. logger = logging.getLogger(__name__)
  2472. logger.info("[configure_ams_slot] printer_id=%s, ams_id=%s, tray_id=%s", printer_id, ams_id, tray_id)
  2473. logger.info(
  2474. f"[configure_ams_slot] tray_info_idx={tray_info_idx!r}, tray_type={tray_type!r}, tray_sub_brands={tray_sub_brands!r}"
  2475. )
  2476. logger.info(
  2477. f"[configure_ams_slot] setting_id={setting_id!r}, kprofile_filament_id={kprofile_filament_id!r}, kprofile_setting_id={kprofile_setting_id!r}"
  2478. )
  2479. # The modal derives tray_type from a preset name or a spool's material, so
  2480. # it can be a product line rather than a type ("PLA+", "PolyTerra PLA").
  2481. # A slot carrying one of those satisfies nothing that asks for PLA, so the
  2482. # slot gets the type and tray_sub_brands -- untouched here -- keeps the
  2483. # name (issue #2902). The requested wording is kept for the id lookup
  2484. # below, which knows some product lines the type table does not.
  2485. requested_tray_type = tray_type
  2486. tray_type = printer_filament_type(tray_type)
  2487. if tray_type != requested_tray_type:
  2488. logger.info("[configure_ams_slot] tray_type %r → %r", requested_tray_type, tray_type)
  2489. # Get MQTT client for this printer
  2490. client = printer_manager.get_client(printer_id)
  2491. if not client:
  2492. raise HTTPException(status_code=400, detail="Printer not connected")
  2493. # Resolve tray_info_idx for the MQTT command.
  2494. # Priority:
  2495. # 1. Use the provided tray_info_idx if set (including cloud-synced
  2496. # custom presets like PFUS* / P*).
  2497. # 2. Reuse the slot's existing tray_info_idx if it's a specific
  2498. # (non-generic) preset for the same material.
  2499. # 3. Fall back to a generic Bambu filament ID.
  2500. _GENERIC_FILAMENT_IDS = {
  2501. "PLA": "GFL99",
  2502. "PETG": "GFG99",
  2503. "ABS": "GFB99",
  2504. "ASA": "GFB98",
  2505. "PC": "GFC99",
  2506. "PA": "GFN99",
  2507. "NYLON": "GFN99",
  2508. "TPU": "GFU99",
  2509. "PVA": "GFS99",
  2510. "HIPS": "GFS98",
  2511. "PLA-CF": "GFL98",
  2512. "PETG-CF": "GFG98",
  2513. "PA-CF": "GFN98",
  2514. "PETG HF": "GFG96",
  2515. }
  2516. _GENERIC_ID_VALUES = set(_GENERIC_FILAMENT_IDS.values())
  2517. effective_tray_info_idx = tray_info_idx
  2518. if not tray_info_idx:
  2519. # No preset provided — try slot reuse or generic fallback
  2520. current_tray_info_idx = ""
  2521. current_tray_type = ""
  2522. state = printer_manager.get_status(printer_id)
  2523. if state and state.raw_data:
  2524. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  2525. if ams_id == 255:
  2526. vt_tray = state.raw_data.get("vt_tray") or []
  2527. ext_id = tray_id + 254
  2528. for vt in vt_tray:
  2529. if isinstance(vt, dict) and int(vt.get("id", 254)) == ext_id:
  2530. current_tray_info_idx = vt.get("tray_info_idx", "")
  2531. current_tray_type = vt.get("tray_type", "")
  2532. break
  2533. else:
  2534. ams_data = state.raw_data.get("ams", {})
  2535. ams_list = (
  2536. ams_data.get("ams", [])
  2537. if isinstance(ams_data, dict)
  2538. else ams_data
  2539. if isinstance(ams_data, list)
  2540. else []
  2541. )
  2542. cur_tray = _find_tray_in_ams_data(ams_list, ams_id, tray_id)
  2543. if cur_tray:
  2544. current_tray_info_idx = cur_tray.get("tray_info_idx", "")
  2545. current_tray_type = cur_tray.get("tray_type", "")
  2546. if (
  2547. current_tray_info_idx
  2548. and current_tray_info_idx not in _GENERIC_ID_VALUES
  2549. and current_tray_type
  2550. and current_tray_type.upper() == tray_type.upper()
  2551. ):
  2552. logger.info(
  2553. "[configure_ams_slot] Reusing slot's existing tray_info_idx=%r (same material %r)",
  2554. current_tray_info_idx,
  2555. tray_type,
  2556. )
  2557. effective_tray_info_idx = current_tray_info_idx
  2558. elif tray_type:
  2559. # Requested wording first, reduced type only as a further fallback,
  2560. # so a material that already resolves keeps resolving to the same
  2561. # id: "PETG HF" has its own generic preset (GFG96) that reducing it
  2562. # to "PETG" would trade away for GFG99.
  2563. material = requested_tray_type.upper().strip()
  2564. generic = (
  2565. _GENERIC_FILAMENT_IDS.get(material)
  2566. or _GENERIC_FILAMENT_IDS.get(material.split("-")[0].split(" ")[0])
  2567. or _GENERIC_FILAMENT_IDS.get(tray_type.upper())
  2568. or ""
  2569. )
  2570. if generic:
  2571. logger.info("[configure_ams_slot] Falling back to generic %r for material %r", generic, tray_type)
  2572. effective_tray_info_idx = generic
  2573. # Send filament setting + K-profile commands
  2574. filament_id_for_kprofile = kprofile_filament_id if kprofile_filament_id else effective_tray_info_idx
  2575. # Realign the slot's filament context to the K-profile's calibration
  2576. # context. The printer's calibration table is keyed by (filament_id,
  2577. # cali_idx) — so for the cali_idx selected via extrusion_cali_sel to
  2578. # actually stick to the slot, ams_filament_setting must declare the
  2579. # slot under the SAME filament_id.
  2580. #
  2581. # Without this, configure_ams_slot would send:
  2582. # ams_filament_setting → tray_info_idx=GFL99 (generic from material)
  2583. # extrusion_cali_sel → filament_id=P4d64437 (kp's preset)
  2584. # ...and the cali_idx would silently be dropped to default because the
  2585. # slot's filament context (GFL99) doesn't match the kp's (P4d64437).
  2586. #
  2587. # This realignment fires only when the kp is targeted at a different
  2588. # preset than the user's filament selection AND the kp's preset is a
  2589. # valid tray_info_idx (GF* official, P* local — not PFUS* cloud-user
  2590. # which the slicer rejects in tray_info_idx).
  2591. effective_setting_id = setting_id
  2592. if (
  2593. kprofile_filament_id
  2594. and kprofile_filament_id != effective_tray_info_idx
  2595. and not kprofile_filament_id.startswith("PFUS")
  2596. ):
  2597. logger.info(
  2598. "[configure_ams_slot] realigning slot filament context to kp: tray_info_idx %r → %r, setting_id %r → %r",
  2599. effective_tray_info_idx,
  2600. kprofile_filament_id,
  2601. setting_id,
  2602. kprofile_setting_id or setting_id,
  2603. )
  2604. effective_tray_info_idx = kprofile_filament_id
  2605. if kprofile_setting_id:
  2606. effective_setting_id = kprofile_setting_id
  2607. # Back-fill setting_id from the resolved filament id when the client sent
  2608. # none. Built-in / local / Orca-generic presets in the Configure AMS Slot
  2609. # modal leave setting_id empty (they carry only a GF* tray_info_idx), and
  2610. # the printer treats a filament-id-without-setting-id slot as half
  2611. # configured: it shows the new material briefly, then reverts to its
  2612. # previously stored profile (#2604). This mirrors the derivation the
  2613. # inventory/assignment path already does (inventory.py). filament_id_to_
  2614. # setting_id leaves P* user presets and already-GFS* values unchanged, so
  2615. # only the empty-setting_id generic paths are affected.
  2616. if effective_tray_info_idx and not effective_setting_id:
  2617. effective_setting_id = filament_id_to_setting_id(effective_tray_info_idx)
  2618. # Always send ams_set_filament_setting — the user explicitly clicked
  2619. # "Configure Slot", so honor that. Previous versions skipped this for
  2620. # RFID-tagged slots to preserve the slicer eye icon, but printers cache
  2621. # stale tag_uid/tray_uuid after a BL spool is removed, causing the check
  2622. # to false-positive on non-RFID slots and silently drop the command.
  2623. success = client.ams_set_filament_setting(
  2624. ams_id=ams_id,
  2625. tray_id=tray_id,
  2626. tray_info_idx=effective_tray_info_idx,
  2627. tray_type=tray_type,
  2628. tray_sub_brands=tray_sub_brands,
  2629. tray_color=tray_color,
  2630. nozzle_temp_min=nozzle_temp_min,
  2631. nozzle_temp_max=nozzle_temp_max,
  2632. setting_id=effective_setting_id,
  2633. )
  2634. if not success:
  2635. raise HTTPException(status_code=500, detail="Failed to send filament configuration command")
  2636. # Method 1: Select existing calibration profile by cali_idx
  2637. # Do NOT include setting_id — BambuStudio never sends it in extrusion_cali_sel,
  2638. # and including it causes the firmware to mislink the profile on X1C/P1S.
  2639. client.extrusion_cali_sel(
  2640. ams_id=ams_id,
  2641. tray_id=tray_id,
  2642. cali_idx=cali_idx,
  2643. filament_id=filament_id_for_kprofile,
  2644. nozzle_diameter=nozzle_diameter,
  2645. )
  2646. # Method 2: Only send extrusion_cali_set when NO existing profile was selected
  2647. # (cali_idx == -1). When cali_idx >= 0, extrusion_cali_sel already selected the
  2648. # correct profile. Sending extrusion_cali_set with the same cali_idx would MODIFY
  2649. # the existing profile's metadata (extruder_id, nozzle_id, name, setting_id),
  2650. # corrupting it — e.g., overwriting a High Flow extruder 1 profile with
  2651. # hardcoded extruder_id=0 and nozzle_id=HS00.
  2652. if k_value > 0 and cali_idx < 0:
  2653. # Calculate global tray ID for extrusion_cali_set
  2654. if ams_id <= 3:
  2655. global_tray_id = ams_id * 4 + tray_id
  2656. elif ams_id >= 128 and ams_id <= 135:
  2657. global_tray_id = (ams_id - 128) * 4 + tray_id
  2658. else:
  2659. global_tray_id = tray_id
  2660. client.extrusion_cali_set(
  2661. tray_id=global_tray_id,
  2662. k_value=k_value,
  2663. nozzle_diameter=nozzle_diameter,
  2664. nozzle_temp=nozzle_temp_max,
  2665. filament_id=filament_id_for_kprofile,
  2666. setting_id=kprofile_setting_id or "",
  2667. name=tray_sub_brands or "",
  2668. cali_idx=cali_idx,
  2669. )
  2670. # Persist the user's K-profile choice so it survives RFID re-reads and
  2671. # session restarts. Pre-Phase-13 this was ephemeral — the MQTT command
  2672. # took effect on the printer but bambuddy never recorded it, so the next
  2673. # `_apply_pa_after_refresh` cycle had no stored profile to re-assert.
  2674. if cali_idx >= 0:
  2675. try:
  2676. from sqlalchemy.orm import selectinload
  2677. from backend.app.models.spool_assignment import SpoolAssignment
  2678. from backend.app.models.spool_k_profile import SpoolKProfile
  2679. from backend.app.models.spoolman_k_profile import SpoolmanKProfile
  2680. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  2681. # Resolve the slot's extruder for the K-profile match key. On a
  2682. # Filament Track Switch machine this comes from the AMS's inlet
  2683. # binding, because every unit reports extruder 0xE there — without
  2684. # that, the `else 0` below filed every profile under the right-hand
  2685. # nozzle and a left-nozzle calibration was stored as a right one.
  2686. slot_state = printer_manager.get_status(printer_id)
  2687. resolved_extruder = slot_extruder(
  2688. ams_id,
  2689. tray_id,
  2690. slot_state.ams_extruder_map if slot_state else None,
  2691. slot_state.ams_switch_inlet if slot_state else None,
  2692. )
  2693. # Still 0 when nothing is known, which is right for a single-nozzle
  2694. # printer — the resolver only returns None when it genuinely cannot
  2695. # tell, and on those machines extruder 0 is the only one there is.
  2696. kp_extruder = resolved_extruder if resolved_extruder is not None else 0
  2697. # Only the active mode's assignment table decides where this
  2698. # K-profile is stored. Reading Spoolman first and falling through
  2699. # was safe while the inactive table was emptied on every mode
  2700. # toggle; nothing is emptied since #2812, so a leftover Spoolman
  2701. # row in built-in mode would file the calibration against a spool
  2702. # the printer is not using and never write the local profile —
  2703. # the calibration would appear to succeed and then not apply.
  2704. from backend.app.services.inventory_mode import spoolman_owns_assignments
  2705. spoolman_mode = await spoolman_owns_assignments(db)
  2706. sm_assignment = None
  2707. if spoolman_mode:
  2708. # Spoolman SlotAssignment — has UniqueConstraint, idempotent.
  2709. sm_result = await db.execute(
  2710. select(SpoolmanSlotAssignment).where(
  2711. SpoolmanSlotAssignment.printer_id == printer_id,
  2712. SpoolmanSlotAssignment.ams_id == ams_id,
  2713. SpoolmanSlotAssignment.tray_id == tray_id,
  2714. )
  2715. )
  2716. sm_assignment = sm_result.scalar_one_or_none()
  2717. if sm_assignment:
  2718. existing = await db.execute(
  2719. select(SpoolmanKProfile).where(
  2720. SpoolmanKProfile.spoolman_spool_id == sm_assignment.spoolman_spool_id,
  2721. SpoolmanKProfile.printer_id == printer_id,
  2722. SpoolmanKProfile.extruder == kp_extruder,
  2723. SpoolmanKProfile.nozzle_diameter == nozzle_diameter,
  2724. )
  2725. )
  2726. kp = existing.scalar_one_or_none()
  2727. if kp:
  2728. kp.cali_idx = cali_idx
  2729. kp.k_value = k_value or 0.0
  2730. kp.setting_id = kprofile_setting_id or None
  2731. kp.name = tray_sub_brands or None
  2732. else:
  2733. db.add(
  2734. SpoolmanKProfile(
  2735. spoolman_spool_id=sm_assignment.spoolman_spool_id,
  2736. printer_id=printer_id,
  2737. extruder=kp_extruder,
  2738. nozzle_diameter=nozzle_diameter,
  2739. k_value=k_value or 0.0,
  2740. name=tray_sub_brands or None,
  2741. cali_idx=cali_idx,
  2742. setting_id=kprofile_setting_id or None,
  2743. )
  2744. )
  2745. await db.commit()
  2746. logger.info(
  2747. "[configure_ams_slot] Persisted Spoolman K-profile spool=%d printer=%d ams=%d tray=%d cali_idx=%d",
  2748. sm_assignment.spoolman_spool_id,
  2749. printer_id,
  2750. ams_id,
  2751. tray_id,
  2752. cali_idx,
  2753. )
  2754. elif not spoolman_mode:
  2755. # Local SpoolAssignment + SpoolKProfile (no UNIQUE — use .first()).
  2756. # Skipped in Spoolman mode even when a local row survives: the
  2757. # profile would be filed against a spool this printer is not
  2758. # drawing on, and the mode's own table has nothing to bind to.
  2759. local_result = await db.execute(
  2760. select(SpoolAssignment)
  2761. .options(selectinload(SpoolAssignment.spool))
  2762. .where(
  2763. SpoolAssignment.printer_id == printer_id,
  2764. SpoolAssignment.ams_id == ams_id,
  2765. SpoolAssignment.tray_id == tray_id,
  2766. )
  2767. )
  2768. local_assignment = local_result.scalar_one_or_none()
  2769. if local_assignment and local_assignment.spool:
  2770. existing = await db.execute(
  2771. select(SpoolKProfile).where(
  2772. SpoolKProfile.spool_id == local_assignment.spool.id,
  2773. SpoolKProfile.printer_id == printer_id,
  2774. SpoolKProfile.extruder == kp_extruder,
  2775. SpoolKProfile.nozzle_diameter == nozzle_diameter,
  2776. )
  2777. )
  2778. # SpoolKProfile has no unique constraint on this tuple, so
  2779. # multiple rows could theoretically exist (shouldn't, but
  2780. # don't crash if they do). Update the first match, leave
  2781. # any duplicates alone.
  2782. kp = existing.scalars().first()
  2783. if kp:
  2784. kp.cali_idx = cali_idx
  2785. kp.k_value = k_value or 0.0
  2786. kp.setting_id = kprofile_setting_id or None
  2787. kp.name = tray_sub_brands or None
  2788. else:
  2789. db.add(
  2790. SpoolKProfile(
  2791. spool_id=local_assignment.spool.id,
  2792. printer_id=printer_id,
  2793. extruder=kp_extruder,
  2794. nozzle_diameter=nozzle_diameter,
  2795. k_value=k_value or 0.0,
  2796. name=tray_sub_brands or None,
  2797. cali_idx=cali_idx,
  2798. setting_id=kprofile_setting_id or None,
  2799. )
  2800. )
  2801. await db.commit()
  2802. logger.info(
  2803. "[configure_ams_slot] Persisted local K-profile spool=%d printer=%d ams=%d tray=%d cali_idx=%d",
  2804. local_assignment.spool.id,
  2805. printer_id,
  2806. ams_id,
  2807. tray_id,
  2808. cali_idx,
  2809. )
  2810. except Exception:
  2811. # MQTT command was already sent successfully — DB persist is best-effort.
  2812. logger.exception(
  2813. "[configure_ams_slot] Failed to persist K-profile (printer=%d ams=%d tray=%d cali_idx=%d)",
  2814. printer_id,
  2815. ams_id,
  2816. tray_id,
  2817. cali_idx,
  2818. )
  2819. try:
  2820. await db.rollback()
  2821. except Exception:
  2822. pass
  2823. # Register a read-back verification (#2582) so the tray telemetry that the
  2824. # status push below returns can confirm the printer accepted this manual
  2825. # slot configuration. Mirrors the inventory/assignment path.
  2826. client.register_assignment_verification(
  2827. ams_id=ams_id,
  2828. tray_id=tray_id,
  2829. tray_info_idx=effective_tray_info_idx,
  2830. tray_color=tray_color,
  2831. cali_idx=cali_idx,
  2832. )
  2833. # Request fresh status push from printer so frontend gets updated data via WebSocket
  2834. logger.info("[configure_ams_slot] Requesting status update from printer")
  2835. update_result = client.request_status_update()
  2836. logger.info("[configure_ams_slot] Status update request result: %s", update_result)
  2837. return {
  2838. "success": True,
  2839. "message": f"Configured AMS {ams_id} tray {tray_id} with {tray_sub_brands}",
  2840. }
  2841. @router.post("/{printer_id}/ams/{ams_id}/tray/{tray_id}/reset")
  2842. async def reset_ams_slot(
  2843. printer_id: int,
  2844. ams_id: int,
  2845. tray_id: int,
  2846. db: AsyncSession = Depends(get_db),
  2847. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  2848. ):
  2849. """Reset an AMS slot to empty/unconfigured state.
  2850. This clears the filament configuration from the slot.
  2851. """
  2852. # Get MQTT client for this printer
  2853. client = printer_manager.get_client(printer_id)
  2854. if not client:
  2855. raise HTTPException(status_code=400, detail="Printer not connected")
  2856. # Reset the slot
  2857. success = client.reset_ams_slot(ams_id=ams_id, tray_id=tray_id)
  2858. if not success:
  2859. raise HTTPException(status_code=500, detail="Failed to send reset command")
  2860. # Also delete any saved slot preset mapping
  2861. result = await db.execute(
  2862. select(SlotPresetMapping).where(
  2863. SlotPresetMapping.printer_id == printer_id,
  2864. SlotPresetMapping.ams_id == ams_id,
  2865. SlotPresetMapping.tray_id == tray_id,
  2866. )
  2867. )
  2868. mapping = result.scalar_one_or_none()
  2869. if mapping:
  2870. await db.delete(mapping)
  2871. await db.commit()
  2872. # Request fresh status push from printer so frontend gets updated data via WebSocket
  2873. client.request_status_update()
  2874. return {
  2875. "success": True,
  2876. "message": f"Reset AMS {ams_id} tray {tray_id}",
  2877. }
  2878. @router.get("/{printer_id}/ams-labels")
  2879. async def get_ams_labels(
  2880. printer_id: int,
  2881. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  2882. db: AsyncSession = Depends(get_db),
  2883. ):
  2884. """Get all user-defined AMS labels for a printer, keyed by AMS unit ID.
  2885. Labels are stored by AMS serial number. This endpoint resolves the current
  2886. serial-to-ams_id mapping from the live printer state so the response is still
  2887. keyed by ams_id for UI compatibility.
  2888. """
  2889. # Build serial -> ams_id map from live printer state
  2890. serial_to_ams_id: dict[str, int] = {}
  2891. state = printer_manager.get_status(printer_id)
  2892. if state and state.raw_data:
  2893. for ams_unit in state.raw_data.get("ams", []):
  2894. sn = str(ams_unit.get("sn") or ams_unit.get("serial_number") or "")
  2895. if sn:
  2896. serial_to_ams_id[sn] = int(ams_unit.get("id", 0))
  2897. # Collect all known serials for this printer (live + synthetic fallback keys)
  2898. serials_to_query = set(serial_to_ams_id.keys())
  2899. # Fetch labels for all known serials
  2900. labels: dict[int, str] = {}
  2901. if serials_to_query:
  2902. result = await db.execute(select(AmsLabel).where(AmsLabel.ams_serial_number.in_(serials_to_query)))
  2903. for lbl in result.scalars().all():
  2904. aid = serial_to_ams_id.get(lbl.ams_serial_number)
  2905. if aid is not None:
  2906. labels[aid] = lbl.label
  2907. # Also fetch labels stored under synthetic keys for this printer (backward compat)
  2908. # Collect all synthetic keys first, then query with a single IN clause.
  2909. if state and state.raw_data:
  2910. synthetic_key_to_aid: dict[str, int] = {
  2911. f"p{printer_id}a{int(ams_unit.get('id', 0))}": int(ams_unit.get("id", 0))
  2912. for ams_unit in state.raw_data.get("ams", [])
  2913. if int(ams_unit.get("id", 0)) not in labels
  2914. }
  2915. if synthetic_key_to_aid:
  2916. result = await db.execute(
  2917. select(AmsLabel).where(AmsLabel.ams_serial_number.in_(synthetic_key_to_aid.keys()))
  2918. )
  2919. for lbl in result.scalars().all():
  2920. aid = synthetic_key_to_aid.get(lbl.ams_serial_number)
  2921. if aid is not None:
  2922. labels[aid] = lbl.label
  2923. return labels
  2924. @router.put("/{printer_id}/ams-labels/{ams_id}")
  2925. async def save_ams_label(
  2926. printer_id: int,
  2927. ams_id: int,
  2928. body: AmsLabelBody,
  2929. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_UPDATE),
  2930. db: AsyncSession = Depends(get_db),
  2931. ):
  2932. """Create or update the friendly name for a specific AMS unit.
  2933. When ``ams_serial`` is provided the label is stored under that serial number so
  2934. it survives the AMS being moved to a different printer. When it is absent (e.g.
  2935. older firmware that does not report a serial) a synthetic key based on the
  2936. printer_id and ams_id is used as a fallback.
  2937. """
  2938. # Verify printer exists
  2939. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  2940. if not result.scalar_one_or_none():
  2941. raise HTTPException(404, "Printer not found")
  2942. # Determine the serial key to store under
  2943. stripped = body.ams_serial.strip() if body.ams_serial else ""
  2944. serial_key = stripped if stripped else f"p{printer_id}a{ams_id}"
  2945. result = await db.execute(select(AmsLabel).where(AmsLabel.ams_serial_number == serial_key))
  2946. existing = result.scalar_one_or_none()
  2947. if existing:
  2948. existing.label = body.label
  2949. existing.ams_id = ams_id
  2950. else:
  2951. db.add(AmsLabel(ams_serial_number=serial_key, ams_id=ams_id, label=body.label))
  2952. await db.commit()
  2953. return {"ams_id": ams_id, "label": body.label}
  2954. @router.delete("/{printer_id}/ams-labels/{ams_id}")
  2955. async def delete_ams_label(
  2956. printer_id: int,
  2957. ams_id: int,
  2958. ams_serial: str = Query(default="", max_length=50),
  2959. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_UPDATE),
  2960. db: AsyncSession = Depends(get_db),
  2961. ):
  2962. """Delete the friendly name for a specific AMS unit, reverting to the auto label."""
  2963. stripped = ams_serial.strip() if ams_serial else ""
  2964. serial_key = stripped if stripped else f"p{printer_id}a{ams_id}"
  2965. result = await db.execute(select(AmsLabel).where(AmsLabel.ams_serial_number == serial_key))
  2966. existing = result.scalar_one_or_none()
  2967. if existing:
  2968. await db.delete(existing)
  2969. await db.commit()
  2970. return {"success": True}
  2971. @router.post("/{printer_id}/debug/simulate-print-complete")
  2972. async def debug_simulate_print_complete(
  2973. printer_id: int,
  2974. db: AsyncSession = Depends(get_db),
  2975. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  2976. ):
  2977. """DEBUG: Simulate print completion to test freeze behavior.
  2978. This triggers the same code path as a real print completion,
  2979. without needing to wait for an actual print to finish.
  2980. """
  2981. from backend.app.main import _active_prints, on_print_complete
  2982. from backend.app.models.archive import PrintArchive
  2983. # Get the most recent archive for this printer
  2984. result = await db.execute(
  2985. select(PrintArchive)
  2986. .where(PrintArchive.printer_id == printer_id)
  2987. .order_by(PrintArchive.created_at.desc())
  2988. .limit(1)
  2989. )
  2990. archive = result.scalar_one_or_none()
  2991. if not archive:
  2992. raise HTTPException(status_code=404, detail="No archives found for this printer")
  2993. # Register this archive as "active" so on_print_complete can find it
  2994. filename = archive.file_path.split("/")[-1] if archive.file_path else "test.3mf"
  2995. subtask_name = archive.print_name or "Test Print"
  2996. _active_prints[(printer_id, filename)] = archive.id
  2997. _active_prints[(printer_id, subtask_name)] = archive.id
  2998. # Simulate print completion data
  2999. data = {
  3000. "status": "completed",
  3001. "filename": filename,
  3002. "subtask_name": subtask_name,
  3003. "timelapse_was_active": False,
  3004. }
  3005. logger.info("Simulating print complete for printer %s, archive %s", printer_id, archive.id)
  3006. # Call the actual on_print_complete handler
  3007. await on_print_complete(printer_id, data)
  3008. return {"success": True, "archive_id": archive.id, "message": "Print completion simulated"}
  3009. # =============================================================================
  3010. # Print Control Endpoints
  3011. # =============================================================================
  3012. @router.post("/{printer_id}/print/stop")
  3013. async def stop_print(
  3014. printer_id: int,
  3015. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3016. db: AsyncSession = Depends(get_db),
  3017. ):
  3018. """Stop/cancel the current print job."""
  3019. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3020. printer = result.scalar_one_or_none()
  3021. if not printer:
  3022. raise HTTPException(404, "Printer not found")
  3023. client = printer_manager.get_client(printer_id)
  3024. if not client:
  3025. raise HTTPException(400, "Printer not connected")
  3026. success = client.stop_print()
  3027. if not success:
  3028. raise HTTPException(500, "Failed to stop print")
  3029. # Mark this printer as user-stopped so on_print_complete reclassifies
  3030. # the resulting "failed"/"aborted" MQTT status as "cancelled" — otherwise
  3031. # the HMS heuristic in _dispatch_archive_update mislabels user-cancels
  3032. # (e.g. the H2D's cancel-sequence module-0x0C HMS) as "Layer shift".
  3033. try:
  3034. from backend.app.main import mark_printer_stopped_by_user
  3035. mark_printer_stopped_by_user(printer_id)
  3036. except Exception as _mark_err:
  3037. logger.warning("Failed to mark printer %s as user-stopped: %s", printer_id, _mark_err)
  3038. return {"success": True, "message": "Print stop command sent"}
  3039. @router.post("/{printer_id}/clear-plate")
  3040. async def clear_plate(
  3041. printer_id: int,
  3042. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CLEAR_PLATE),
  3043. db: AsyncSession = Depends(get_db),
  3044. ):
  3045. """Acknowledge that the build plate has been cleared after a finished/failed print.
  3046. Sets a plate-cleared flag so the scheduler can start the next queued print.
  3047. No MQTT command is sent to the printer — the scheduler's start_print command
  3048. will override the FINISH/FAILED state when it sends the next job.
  3049. """
  3050. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3051. printer = result.scalar_one_or_none()
  3052. if not printer:
  3053. raise HTTPException(404, "Printer not found")
  3054. # Deliberately NOT gated on the printer being connected. Acknowledging the plate
  3055. # only mutates Bambuddy-side state — no MQTT command is sent — and with Auto Power
  3056. # Off the normal end-of-print state is exactly this: gate up, printer powered down.
  3057. # The guard this replaces was inherited from the sibling stop/pause/resume handlers,
  3058. # where reaching the printer IS required, and left farms with no way to release the
  3059. # gate short of powering each printer back on by hand (#2864).
  3060. # Accept the acknowledgment whenever the printer is awaiting it — not only when the
  3061. # reported state is FINISH/FAILED. After a power cycle the printer boots into IDLE
  3062. # but the awaiting flag persists, and the user still needs a way to ack it (#961).
  3063. state = printer_manager.get_status(printer_id)
  3064. awaiting = printer_manager.is_awaiting_plate_clear(printer_id)
  3065. if not awaiting and (not state or state.state not in ("FINISH", "FAILED")):
  3066. raise HTTPException(
  3067. 400,
  3068. f"Printer is not awaiting plate-clear acknowledgment (state={state.state if state else 'unknown'})",
  3069. )
  3070. printer_manager.set_awaiting_plate_clear(printer_id, False)
  3071. return {"success": True, "message": "Plate cleared, next print will start shortly"}
  3072. @router.post("/{printer_id}/print/pause")
  3073. async def pause_print(
  3074. printer_id: int,
  3075. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3076. db: AsyncSession = Depends(get_db),
  3077. ):
  3078. """Pause the current print job."""
  3079. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3080. printer = result.scalar_one_or_none()
  3081. if not printer:
  3082. raise HTTPException(404, "Printer not found")
  3083. client = printer_manager.get_client(printer_id)
  3084. if not client:
  3085. raise HTTPException(400, "Printer not connected")
  3086. success = client.pause_print()
  3087. if not success:
  3088. raise HTTPException(500, "Failed to pause print")
  3089. return {"success": True, "message": "Print pause command sent"}
  3090. @router.post("/{printer_id}/print/resume")
  3091. async def resume_print(
  3092. printer_id: int,
  3093. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3094. db: AsyncSession = Depends(get_db),
  3095. ):
  3096. """Resume a paused print job."""
  3097. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3098. printer = result.scalar_one_or_none()
  3099. if not printer:
  3100. raise HTTPException(404, "Printer not found")
  3101. client = printer_manager.get_client(printer_id)
  3102. if not client:
  3103. raise HTTPException(400, "Printer not connected")
  3104. success = client.resume_print()
  3105. if not success:
  3106. raise HTTPException(500, "Failed to resume print")
  3107. return {"success": True, "message": "Print resume command sent"}
  3108. @router.post("/{printer_id}/print-speed")
  3109. async def set_print_speed(
  3110. printer_id: int,
  3111. mode: int = Query(..., description="Speed mode (1=silent, 2=standard, 3=sport, 4=ludicrous)"),
  3112. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3113. db: AsyncSession = Depends(get_db),
  3114. ):
  3115. """Set the print speed mode."""
  3116. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3117. printer = result.scalar_one_or_none()
  3118. if not printer:
  3119. raise HTTPException(404, "Printer not found")
  3120. client = printer_manager.get_client(printer_id)
  3121. if not client:
  3122. raise HTTPException(400, "Printer not connected")
  3123. success = client.set_print_speed(mode)
  3124. if not success:
  3125. raise HTTPException(500, "Failed to set print speed")
  3126. speed_names = {1: "Silent", 2: "Standard", 3: "Sport", 4: "Ludicrous"}
  3127. return {"success": True, "message": f"Print speed set to {speed_names.get(mode, 'Unknown')}"}
  3128. @router.post("/{printer_id}/temperature/nozzle")
  3129. async def set_nozzle_temperature(
  3130. printer_id: int,
  3131. target: int = Query(..., ge=0, le=320, description="Target nozzle temperature in Celsius; 0 turns heating off"),
  3132. nozzle: int = Query(0, ge=0, le=1, description="Nozzle/extruder index (0=right/default, 1=left)"),
  3133. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3134. db: AsyncSession = Depends(get_db),
  3135. ):
  3136. """Set a nozzle target temperature."""
  3137. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3138. printer = result.scalar_one_or_none()
  3139. if not printer:
  3140. raise HTTPException(404, "Printer not found")
  3141. client = printer_manager.get_client(printer_id)
  3142. if not client:
  3143. raise HTTPException(400, "Printer not connected")
  3144. success = client.set_nozzle_temperature(target, nozzle)
  3145. if not success:
  3146. raise HTTPException(500, "Failed to set nozzle temperature")
  3147. return {"success": True, "message": f"Nozzle temperature set to {target}°C"}
  3148. @router.post("/{printer_id}/temperature/bed")
  3149. async def set_bed_temperature(
  3150. printer_id: int,
  3151. target: int = Query(..., ge=0, le=140, description="Target bed temperature in Celsius; 0 turns heating off"),
  3152. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3153. db: AsyncSession = Depends(get_db),
  3154. ):
  3155. """Set the bed target temperature."""
  3156. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3157. printer = result.scalar_one_or_none()
  3158. if not printer:
  3159. raise HTTPException(404, "Printer not found")
  3160. client = printer_manager.get_client(printer_id)
  3161. if not client:
  3162. raise HTTPException(400, "Printer not connected")
  3163. success = client.set_bed_temperature(target)
  3164. if not success:
  3165. raise HTTPException(500, "Failed to set bed temperature")
  3166. return {"success": True, "message": f"Bed temperature set to {target}°C"}
  3167. @router.post("/{printer_id}/temperature/chamber")
  3168. async def set_chamber_temperature(
  3169. printer_id: int,
  3170. target: int = Query(
  3171. ...,
  3172. ge=0,
  3173. le=MAX_CHAMBER_TEMP_C,
  3174. description="Target chamber temperature in Celsius; 0 turns heating off",
  3175. ),
  3176. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3177. db: AsyncSession = Depends(get_db),
  3178. ):
  3179. """Set the chamber target temperature.
  3180. Gated on `supports_chamber_heater(model)`: only H2C, H2D, H2D Pro, H2S,
  3181. and X2D have an active chamber heater. Sensor-only models (X1C, X1E,
  3182. P2S) report chamber temp but silently swallow M141, so we 400 here
  3183. rather than send a no-op.
  3184. """
  3185. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3186. printer = result.scalar_one_or_none()
  3187. if not printer:
  3188. raise HTTPException(404, "Printer not found")
  3189. if not supports_chamber_heater(printer.model):
  3190. raise HTTPException(400, f"Model {printer.model or 'unknown'} does not have an active chamber heater")
  3191. client = printer_manager.get_client(printer_id)
  3192. if not client:
  3193. raise HTTPException(400, "Printer not connected")
  3194. success = client.set_chamber_temperature(target)
  3195. if not success:
  3196. raise HTTPException(500, "Failed to set chamber temperature")
  3197. return {"success": True, "message": f"Chamber temperature set to {target}°C"}
  3198. @router.post("/{printer_id}/fan-speed")
  3199. async def set_fan_speed(
  3200. printer_id: int,
  3201. fan: str = Query(..., description="Fan to control: part, aux, aux2 (left aux), or chamber"),
  3202. speed: int = Query(..., ge=0, le=100, description="Fan speed percentage"),
  3203. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3204. db: AsyncSession = Depends(get_db),
  3205. ):
  3206. """Set a fan speed by percentage.
  3207. Fan index 10 ("aux2") is the optional left auxiliary part cooling fan on
  3208. P2S/X2D — driven with "M106 P10" exactly like Bambu's official machine
  3209. profile gcode does. It only exists when the printer reports airduct part 10,
  3210. so the request is rejected rather than sending M106 P10 into the void on a
  3211. machine that has no such fan.
  3212. That gate also rejects for the short window between connecting and the
  3213. first airduct push, when nothing is known about the fan yet. The card hides
  3214. the badge over the same window, so there is no control to click; a direct
  3215. API caller gets a 400 and should retry once the status reports the fan.
  3216. """
  3217. fan_ids = {"part": 1, "aux": 2, "chamber": 3, "aux2": 10}
  3218. fan_id = fan_ids.get(fan)
  3219. if fan_id is None:
  3220. raise HTTPException(400, "fan must be 'part', 'aux', 'aux2', or 'chamber'")
  3221. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3222. printer = result.scalar_one_or_none()
  3223. if not printer:
  3224. raise HTTPException(404, "Printer not found")
  3225. client = printer_manager.get_client(printer_id)
  3226. if not client:
  3227. raise HTTPException(400, "Printer not connected")
  3228. # Presence gate for the accessory fan. Without this, aux2 is accepted for
  3229. # every model and an A1 would be sent M106 P10 for a fan it does not have.
  3230. # The UI already hides the badge; this closes the same hole on the API.
  3231. if fan == "aux2" and getattr(client.state, "left_aux_fan_speed", None) is None:
  3232. raise HTTPException(
  3233. 400,
  3234. "This printer does not report a left auxiliary fan "
  3235. "(no airduct part 10). The fan is an accessory kit on the P2S "
  3236. "and factory-fitted on the X2D.",
  3237. )
  3238. pwm_speed = round(speed * 255 / 100)
  3239. success = client.set_fan_speed(fan_id, pwm_speed)
  3240. if not success:
  3241. raise HTTPException(500, "Failed to set fan speed")
  3242. # The enclosure fan is called "Exhaust" on P2S/X2D and "Chamber" elsewhere;
  3243. # match whatever the printer card badge shows so the toast agrees with the
  3244. # control the user just clicked.
  3245. fan_names = {
  3246. "part": "Part cooling fan",
  3247. "aux": "Auxiliary fan",
  3248. "aux2": "Left auxiliary fan",
  3249. "chamber": "Exhaust fan" if uses_exhaust_fan_label(printer.model) else "Chamber fan",
  3250. }
  3251. return {"success": True, "message": f"{fan_names[fan]} set to {speed}%"}
  3252. @router.post("/{printer_id}/select-extruder")
  3253. async def select_extruder(
  3254. printer_id: int,
  3255. extruder: int = Query(..., ge=0, le=1, description="Extruder index (0=right, 1=left)"),
  3256. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3257. db: AsyncSession = Depends(get_db),
  3258. ):
  3259. """Select the active extruder/nozzle on dual-nozzle printers."""
  3260. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3261. printer = result.scalar_one_or_none()
  3262. if not printer:
  3263. raise HTTPException(404, "Printer not found")
  3264. client = printer_manager.get_client(printer_id)
  3265. if not client:
  3266. raise HTTPException(400, "Printer not connected")
  3267. success = client.select_extruder(extruder)
  3268. if not success:
  3269. raise HTTPException(500, "Failed to select nozzle")
  3270. return {"success": True, "message": f"{'Left' if extruder == 1 else 'Right'} nozzle selected"}
  3271. @router.post("/{printer_id}/airduct-mode")
  3272. async def set_airduct_mode(
  3273. printer_id: int,
  3274. mode: str = Query(..., description="Airduct mode: 'cooling' or 'heating'"),
  3275. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3276. db: AsyncSession = Depends(get_db),
  3277. ):
  3278. """Set the airduct mode (cooling/heating) on supported printers (P2S/H2*)."""
  3279. if mode not in ("cooling", "heating"):
  3280. raise HTTPException(400, "Mode must be 'cooling' or 'heating'")
  3281. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3282. printer = result.scalar_one_or_none()
  3283. if not printer:
  3284. raise HTTPException(404, "Printer not found")
  3285. client = printer_manager.get_client(printer_id)
  3286. if not client:
  3287. raise HTTPException(400, "Printer not connected")
  3288. success = client.set_airduct_mode(mode)
  3289. if not success:
  3290. raise HTTPException(500, "Failed to set airduct mode")
  3291. return {"success": True, "message": f"Airduct mode set to {mode}"}
  3292. @router.post("/{printer_id}/chamber-light")
  3293. async def set_chamber_light(
  3294. printer_id: int,
  3295. on: bool = Query(..., description="True to turn on, False to turn off"),
  3296. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3297. db: AsyncSession = Depends(get_db),
  3298. ):
  3299. """Turn the chamber light on or off."""
  3300. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3301. printer = result.scalar_one_or_none()
  3302. if not printer:
  3303. raise HTTPException(404, "Printer not found")
  3304. client = printer_manager.get_client(printer_id)
  3305. if not client:
  3306. raise HTTPException(400, "Printer not connected")
  3307. success = client.set_chamber_light(on)
  3308. if not success:
  3309. raise HTTPException(500, "Failed to control chamber light")
  3310. return {"success": True, "message": f"Chamber light {'on' if on else 'off'}"}
  3311. @router.post("/{printer_id}/bed-jog")
  3312. async def bed_jog(
  3313. printer_id: int,
  3314. distance: float = Query(
  3315. ...,
  3316. description=(
  3317. "Signed nozzle-bed gap adjustment in mm. Negative = decrease gap "
  3318. '("up" arrow in the UI: bed up on bed-on-Z models, toolhead down '
  3319. "on A1 bed-slingers). Positive = increase gap. The backend "
  3320. "translates this into the right G-code Z sign per printer model."
  3321. ),
  3322. ),
  3323. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3324. db: AsyncSession = Depends(get_db),
  3325. ):
  3326. """Adjust the nozzle-bed gap by a relative distance.
  3327. Emits a short G-code sequence via MQTT.
  3328. Soft-endstop policy (#2579). The printer's software travel limits are the
  3329. only thing between a jog button and a bed crash — on Bambu machines the
  3330. physical endstops are homing-only (there is no runtime limit switch in the
  3331. travel path), so once they are disabled nothing stops the move. The old
  3332. code disabled them (``M211 S0``) around every forced jog, and the UI sent
  3333. ``force`` on every jog, so the limits were off on every bed move — that is
  3334. what let a jog drive the nozzle into the bed on all models (#2579). This
  3335. endpoint now emits a **bare relative move and never touches ``M211`` at
  3336. all** — byte-for-byte what the printer's own touchscreen jog sends, which
  3337. stops at the travel limit. Bambuddy no longer disables the firmware's soft
  3338. endstops, and it no longer sends ``M211 S1`` either: that was an unverified
  3339. attempt to re-enable a printer left disabled by an older build, and on real
  3340. hardware the jog moved past the limit *with* it. If a printer still jogs
  3341. past its limits, its endstops were disabled at the firmware level by the old
  3342. build — power-cycle it once to restore them; from then on Bambuddy leaves
  3343. them alone.
  3344. Direction handling: on bed-on-Z printers (X1 / P1 / H2 family) the bed
  3345. is the Z-axis, and Bambu's home convention puts Z=0 at the top with
  3346. Z+ moving the bed down — so a frontend "Up" (decrease gap) maps
  3347. naturally to ``G1 Z-``. On bed-slingers (A1 / A1 Mini) the Z-axis is
  3348. the *toolhead*, and ``G1 Z-`` instead drives the nozzle DOWN into the
  3349. bed (#1334 reported exactly that crash). For those models we invert
  3350. the sign before emitting the G-code, so the UI semantics stay the
  3351. same regardless of which part physically moves.
  3352. """
  3353. if distance == 0 or abs(distance) > 200:
  3354. raise HTTPException(400, "Distance must be non-zero and ≤ 200 mm")
  3355. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3356. printer = result.scalar_one_or_none()
  3357. if not printer:
  3358. raise HTTPException(404, "Printer not found")
  3359. client = printer_manager.get_client(printer_id)
  3360. if not client:
  3361. raise HTTPException(400, "Printer not connected")
  3362. from backend.app.services.printer_manager import is_bed_slinger
  3363. gcode_distance = -distance if is_bed_slinger(printer.model) else distance
  3364. # Bare relative move — exactly what the touchscreen sends. Never touch M211
  3365. # (#2579): the firmware keeps its soft endstops on by default and clamps the
  3366. # move at the travel limit.
  3367. lines = ["G91", f"G1 Z{gcode_distance:.2f} F600", "G90"]
  3368. if not client.send_gcode("\n".join(lines)):
  3369. raise HTTPException(500, "Failed to send bed-jog command")
  3370. return {"success": True, "message": f"Bed jog {distance:+.1f} mm sent"}
  3371. @router.post("/{printer_id}/xy-jog")
  3372. async def xy_jog(
  3373. printer_id: int,
  3374. x: float = Query(0, description="Signed relative X movement in mm"),
  3375. y: float = Query(0, description="Signed relative Y movement in mm"),
  3376. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3377. db: AsyncSession = Depends(get_db),
  3378. ):
  3379. """Move the toolhead by a relative X/Y distance."""
  3380. if (x == 0 and y == 0) or abs(x) > 200 or abs(y) > 200:
  3381. raise HTTPException(400, "X/Y movement must be non-zero and ≤ 200 mm per axis")
  3382. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3383. printer = result.scalar_one_or_none()
  3384. if not printer:
  3385. raise HTTPException(404, "Printer not found")
  3386. client = printer_manager.get_client(printer_id)
  3387. if not client:
  3388. raise HTTPException(400, "Printer not connected")
  3389. axes = []
  3390. if x:
  3391. axes.append(f"X{x:.2f}")
  3392. if y:
  3393. axes.append(f"Y{y:.2f}")
  3394. # Bare relative move — never touch M211 (#2579). The firmware keeps its soft
  3395. # endstops on by default and clamps the move at the travel limit; a printer
  3396. # left disabled by an older build is recovered with a power cycle.
  3397. if not client.send_gcode("\n".join(["G91", f"G1 {' '.join(axes)} F6000", "G90"])):
  3398. raise HTTPException(500, "Failed to send XY jog command")
  3399. return {"success": True, "message": f"XY jog X{x:+.1f} Y{y:+.1f} mm sent"}
  3400. @router.post("/{printer_id}/extruder-jog")
  3401. async def extruder_jog(
  3402. printer_id: int,
  3403. distance: float = Query(
  3404. ..., description="Signed relative extrusion distance in mm. Positive extrudes, negative retracts."
  3405. ),
  3406. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3407. db: AsyncSession = Depends(get_db),
  3408. ):
  3409. """Extrude or retract filament by a relative distance.
  3410. No client-side cold-extrude guard: Bambu firmware refuses extrusion
  3411. below its min-extrude temperature, so a cold call is rejected at the
  3412. printer, not silently damaging the extruder gear.
  3413. """
  3414. if distance == 0 or abs(distance) > 100:
  3415. raise HTTPException(400, "Extruder movement must be non-zero and ≤ 100 mm")
  3416. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3417. printer = result.scalar_one_or_none()
  3418. if not printer:
  3419. raise HTTPException(404, "Printer not found")
  3420. client = printer_manager.get_client(printer_id)
  3421. if not client:
  3422. raise HTTPException(400, "Printer not connected")
  3423. if not client.send_gcode("\n".join(["M83", f"G1 E{distance:.2f} F300", "M82"])):
  3424. raise HTTPException(500, "Failed to send extruder jog command")
  3425. return {"success": True, "message": f"Extruder jog {distance:+.1f} mm sent"}
  3426. @router.post("/{printer_id}/home-axes")
  3427. async def home_axes(
  3428. printer_id: int,
  3429. axes: str = Query(
  3430. "all",
  3431. description="Legacy; accepted values are 'z' | 'xy' | 'all'. Always runs the printer's full auto-home sequence — see below.",
  3432. ),
  3433. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3434. db: AsyncSession = Depends(get_db),
  3435. ):
  3436. """Run the printer's full auto-home sequence via bare `G28`.
  3437. Bambu printers (H2C / H2D / H2S / X1 family) home the Z axis by moving
  3438. the BED UP toward an endstop at the top of travel. If the toolhead is
  3439. not already parked out of the way, a bare `G28 Z` will crash the bed
  3440. into the toolhead — #1052 reported exactly that on H2C: the bed rose
  3441. without stopping at a safe height because `G28 Z` skipped the
  3442. toolhead-park step that a full `G28` runs first.
  3443. The endpoint therefore ignores the `axes` argument and always sends a
  3444. bare `G28`, which the firmware expands into a safe multi-step sequence
  3445. (park toolhead → home XY → home Z). The argument is kept only for
  3446. backward-compat with existing clients; sending an invalid value still
  3447. returns 400 so typos surface instead of silently proceeding.
  3448. """
  3449. axes = axes.lower()
  3450. if axes not in ("z", "xy", "all"):
  3451. raise HTTPException(400, "axes must be 'z', 'xy', or 'all'")
  3452. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3453. printer = result.scalar_one_or_none()
  3454. if not printer:
  3455. raise HTTPException(404, "Printer not found")
  3456. client = printer_manager.get_client(printer_id)
  3457. if not client:
  3458. raise HTTPException(400, "Printer not connected")
  3459. if not client.send_gcode("G28"):
  3460. raise HTTPException(500, "Failed to send home command")
  3461. return {"success": True, "message": "Full auto-home sequence sent"}
  3462. @router.post("/{printer_id}/hms/clear")
  3463. async def clear_hms_errors(
  3464. printer_id: int,
  3465. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3466. db: AsyncSession = Depends(get_db),
  3467. ):
  3468. """Clear HMS/print errors on the printer."""
  3469. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3470. printer = result.scalar_one_or_none()
  3471. if not printer:
  3472. raise HTTPException(404, "Printer not found")
  3473. client = printer_manager.get_client(printer_id)
  3474. if not client:
  3475. raise HTTPException(400, "Printer not connected")
  3476. success = client.clear_hms_errors()
  3477. if not success:
  3478. raise HTTPException(500, "Failed to clear HMS errors")
  3479. return {"success": True, "message": "HMS errors cleared"}
  3480. @router.get("/{printer_id}/print/objects")
  3481. async def get_printable_objects(
  3482. printer_id: int,
  3483. reload: bool = False,
  3484. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  3485. db: AsyncSession = Depends(get_db),
  3486. ):
  3487. """Get the list of printable objects for the current print.
  3488. Returns a list of objects with id, name, position (if available), and skip status.
  3489. Objects that have already been skipped are marked in the skipped_objects list.
  3490. Args:
  3491. reload: If True, reload objects from the archive file (useful after restart)
  3492. """
  3493. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3494. printer = result.scalar_one_or_none()
  3495. if not printer:
  3496. raise HTTPException(404, "Printer not found")
  3497. client = printer_manager.get_client(printer_id)
  3498. if not client:
  3499. raise HTTPException(400, "Printer not connected")
  3500. # Reload objects from 3MF if requested or no objects loaded
  3501. if reload or not client.state.printable_objects:
  3502. # The archive of a running print normally holds the very file the
  3503. # printer is executing, so ask the disk before asking the printer:
  3504. # the fan-out below pulls the whole 3MF over FTPS from a machine that
  3505. # is mid-print — 15 MB on the print this was written for — and on a
  3506. # printer that kept the file on internal storage it cannot succeed at
  3507. # all. skipped_objects is deliberately left alone: a reload is
  3508. # not a new print, and the list of what the user already skipped only
  3509. # lives here.
  3510. from backend.app.models.archive import PrintArchive
  3511. from backend.app.services.archive import extract_printable_objects_from_archive
  3512. subtask_id = str(getattr(client.state, "subtask_id", "") or "").strip()
  3513. if subtask_id not in ("", "0"):
  3514. archive = await db.scalar(
  3515. select(PrintArchive)
  3516. .where(
  3517. PrintArchive.printer_id == printer_id,
  3518. PrintArchive.status == "printing",
  3519. PrintArchive.subtask_id == subtask_id,
  3520. )
  3521. .order_by(PrintArchive.created_at.desc())
  3522. .limit(1)
  3523. )
  3524. if archive is not None:
  3525. objects, bbox_all = extract_printable_objects_from_archive(
  3526. settings.base_dir / archive.file_path,
  3527. plate_number=resolve_plate_id(client.state),
  3528. )
  3529. if objects:
  3530. client.state.printable_objects = objects
  3531. client.state.printable_objects_bbox_all = bbox_all
  3532. logger.info(
  3533. "Reloaded %s objects for printer %s from archive %s",
  3534. len(objects),
  3535. printer_id,
  3536. archive.id,
  3537. )
  3538. # Only when the disk could not answer: a `reload=true` that the archive
  3539. # satisfied has already refreshed from the file the printer is running.
  3540. if not client.state.printable_objects:
  3541. subtask_name = client.state.subtask_name
  3542. if subtask_name:
  3543. from backend.app.services.archive import extract_printable_objects_from_3mf
  3544. from backend.app.services.bambu_ftp import download_file_try_paths_async
  3545. # Build possible 3MF filenames (try both .gcode.3mf and .3mf)
  3546. possible_filenames = []
  3547. if subtask_name.endswith(".3mf"):
  3548. possible_filenames.append(subtask_name)
  3549. else:
  3550. possible_filenames.append(f"{subtask_name}.gcode.3mf")
  3551. possible_filenames.append(f"{subtask_name}.3mf")
  3552. # Also try with spaces converted to underscores (Bambu Studio may normalize filenames)
  3553. if " " in subtask_name:
  3554. normalized = subtask_name.replace(" ", "_")
  3555. if normalized.endswith(".3mf"):
  3556. possible_filenames.append(normalized)
  3557. else:
  3558. possible_filenames.append(f"{normalized}.gcode.3mf")
  3559. possible_filenames.append(f"{normalized}.3mf")
  3560. # Download 3MF from printer
  3561. temp_path = settings.archive_dir / "temp" / f"objects_{printer_id}_{possible_filenames[0]}"
  3562. temp_path.parent.mkdir(parents=True, exist_ok=True)
  3563. # Build list of all remote paths to try
  3564. remote_paths = []
  3565. for filename in possible_filenames:
  3566. remote_paths.extend([f"/{filename}", f"/cache/{filename}", f"/model/{filename}"])
  3567. try:
  3568. downloaded = await download_file_try_paths_async(
  3569. printer.ip_address,
  3570. printer.access_code,
  3571. remote_paths,
  3572. temp_path,
  3573. printer_model=printer.model,
  3574. )
  3575. if downloaded and temp_path.exists():
  3576. with open(temp_path, "rb") as f:
  3577. data = f.read()
  3578. # Scope to the running plate: an all-plates 3MF lists every
  3579. # plate's objects, and offering plate 1's while the printer
  3580. # runs plate 2 makes every skip a misfire (#2522).
  3581. objects, bbox_all = extract_printable_objects_from_3mf(
  3582. data,
  3583. plate_number=resolve_plate_id(client.state),
  3584. include_positions=True,
  3585. )
  3586. if objects:
  3587. client.state.printable_objects = objects
  3588. client.state.printable_objects_bbox_all = bbox_all
  3589. logger.info("Reloaded %s objects for printer %s", len(objects), printer_id)
  3590. except Exception as e:
  3591. logger.debug("Failed to reload objects from printer: %s", e)
  3592. finally:
  3593. if temp_path.exists():
  3594. temp_path.unlink()
  3595. # Return objects with their skip status and position data
  3596. objects = []
  3597. for obj_id, obj_data in client.state.printable_objects.items():
  3598. # Handle both old format (string name) and new format (dict with name, x, y)
  3599. if isinstance(obj_data, dict):
  3600. obj_entry = {
  3601. "id": obj_id,
  3602. "name": obj_data.get("name", f"Object {obj_id}"),
  3603. "x": obj_data.get("x"),
  3604. "y": obj_data.get("y"),
  3605. "skipped": obj_id in client.state.skipped_objects,
  3606. }
  3607. else:
  3608. # Legacy format: obj_data is just the name string
  3609. obj_entry = {
  3610. "id": obj_id,
  3611. "name": obj_data,
  3612. "x": None,
  3613. "y": None,
  3614. "skipped": obj_id in client.state.skipped_objects,
  3615. }
  3616. objects.append(obj_entry)
  3617. return {
  3618. "objects": objects,
  3619. "total": len(objects),
  3620. "skipped_count": len(client.state.skipped_objects),
  3621. "is_printing": client.state.state in ("RUNNING", "PAUSE"),
  3622. "bbox_all": getattr(client.state, "printable_objects_bbox_all", None),
  3623. }
  3624. @router.post("/{printer_id}/print/skip-objects")
  3625. async def skip_objects(
  3626. printer_id: int,
  3627. object_ids: list[int],
  3628. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3629. db: AsyncSession = Depends(get_db),
  3630. ):
  3631. """Skip specific objects during the current print.
  3632. Args:
  3633. object_ids: List of object identify_id values to skip
  3634. """
  3635. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3636. printer = result.scalar_one_or_none()
  3637. if not printer:
  3638. raise HTTPException(404, "Printer not found")
  3639. client = printer_manager.get_client(printer_id)
  3640. if not client:
  3641. raise HTTPException(400, "Printer not connected")
  3642. if not object_ids:
  3643. raise HTTPException(400, "No object IDs provided")
  3644. # Validate object IDs exist in printable_objects
  3645. invalid_ids = [oid for oid in object_ids if oid not in client.state.printable_objects]
  3646. if invalid_ids:
  3647. raise HTTPException(400, f"Invalid object IDs: {invalid_ids}")
  3648. success = client.skip_objects(object_ids)
  3649. if not success:
  3650. raise HTTPException(500, "Failed to skip objects")
  3651. # Get names of skipped objects for response (handle both old and new format)
  3652. skipped_names = []
  3653. for oid in object_ids:
  3654. obj_data = client.state.printable_objects.get(oid, str(oid))
  3655. if isinstance(obj_data, dict):
  3656. skipped_names.append(obj_data.get("name", str(oid)))
  3657. else:
  3658. skipped_names.append(obj_data)
  3659. return {
  3660. "success": True,
  3661. "message": f"Skipped {len(object_ids)} object(s): {', '.join(skipped_names)}",
  3662. "skipped_objects": object_ids,
  3663. }
  3664. # =============================================================================
  3665. # AMS Control Endpoints
  3666. # =============================================================================
  3667. @router.post("/{printer_id}/ams/{ams_id}/slot/{slot_id}/refresh")
  3668. async def refresh_ams_slot(
  3669. printer_id: int,
  3670. ams_id: int,
  3671. slot_id: int,
  3672. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_AMS_RFID),
  3673. db: AsyncSession = Depends(get_db),
  3674. ):
  3675. """Re-read RFID for an AMS slot (triggers filament info refresh)."""
  3676. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3677. printer = result.scalar_one_or_none()
  3678. if not printer:
  3679. raise HTTPException(404, "Printer not found")
  3680. client = printer_manager.get_client(printer_id)
  3681. if not client:
  3682. raise HTTPException(400, "Printer not connected")
  3683. success, message = client.ams_refresh_tray(ams_id, slot_id)
  3684. if not success:
  3685. raise HTTPException(400, message)
  3686. # Apply PA profile after delay (RFID re-read takes a few seconds)
  3687. spawn_background_task(
  3688. _apply_pa_after_refresh(printer_id, ams_id, slot_id),
  3689. name=f"apply-pa-after-refresh-{printer_id}-{ams_id}-{slot_id}",
  3690. )
  3691. return {"success": True, "message": message}
  3692. async def _apply_pa_after_refresh(printer_id: int, ams_id: int, slot_id: int):
  3693. """Apply PA profile after RFID re-read completes.
  3694. Waits for the printer to finish processing the RFID data, then selects
  3695. the K-profile via extrusion_cali_sel. Does NOT re-send ams_set_filament_setting
  3696. because that would overwrite the RFID-provided filament data.
  3697. """
  3698. await asyncio.sleep(5)
  3699. try:
  3700. from backend.app.api.routes.inventory import _find_tray_in_ams_data
  3701. from backend.app.core.database import async_session
  3702. from backend.app.models.spool import Spool
  3703. from backend.app.models.spool_assignment import SpoolAssignment as SA
  3704. from backend.app.models.spoolman_k_profile import SpoolmanKProfile
  3705. from backend.app.models.spoolman_slot_assignment import SpoolmanSlotAssignment
  3706. from backend.app.services.spool_tag_matcher import (
  3707. ZERO_TAG_UID,
  3708. ZERO_TRAY_UUID,
  3709. is_bambu_tag,
  3710. )
  3711. from backend.app.utils.tag_normalization import (
  3712. normalize_tag_uid,
  3713. normalize_tray_uuid,
  3714. )
  3715. client = printer_manager.get_client(printer_id)
  3716. if not client:
  3717. return
  3718. state = printer_manager.get_status(printer_id)
  3719. if not state or not state.raw_data:
  3720. return
  3721. # Find current tray data (should have RFID data by now)
  3722. ams_data = state.raw_data.get("ams", {})
  3723. ams_list = (
  3724. ams_data.get("ams", []) if isinstance(ams_data, dict) else ams_data if isinstance(ams_data, list) else []
  3725. )
  3726. tray = _find_tray_in_ams_data(ams_list, ams_id, slot_id)
  3727. if not tray or not tray.get("tray_type"):
  3728. logger.debug("PA re-apply: no tray data for AMS%d-T%d", ams_id, slot_id)
  3729. return
  3730. tag_uid = tray.get("tag_uid", "")
  3731. tray_uuid = tray.get("tray_uuid", "")
  3732. tray_info_idx = tray.get("tray_info_idx", "")
  3733. if not is_bambu_tag(tag_uid, tray_uuid, tray_info_idx):
  3734. return
  3735. # Compute nozzle/extruder once — used by both local and Spoolman lookup.
  3736. # Shared with every other slot-configuring path (services.slot_nozzle),
  3737. # so the diameter this cascade filters on is the one the slot's own
  3738. # hotend actually has.
  3739. slot_nozzle = resolve_slot_nozzle(state, ams_id, slot_id, printer_manager.get_model(printer_id))
  3740. nozzle_diameter = slot_nozzle.diameter
  3741. resolved_extruder = slot_nozzle.extruder
  3742. # 3-stage K-profile cascade: local SpoolKProfile → Spoolman SpoolmanKProfile
  3743. # → live tray.cali_idx fallback. Pre-Phase-13 only handled the local path
  3744. # and exited silently if no SpoolKProfile match; Spoolman-assigned slots
  3745. # were ignored entirely and live cali_idx was never re-asserted.
  3746. matching_cali_idx: int | None = None
  3747. matching_filament_id: str = tray_info_idx
  3748. async with async_session() as db:
  3749. from sqlalchemy import or_, select as sa_select
  3750. from sqlalchemy.orm import selectinload
  3751. # Stage 1: local SpoolAssignment + SpoolKProfile match
  3752. result = await db.execute(
  3753. sa_select(SA)
  3754. .options(selectinload(SA.spool).selectinload(Spool.k_profiles))
  3755. .where(SA.printer_id == printer_id, SA.ams_id == ams_id, SA.tray_id == slot_id)
  3756. )
  3757. assignment = result.scalar_one_or_none()
  3758. spool: Spool | None = assignment.spool if assignment else None
  3759. # Stage 1b: tag-based fallback. The slot may have just been reset
  3760. # (SpoolAssignment row deleted) before the user triggered a re-read.
  3761. # The live tray already carries the spool's tray_uuid/tag_uid from
  3762. # the RFID re-read, but the SA row hasn't been re-created yet.
  3763. # Without this fallback we miss the stored SpoolKProfile and Stage 3
  3764. # ends up re-asserting whatever cali_idx the firmware reset to
  3765. # (typically the default profile).
  3766. if spool is None:
  3767. norm_uuid = normalize_tray_uuid(tray_uuid) if tray_uuid else ""
  3768. norm_tag = normalize_tag_uid(tag_uid) if tag_uid else ""
  3769. tag_filters = []
  3770. if norm_uuid and norm_uuid != ZERO_TRAY_UUID:
  3771. tag_filters.append(Spool.tray_uuid == norm_uuid)
  3772. if norm_tag and norm_tag != ZERO_TAG_UID:
  3773. tag_filters.append(Spool.tag_uid == norm_tag)
  3774. if tag_filters:
  3775. tag_lookup = await db.execute(
  3776. select(Spool).options(selectinload(Spool.k_profiles)).where(or_(*tag_filters)).limit(1)
  3777. )
  3778. spool = tag_lookup.scalar_one_or_none()
  3779. if spool is not None:
  3780. logger.info(
  3781. "PA re-apply AMS%d-T%d: matched spool %d via tag fallback "
  3782. "(SpoolAssignment row missing, likely after slot reset)",
  3783. ams_id,
  3784. slot_id,
  3785. spool.id,
  3786. )
  3787. if spool is not None and spool.k_profiles:
  3788. # Prefer exact extruder match, fall back to extruder-agnostic kp
  3789. # for the same printer + nozzle. Hard-skipping on extruder
  3790. # mismatch made the cascade refuse perfectly valid stored
  3791. # profiles whenever the AMS-extruder mapping had shifted since
  3792. # calibration time, falling all the way through to Stage 3 and
  3793. # re-asserting the firmware default.
  3794. exact_kp = None
  3795. fallback_kp = None
  3796. for kp in spool.k_profiles:
  3797. if not slot_nozzle.flow_matches(kp.nozzle_type):
  3798. continue
  3799. if kp.printer_id != printer_id or kp.nozzle_diameter != nozzle_diameter or kp.cali_idx is None:
  3800. continue
  3801. if resolved_extruder is not None and kp.extruder is not None and kp.extruder == resolved_extruder:
  3802. exact_kp = kp
  3803. break
  3804. if fallback_kp is None:
  3805. fallback_kp = kp
  3806. chosen_kp = exact_kp or fallback_kp
  3807. if chosen_kp is not None:
  3808. matching_cali_idx = chosen_kp.cali_idx
  3809. # The filament_id in extrusion_cali_sel must match the preset
  3810. # under which the K-profile was calibrated. Prefer the spool's
  3811. # slicer_filament setting, falling back to the tray's RFID value.
  3812. matching_filament_id = spool.slicer_filament or tray_info_idx
  3813. # Stage 2: Spoolman SpoolmanSlotAssignment + SpoolmanKProfile match
  3814. # (only when no local spool was matched — local takes priority,
  3815. # including the tag-based fallback above)
  3816. if matching_cali_idx is None and spool is None:
  3817. sm_result = await db.execute(
  3818. select(SpoolmanSlotAssignment).where(
  3819. SpoolmanSlotAssignment.printer_id == printer_id,
  3820. SpoolmanSlotAssignment.ams_id == ams_id,
  3821. SpoolmanSlotAssignment.tray_id == slot_id,
  3822. )
  3823. )
  3824. sm_assignment = sm_result.scalar_one_or_none()
  3825. if sm_assignment:
  3826. kp_result = await db.execute(
  3827. sa_select(SpoolmanKProfile).where(
  3828. SpoolmanKProfile.spoolman_spool_id == sm_assignment.spoolman_spool_id,
  3829. SpoolmanKProfile.printer_id == printer_id,
  3830. )
  3831. )
  3832. for kp in kp_result.scalars().all():
  3833. if kp.nozzle_diameter == nozzle_diameter:
  3834. if (
  3835. resolved_extruder is not None
  3836. and kp.extruder is not None
  3837. and kp.extruder != resolved_extruder
  3838. ):
  3839. continue
  3840. if kp.cali_idx is not None:
  3841. matching_cali_idx = kp.cali_idx
  3842. # Spoolman has no slicer_filament — use the tray's RFID value
  3843. matching_filament_id = tray_info_idx
  3844. break
  3845. # Stage 3: live tray.cali_idx fallback. Re-asserts the printer's current
  3846. # selection so the value sticks across the RFID re-read (otherwise some
  3847. # firmwares clear cali_idx back to -1 mid-cycle).
  3848. if matching_cali_idx is None:
  3849. live_cali_idx = tray.get("cali_idx")
  3850. if live_cali_idx is not None and live_cali_idx >= 0:
  3851. matching_cali_idx = live_cali_idx
  3852. if matching_cali_idx is None:
  3853. logger.debug(
  3854. "PA re-apply AMS%d-T%d: no stored or live cali_idx — skipping MQTT",
  3855. ams_id,
  3856. slot_id,
  3857. )
  3858. return
  3859. logger.info(
  3860. "PA re-apply AMS%d-T%d: cali_idx=%d, filament_id=%s",
  3861. ams_id,
  3862. slot_id,
  3863. matching_cali_idx,
  3864. matching_filament_id,
  3865. )
  3866. # NOTE: Do NOT send ams_set_filament_setting here — it tells the firmware
  3867. # "this is a manual config" which destroys the RFID-detected spool state
  3868. # (changes eye icon to pen icon in slicer).
  3869. client.extrusion_cali_sel(
  3870. ams_id=ams_id,
  3871. tray_id=slot_id,
  3872. cali_idx=matching_cali_idx,
  3873. filament_id=matching_filament_id,
  3874. nozzle_diameter=nozzle_diameter,
  3875. )
  3876. # NOTE: Do NOT send extrusion_cali_set here. extrusion_cali_sel already
  3877. # selected the correct profile by cali_idx. Sending extrusion_cali_set with
  3878. # the same cali_idx would MODIFY the existing profile's metadata (extruder_id,
  3879. # nozzle_id, name), corrupting it.
  3880. logger.info(
  3881. "Applied PA profile cali_idx=%d to printer %d AMS%d-T%d",
  3882. matching_cali_idx,
  3883. printer_id,
  3884. ams_id,
  3885. slot_id,
  3886. )
  3887. except Exception as e:
  3888. logger.warning("Failed to apply PA profile after RFID re-read: %s", e)
  3889. # 24-27 are the A2L AMS-Lite slots (normalised unit 6 = 6*4+slot); see
  3890. # a2l-am-unit-16. They are valid global tray ids alongside the regular 0-15.
  3891. _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)"
  3892. def _is_valid_load_tray_id(tray_id: int) -> bool:
  3893. """Whether ``tray_id`` names a slot the load/unload commands can address."""
  3894. return tray_id in range(16) or tray_id in range(24, 28) or tray_id in (254, 255)
  3895. @router.post("/{printer_id}/ams/load")
  3896. async def ams_load(
  3897. printer_id: int,
  3898. tray_id: int = Query(..., description="Tray ID: 0-15 for AMS slots (ams_id*4+slot_id), 254 for external spool"),
  3899. extruder_id: int | None = Query(
  3900. None,
  3901. ge=0,
  3902. le=1,
  3903. description=(
  3904. "Hotend to feed: 0 = right/main, 1 = left/deputy. Only meaningful "
  3905. "on a printer with a Filament Track Switch fitted, where the AMS is "
  3906. "bound to a switch inlet rather than a hotend and the firmware "
  3907. "cannot work the target out for itself. Omit on every other printer "
  3908. "— the field is absent from BambuStudio's own command there too."
  3909. ),
  3910. ),
  3911. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3912. db: AsyncSession = Depends(get_db),
  3913. ):
  3914. """Load filament from a specific AMS slot or external spool.
  3915. Tray ID encoding (matches Bambu firmware convention):
  3916. - 0..15: AMS slot, computed as ams_id * 4 + slot_id
  3917. - 254: external spool (single-external printers, or Ext-L on dual-nozzle H2D)
  3918. - 255: Ext-R on dual-nozzle H2D
  3919. """
  3920. if not _is_valid_load_tray_id(tray_id):
  3921. raise HTTPException(400, _LOAD_TRAY_ID_ERROR)
  3922. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3923. printer = result.scalar_one_or_none()
  3924. if not printer:
  3925. raise HTTPException(404, "Printer not found")
  3926. client = printer_manager.get_client(printer_id)
  3927. if not client:
  3928. raise HTTPException(400, "Printer not connected")
  3929. success = client.ams_load_filament(tray_id, extruder_id=extruder_id)
  3930. if not success:
  3931. raise HTTPException(500, "Failed to send load command")
  3932. if tray_id == 254:
  3933. target = "external spool"
  3934. elif tray_id == 255:
  3935. target = "Ext-R"
  3936. else:
  3937. target = f"AMS {tray_id // 4} slot {tray_id % 4 + 1}"
  3938. return {"success": True, "message": f"Loading filament from {target}"}
  3939. @router.post("/{printer_id}/ams/unload")
  3940. async def ams_unload(
  3941. printer_id: int,
  3942. tray_id: int | None = Query(
  3943. None,
  3944. description=(
  3945. "Tray ID of the slot to unload, same encoding as the load endpoint. "
  3946. "Identifies which hotend to unload on a dual-nozzle printer, where "
  3947. "both can hold filament at once and the printer's single tray_now "
  3948. "field names only one of them. Omit to unload whatever tray_now "
  3949. "names, which is the only option a single-nozzle printer has."
  3950. ),
  3951. ),
  3952. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  3953. db: AsyncSession = Depends(get_db),
  3954. ):
  3955. """Unload the filament in a given slot, or the currently loaded one."""
  3956. if tray_id is not None and not _is_valid_load_tray_id(tray_id):
  3957. raise HTTPException(400, _LOAD_TRAY_ID_ERROR)
  3958. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3959. printer = result.scalar_one_or_none()
  3960. if not printer:
  3961. raise HTTPException(404, "Printer not found")
  3962. client = printer_manager.get_client(printer_id)
  3963. if not client:
  3964. raise HTTPException(400, "Printer not connected")
  3965. success = client.ams_unload_filament(tray_id)
  3966. if not success:
  3967. # A named slot that no hotend is fed from is a no-op, not a fault: the
  3968. # menu is per-slot and the operator may well have clicked one that is
  3969. # not loaded. Say so instead of returning a 500 they cannot act on.
  3970. if tray_id is not None:
  3971. raise HTTPException(409, "No hotend is loaded from that slot")
  3972. raise HTTPException(500, "Failed to send unload command")
  3973. return {"success": True, "message": "Unloading filament"}
  3974. @router.get("/{printer_id}/runtime-debug")
  3975. async def get_runtime_debug(
  3976. printer_id: int,
  3977. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_READ),
  3978. db: AsyncSession = Depends(get_db),
  3979. ):
  3980. """Debug endpoint: Get runtime tracking status for a printer."""
  3981. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  3982. printer = result.scalar_one_or_none()
  3983. if not printer:
  3984. raise HTTPException(404, "Printer not found")
  3985. state = printer_manager.get_status(printer_id)
  3986. return {
  3987. "printer_name": printer.name,
  3988. "runtime_seconds": printer.runtime_seconds,
  3989. "runtime_hours": printer.runtime_seconds / 3600.0 if printer.runtime_seconds else 0,
  3990. "print_hours_offset": printer.print_hours_offset,
  3991. "total_hours": (printer.runtime_seconds / 3600.0 if printer.runtime_seconds else 0)
  3992. + (printer.print_hours_offset or 0),
  3993. "last_runtime_update": printer.last_runtime_update.isoformat() if printer.last_runtime_update else None,
  3994. "mqtt_state": {
  3995. "connected": state.connected if state else False,
  3996. "state": state.state if state else None,
  3997. "progress": state.progress if state else None,
  3998. "gcode_file": state.gcode_file if state else None,
  3999. }
  4000. if state
  4001. else None,
  4002. "is_active": printer.is_active,
  4003. }
  4004. @router.post("/{printer_id}/hms/execute-action")
  4005. async def execute_hms_action(
  4006. printer_id: int,
  4007. body: HmsActionBody,
  4008. _=RequirePermissionIfAuthEnabled(Permission.PRINTERS_CONTROL),
  4009. db: AsyncSession = Depends(get_db),
  4010. ):
  4011. """Execute an HMS action on the printer."""
  4012. result = await db.execute(select(Printer).where(Printer.id == printer_id))
  4013. printer = result.scalar_one_or_none()
  4014. if not printer:
  4015. raise HTTPException(404, "Printer not found")
  4016. client = printer_manager.get_client(printer_id)
  4017. if not client:
  4018. raise HTTPException(400, "Printer not connected")
  4019. # Snapshot pre-state so we can verify the printer actually acted on the
  4020. # command. publish() success is NOT the same as printer-ack: Bambu's
  4021. # firmware silently rejects malformed HMS commands at QoS 1 (the broker
  4022. # ACKs the publish, but the printer drops it). Verified end-to-end against
  4023. # a live H2D — see #1830 §(3).
  4024. #
  4025. # We probe `_last_message_time` (bumped on every MQTT push) rather than a
  4026. # (gcode_state, hms_errors-length) diff. The old diff missed the
  4027. # wrong-plate IGNORE_RESUME case where the printer briefly resumes and
  4028. # re-pauses with the same fault inside the 2.5s window: both fields
  4029. # round-trip to their pre-publish values → false 502 even though the
  4030. # firmware fully ack'd the resume. Every accepted command triggers a
  4031. # pushall response within ~100-500ms, so a fresh inbound message after
  4032. # the publish is the robust ack signal.
  4033. pre_last_message = client._last_message_time
  4034. success = client.execute_hms_action(body.print_error, body.action, body.job_id)
  4035. if not success:
  4036. raise HTTPException(400, "Failed to execute HMS action")
  4037. # Give the printer time to push a state update. The dispatch helper already
  4038. # publishes a pushall after every command, so a fresh status should arrive
  4039. # within ~1s; the default 2.5s covers slower firmware variants without
  4040. # making the UI feel hung. Plain sleep is fine — paho's MQTT callback
  4041. # runs in its own thread and updates state regardless of whether this
  4042. # coroutine is awaiting.
  4043. await asyncio.sleep(HMS_ACTION_ACK_WAIT_SECONDS)
  4044. acked = client._last_message_time > pre_last_message
  4045. if not acked:
  4046. # Publish succeeded but the printer sent nothing back. Almost always
  4047. # firmware-side silent rejection (err mismatch, command/state mismatch)
  4048. # or a dropped MQTT route. 502 makes it visible at the UI instead of
  4049. # the 200-but-broken loop #1830 reported.
  4050. raise HTTPException(502, "Printer did not acknowledge HMS action within 2.5s")
  4051. return {"success": True, "message": "HMS action executed"}