printers.py 167 KB

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