printers.py 149 KB

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