printers.py 159 KB

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