printers.py 167 KB

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