printers.py 163 KB

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