printers.py 166 KB

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