printers.py 202 KB

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