printers.py 176 KB

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