printers.py 182 KB

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