printers.py 204 KB

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