printers.py 151 KB

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