printers.py 194 KB

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