printers.py 183 KB

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