printers.py 168 KB

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