printers.py 193 KB

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