printers.py 148 KB

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